<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Onyi Lam on Medium]]></title>
        <description><![CDATA[Stories by Onyi Lam on Medium]]></description>
        <link>https://medium.com/@onyilam?source=rss-96b16f7a5201------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*zYYvgucmq1WUPmcS.jpg</url>
            <title>Stories by Onyi Lam on Medium</title>
            <link>https://medium.com/@onyilam?source=rss-96b16f7a5201------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 08:06:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@onyilam/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Got GAM? a flexible modeling approach that preserves interpretability]]></title>
            <link>https://medium.com/data-science/gam-a-flexible-modeling-approach-that-preserves-interpretability-a68a4f235b6e?source=rss-96b16f7a5201------2</link>
            <guid isPermaLink="false">https://medium.com/p/a68a4f235b6e</guid>
            <category><![CDATA[gam]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[interpretable-ai]]></category>
            <dc:creator><![CDATA[Onyi Lam]]></dc:creator>
            <pubDate>Thu, 09 Jul 2020 17:35:42 GMT</pubDate>
            <atom:updated>2020-07-09T19:24:18.341Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*brR3hColEjY9Mq2U0wjIig.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@pieterpanflute">Pieter</a> on <a href="http://www.unsplash.com/">Unsplash</a></figcaption></figure><p>In many social science and business problems, it is often more important to explain why a phenomenon happens than improving the model’s predictability on the event happening. Having an interpretable model is, therefore, crucial in understanding how different factors interact with the outcome of interest.</p><p>The model’s interpretability is also important in highly regulated business environments, such as loan approval decisions. Even in situations where prediction accuracy is more important than the “why”, an interpretable model can help debug more complicated models and guide new approaches to feature engineering and data preprocessing.</p><h3>GAM — under the hood</h3><p>In this context, generalized additive models (GAM) offer a middle ground between simple models, such as those we fit with linear regression, and more sophisticated machine learning models like neural networks that usually promise superior prediction performance to simple models. GAM can also be used in various tasks: regression, classification, binary choice.</p><p>In linear regression, we model outcome y as a function of 2 inputs X₁ and X₂ with the following:</p><blockquote>y = β₁X₁ + β₂ X₂ + u</blockquote><p>In GAM, the β Xᵢ is replaced by f(Xᵢ), where f() can be any arbitrary nonlinear functions. In other words, GAM is composed of a sum of smooth functions f() on the input. The idea is still that each input feature makes a separate contribution to the response, and these just add up, but these contributions don’t have to be strictly proportional to the inputs. The beauty of this approach is that, similar to what β represents in linear regression, the partial response function f() still captures the change on outcome y to change the input. The change in prediction depends on the initial value of Xᵢ.</p><p>A common approach to deal with nonlinear relationships in regression models involves creating polynomial features. For the predictor in question, Xᵢ, we add terms e.g. quadratic (Xᵢ²), cubic (Xᵢ³), etc to get a better fit. GAM encompasses this idea but includes an additional aspect: <em>penalized estimation</em>. The idea is similar to that of a ridge or lasso regression, where penalty terms are added to help avoid overfitting.</p><p>Another way of creating transformations of a variable is to cut the variable into distinct regions, and fit those regions separately. However, the different fits could be unconnected, leading to sometimes notably different predictions for values close together. GAM allows the user to specify the number ofknots in the variable, which are used to create sections where separate cubic polynomials are fit at each section and then joined to create a continuous curve.</p><h4>So what smooth function should be used?</h4><p>A number of smooths are available with the <em>mgcv </em>package in <strong>R</strong>, and one can learn more via the help file for <strong>smooth.terms</strong> (<a href="http://www.inside-r.org/r-doc/mgcv/smooth.terms">link</a>). The default is thin plate regression splines (TPRS), which works well in general in terms of performance. Cubic spline is also a common basis that mirrors adding polynomial terms for the covariates.</p><h3>Implementing in R</h3><p>We use the mgcv package in `R` to implement gam and use a built-in dataset medcare from the package <a href="https://cran.r-project.org/web/packages/catdata/catdata.pdf">catdata</a> to illustrate gam and compare with the performance using logistic regression.</p><p>The medcare data was collected on 4406 individuals, aged 66 and over, that were covered by a public insurance program. The outcome variable is healthpoor, a binary variable that equals 1 if the individual reports poor health and 0 otherwise. We are interested in knowing how ofp, the number of physician office visits, might be correlated with health outcomes. One can hypothesize a nonlinear relationship between the two variables: a healthy individual will have few physician visits, but having more visits also allow the patients to return to be more healthy. So we are interested to have a more flexible modeling approach.</p><p>The <em>mgcv </em>treats gam as a generalized version of glm, so one can directly call thegam method to use glm methods such as linear and logistic regression.</p><pre>library(catdata)<br>library(mgcv)<br>library(Metrics)<br>library(ggplot2)<br>library(visreg)</pre><pre>data(medcare)</pre><pre>#### logit model (same as running glm with family set to &quot;binomial&quot;)<br>lm &lt;- gam(healthpoor ~ male+ age + ofp, family = binomial, data = medcare)<br>pred &lt;- predict(lm, type=&quot;response&quot;)<br>lm_auc &lt;- Metrics::auc(medcare$healthpoor, pred)<br>lm_auc</pre><pre>#### generalized additive model<br>gam &lt;- gam(healthpoor ~ male+s(age)+s(ofp), family = binomial, data = medcare)<br>pred &lt;- predict(gam, type=&quot;response&quot;)<br>gam_auc &lt;- Metrics::auc(medcare$healthpoor, pred)<br>gam_auc</pre><p>The <a href="https://stat.ethz.ch/R-manual/R-devel/library/mgcv/html/s.html">s()</a> terms in the gam formula indicate which terms are to be smoothed. There are several options you can pass on to the s() terms — for example, you can specify a different smooth function bs, and a different number of knots k.</p><p>If the number of unique values is less than the number of basis (For example, when you tried to add s() to a binary variable like male), the function would return the following error:</p><blockquote>A term has fewer unique covariate combinations than specified maximum degrees of freedom.</blockquote><p>Using visreg to visualize the fitted terms ofofp, we can see that gam produces a much more nuanced prediction of ofp while that of the logistic regression is much more linear.</p><pre>visreg(gam, &quot;ofp&quot;, jitter=TRUE, line=list(col=&quot;red&quot;),<br>       fill=list(col=&quot;green&quot;))</pre><p>The gam model also yields a slightly better AUC, 0.679, versus 0.673 of the logistic regression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*YGDkiAC_OHkTspT32pI-Xg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*Y1FUVaq5SMDC8XQvG1WbZA.png" /><figcaption>IPrediction based on ofp: gam (left), logistic regression (right). mage by Author.</figcaption></figure><h4>Interpretation</h4><p>We are ultimately interested in estimating the change in ofp on the probability of healthpoor. To do that, we need to fix the other features’ values to their mean or mode(if the feature is a categorical variable). We then create a test dataframe that has a list of possible values of ofp.</p><pre># function to get mode of an array of values<br>getmode &lt;- function(v) {<br>  uniqv &lt;- unique(v)<br>  uniqv[which.max(tabulate(match(v, uniqv)))]<br>}</pre><pre>testdata = data.frame(ofp = seq(0, 100, length = 101),<br>                      male = getmode(gam$model$male),<br>                      age = mean(gam$model$age))</pre><p>Using the predict function, we can then extrapolate the previously fitted gam model to the test data. The plot shows that ofp has a nonlinear relationship with the likelihood of reporting poor health, holding other variables constant. Furthermore, the confidence interval less tight in regions with higher ofp.</p><pre>fits = predict(gam, newdata=testdata, type=&#39;response&#39;, se=T)</pre><pre>### create a confidence interval for the fits<br>predicts = data.frame(testdata, fits) %&gt;% <br>  mutate(lower = fit - 1.96*se.fit,<br>         upper = fit + 1.96*se.fit)</pre><pre>ggplot(aes(x=ofp,y=fit), data=predicts) +<br>  geom_ribbon(aes(ymin = lower, ymax=upper), fill=&#39;gray90&#39;) +<br>  geom_line(color=&#39;#00aaff&#39;) +theme_bw()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*WlzqOr3zg-zekSOE0gnfPA.png" /><figcaption>Image by Author.</figcaption></figure><h3>References</h3><p>For more information on GAM:</p><ul><li><a href="https://m-clark.github.io/generalized-additive-models">https://m-clark.github.io/generalized-additive-models</a></li><li><a href="https://www.rdocumentation.org/packages/mgcv/versions/1.8-31/topics/gam">https://www.rdocumentation.org/packages/mgcv/versions/1.8-31/topics/gam</a></li><li><a href="https://noamross.github.io/gams-in-r-course/">https://noamross.github.io/gams-in-r-course/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a68a4f235b6e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/gam-a-flexible-modeling-approach-that-preserves-interpretability-a68a4f235b6e">Got GAM? a flexible modeling approach that preserves interpretability</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I built Jicount.com — an effort to introduce more transparency in peer review]]></title>
            <link>https://medium.com/@onyilam/why-i-built-jicount-com-an-effort-to-introduce-more-transparency-in-peer-review-f3c4d1269915?source=rss-96b16f7a5201------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3c4d1269915</guid>
            <category><![CDATA[academia]]></category>
            <category><![CDATA[peer-review]]></category>
            <dc:creator><![CDATA[Onyi Lam]]></dc:creator>
            <pubDate>Sun, 18 Aug 2019 23:36:39 GMT</pubDate>
            <atom:updated>2019-08-20T19:00:05.635Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Make Peer Review Great Again</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/0*CZeAyvq5aeuujN0U.png" /></figure><p>It is often real test of resolve for researchers to go through peer review. The grumpy and aggressive reviewer #2 often has the researchers wonder if their papers will ever find a home. And no matter how successful you are as a researcher, your papers have probably been rejected by academic journals at least once.</p><p>The process is also expensive in some disciplines: for example, it often costs around ~$100 USD to submit a paper to economics journals. After submission, it might take weeks and sometimes months before the editor of the journal arrives at a decision. During this period, researchers are not allowed to submit their papers to other journals. It is therefore not rare for a paper to wait a few years before getting published. This prolonged process could potentially affect the tenure outcome of many junior academic researchers.</p><p>For people who are less familiar with peer review, it is a process designed to be an objective assessment of the quality of the articles submission for publication, and is the best possible system for quality control the scientific community has. But despite the best intention of the referees and the editor, peer review inevitably involves a lot of arbitrariness and personal biases. Anecdotal evidence suggests that many leading journals have made mistakes such as rejecting seminal contributions or accepting mediocre submissions.</p><p>In the current system, researchers usually can’t see which papers were rejected and why. Furthermore, they can’t even see the reviews for the accepted papers at most journals. The lack of transparency means that we don’t know if potential personal biases can get in the way of what is supposed to be a merit-based process.</p><p>This is why i decided to build <a href="http://www.jicount.com/">Jicount.com</a>, a platform that allows researchers to upload milestones and activities associated with their papers. The goal of the platform is to provide a supportive space for researchers to engage with other researchers before and after the submission process. In the current version, users can upload multiple files associated with the following activities to their paper:</p><p><em>Working Paper, Presentation, Submitted, Rejected, Revise and Resubmitted, Accepted, Appeared in Journal</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NwJLjisCm1MkmAUBgXvjHg.png" /><figcaption>the timeline feature in Jicount</figcaption></figure><p>A researcher can upload slides of their presentation, working paper or an abstract associated with each activity of their paper. Since papers tend to evolve over time, a user can upload different version of their papers by adding a new activity to the timeline. This timeline design also allows a researcher to upload (multiple) referee reports associated with each submission outcome. Other researchers can read about the critiques of the reviewers and understand why the editorial decision was made. The hope is that by bringing more transparency in this process, there is more accountability in this process.</p><p>The ability for researchers to share their papers’ path to a successful placement can help other researchers, especially the those who are early in their career, to better understand the steps needed to arrive at publication. Often times, people only see the shiny line of publication in the CV of successful researchers but not the work behind. It takes both persistence and many revisions to arrive at a state ready for publication. Jicount hopes to make this process more translucent to encourage researchers to hang on, and let them know that they are not alone.</p><p>Aside from allowing users to upload their papers’ activities, users can also comment/like on other users’ papers’ activities. In my vision, researchers can get advices on the journals that are best fit for their paper. They can also give feedback on others’ papers before the article is sent out for publication, thereby increasing the chance of the paper’s chance to survive peer review and shortening the time to publication.</p><p>These advices and interactions are previously limited to smaller academic circles. The channels through which researchers can get advices are also largely dependent on face-to-face interaction — researchers usually get advices from other experienced researchers who work in the same lab or department as them, or those who happen to be in the same seminar/conference. This also means that graduate students who study at lesser known schools will not have the same advices as students who go to better known schools with more experienced professors. The current system therefore perpetuates the status quo and hampers knowledge diffusion. Jicount hopes to provide more opportunity for researchers all over the world to seek and give advices regardless of their experience level and location.</p><p>If you want to learn more about the project, or want to contribute to the project, email me (onyilam@gmail.com) or check out the <a href="https://github.com/onyilam/jikan">github repo</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3c4d1269915" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Dimensionality Reduction to Visualize Job Polarization]]></title>
            <link>https://medium.com/data-science/using-dimensionality-reduction-to-visualize-job-polarization-cf2a9ceac90e?source=rss-96b16f7a5201------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf2a9ceac90e</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[dimensionality-reduction]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[polarization]]></category>
            <category><![CDATA[economics]]></category>
            <dc:creator><![CDATA[Onyi Lam]]></dc:creator>
            <pubDate>Tue, 28 May 2019 22:47:50 GMT</pubDate>
            <atom:updated>2019-05-28T22:47:50.396Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/731/0*Ca2R8orAPuzWi4HO" /><figcaption>PC1 and PC2 extracted from the MDS Embedding using 2003 data. Each point represents a job, and each color represents a job zone. The smaller the job zone, the less education requirement/experience it requires.</figcaption></figure><p>In this post, we illustrate how dimensionality reduction techniques including principal component analysis (PCA) and multidimensional scaling (MDS) can be used to visualize polarization of work activities since 2003, using data from <a href="https://www.onetcenter.org/overview.html">O*NET</a>,a US government-sponsored website with a rich set of variables that describe work and worker characteristics.</p><p>Let’s briefly go over the data structure of O*NET to understand why using dimensionality reduction techniques could be useful. The dataset is organized around different mix of knowledge, skills, abilities and work activities that are required to perform at each job. It contains hundreds of standardized and occupation-specific variables on almost 1,000 occupations covering the entire U.S. economy.</p><p>For this analysis, we used the <a href="https://www.onetcenter.org/db_releases.html">Work Activity files </a>from 11/2003 and 8/2018 to compare how activities performed at different jobs changed in this span of 15 years. There are 41 different work activities such as “Handling and Moving Objects” and “Resolving Conflicts and Negotiating with Others”. In the file, a data value is assigned to each occupation-activity-scale combo. In general, the higher the data value, the more important is the activity to the the job. For example, in the 2018 file (shown in the screenshot below), the data value for the job “Chief Executive” to perform activity “Getting Information” using the scale “Importance” is 4.72.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/0*QULJamNo52_KDVXr" /></figure><h3>Principal Component Analysis</h3><p>In order to understand how work activities performed at different jobs have changed, one can follow each of these 41 activities separately over time for each job, but it can quickly become out of hand. PCA can help address this issue by reducing the number of activities that we need to keep track of. Specifically, it does so by transforming the data to a new coordinate system such that the first coordinate (i.e. the first principal component) represents the projection with the greatest variance of data, the second greatest variance on the second coordinate, and so on.</p><p>The following code implements PCA in python using the scikit-learn library. It does so by first standardizing the feature scale:</p><pre>from sklearn.decomposition import PCA<br>from sklearn.preprocessing import StandardScaler</pre><pre>#df is the dataframe that contains the value of each of the 41 activities for all jobs</pre><pre>x = df.loc[:, features].values<br>x = StandardScaler().fit_transform(x)</pre><pre>pca = PCA(n_components=num_dim)<br>#num_dim is the number of dimension we want to examine. We set num_dim to be 2.<br>principalComponents = pca.fit_transform(x)</pre><p>The figures below plot the principal components in the two periods. To illustrate how jobs that require different education levels differ by the work activities they do, we color-coded each job (denoted by the points on the scatter plot) by the <a href="https://www.onetonline.org/help/online/zones">job zone</a> they belong to. Education is one of the criteria in determining job zone, along with other measures such as experience and training. The higher the job zone, the more preparation the job requires. Occupations that belong to job zone 1 are jobs that sometimes require a high school diploma whereas job zone 5 occupations usually require graduate school degree.</p><p>If polarization is growing, the activities that high and low-skill group performs would be more different from each other. And this is exactly what we see when we compare the plots in this two periods. In 2018, jobs of similar color are more closely clustered together, suggesting that there is little overlap in work activities across jobs that belong to different zones. Actually doing the calculation reveals that jobs that require less preparation (those in zone 1 and 2) have a larger PC1 value in 2018 than in 2003. In 2003, jobs in zone 4 (colored in yellow), which demand relatively more education, were more scattered along the x-axis. In contrary in 2018, they mostly lied to the left of 0, which means that they are more clustered together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/0*4G08UpCFtDzc-aAg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/0*vBQ9kzGhLp1ZMZCX" /><figcaption>PC1 and PC2 using PCA, 2003 on the left, 2018 on the right</figcaption></figure><p>To examine this pattern more rigorously, we can calculate the distance between jobs in different job zones. We do so by first determining the centroid of the job zone cluster, then compute the distance between the centroids of the job zones. In 2003, the distance between job zone 1 and 5 is 5.7, and it has increased to 6.7 in 2018. Similar increase in distance also took place between job zone 1 and 4, and between job zone 2 and 5.</p><p><strong>Interpreting the Principal Components</strong></p><p>The PCs themselves do not have any substantive meaning, so in order to relate the principal components with the work activities, we can examine the standard Pearson correlations between the PCs and the work activities themselves. For the year 2003, PC1 is most strongly correlated with “Inspecting Equipment, Structures, or Material”, and other physical labor intensive activities. On the other hand, PC2 is most strongly correlated with cognitive activities such as “processing information” and “getting information”.</p><p>Note that while the top 3 activities that have the highest correlation with PC1 are the same in both 2003 and 2018, that is not the case for PC2. For PC2, “Making Decisions and Solving Problems” is present in 2018 but not in 2003, whereas “Getting Information” is present in 2003 but not in 2018. So while the two dimensions capture activities of similar nature in both periods, they are not exactly the same.</p><p>PC1 using PCA:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b460ef04cb5292b172ca7b4d469b30e/href">https://medium.com/media/7b460ef04cb5292b172ca7b4d469b30e/href</a></iframe><p>PC2 using PCA:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b773a730792b021cdef2787e7a32a53/href">https://medium.com/media/4b773a730792b021cdef2787e7a32a53/href</a></iframe><h3><strong>Multidimensional Scaling</strong></h3><p>Another method that allows researchers to visualize growing polarization across jobs is MDS. What MDS attempts to do is to preserve the the pairwise distance between the jobs while projecting the matrix into lower dimensions. The input to the MDS model is a matrix of distances between the jobs, instead of the data values for each activity-job as in the PCA. So to convert job activity data into a distance matrix such that it is suitable for MDS, we first multiply the matrix of data value by itself. The code below illustrates this step as well as the fitting of the distance matrix into its embedding:</p><pre>from sklearn.manifold import MDS</pre><pre>### multiplying the x matrix with itself<br>t = np.dot(x, np.transpose(x))<br>mds = MDS(n_components= n_dimension, max_iter=3000, eps=1e-9, random_state=12345,<br>dissimilarity=”precomputed”, n_jobs=1)<br>pos = mds.fit(t).embedding_</pre><p>After that, we can extract the first two principal components from the position of the dataset in the MDS embedding space as before:</p><pre># select the top 2 dimensions of data<br>clf = PCA(n_components=2)<br>pos = clf.fit_transform(pos)</pre><p>Similar to the PCA analysis, the first principal component in 2018 captures the more manual labor intensive activities such as “Handling and Moving Objects”. In 2003, however, the first principal component captures different type of activities from the previous PCA analysis. Instead of the manual labor intensive activities, PC1 is most correlated with more managerial activities such as “Developing Objectives and Strategies” and “Provide Consultation and Advice to Others”. This difference reveals another dimension that are not apparent from using PCA.</p><p><strong>PC1 using MDS:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fdd57a05db301e51fa027d0a62af7a1/href">https://medium.com/media/6fdd57a05db301e51fa027d0a62af7a1/href</a></iframe><p><strong>PC2 using MDS:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55ae2eff880c6a38ce62b51962381968/href">https://medium.com/media/55ae2eff880c6a38ce62b51962381968/href</a></iframe><p>The figures below show the principal components of the MDS embedding for 2003 (left) and 2018 (right). As the first impression, jobs of different colors are more mixed in with each other in 2003 than in 2018, which means that along the two main dimensions, there are more overlapping in activities across jobs belonging to different job zones. In addition, none of the jobs that belong to job zone 4 or 5 have a PC1 &lt; 0 in 2018 (All red and green dots lie on the left of 0 in PC1). These two patterns suggest that the activities that each job performs have become more separated over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/0*KJo4TaRsxShZ1Jz3" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/0*Ca2R8orAPuzWi4HO" /><figcaption>PC1 and PC2 using MDS, 2003 on the left, 2018 on the right</figcaption></figure><p>To conclude, both methods illustrate a growing polarization in work activities performed by jobs that require different levels of preparation, but they can also reveal differences in the subtleties of the data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf2a9ceac90e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/using-dimensionality-reduction-to-visualize-job-polarization-cf2a9ceac90e">Using Dimensionality Reduction to Visualize Job Polarization</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How social scientists can use transfer learning to kickstart a deep learning project]]></title>
            <link>https://medium.com/pew-research-center-decoded/how-social-scientists-can-use-transfer-learning-to-kickstart-a-deep-learning-project-fdceeb565cc5?source=rss-96b16f7a5201------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdceeb565cc5</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[transfer-learning]]></category>
            <dc:creator><![CDATA[Onyi Lam]]></dc:creator>
            <pubDate>Wed, 30 Jan 2019 20:00:32 GMT</pubDate>
            <atom:updated>2019-11-21T22:41:31.316Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>How social scientists can use transfer learning to kick-start a deep learning project</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*ky2ZIcEx2J4sGQGKfoAhqA.png" /></figure><p>Social scientists are increasingly adopting machine learning methods to analyze large amounts of text, images and other kinds of data. These methods, which include different types of <a href="https://en.wikipedia.org/wiki/Deep_learning">deep learning models</a>, allow researchers to measure important concepts and model human behavior and information flows in innovative ways. However, a lack of established best practices in this fast-changing field can make these methods difficult to implement. This post dives into Pew Research Center’s recent experience adopting a deep learning model for a project that studied <a href="http://www.pewsocialtrends.org/2018/12/17/gender-and-jobs-in-online-image-searches/">gender representation in Google Images</a>. It also describes how we used a technique called “transfer learning” to make our classification project much more manageable.</p><h3><strong>Background</strong></h3><p>The gender representation report research team was comprised of researchers with social science backgrounds, including economist Onyi Lam and political scientists Adam Hughes and Stefan Wojcik. Before this project, we’d used machine learning to conduct text analysis research, often relying on the Python library <a href="https://scikit-learn.org/stable/">scikit-learn</a>. We had almost no prior experience with deep learning. But we were interested in expanding our research to examine images since images represent a large component of online information.</p><p>We decided to explore how online image searches represent men and women in the workplace. To answer this question, we obtained a large quantity of images from Google search results for various jobs and then classified individuals who appeared in those images as male or female.</p><p>This particular project was ideally suited to machine learning because of its scope. What requires hours of manual human labor can be automated and completed in a few minutes with machine learning. And since machine learning models can scale to very large datasets, we were able to significantly expand our project’s scope. In addition to the more than 10,000 images we collected from English language Google searches in the U.S., we included over 40,000 images from searches using 17 other country-language combinations as well.</p><h3><strong>How transfer learning works</strong></h3><p>A deep learning model is composed of layers that represent different information about an object. Generally speaking, deeper neural networks with more layers are able to tackle more complicated tasks. However, this increased performance comes at a cost, since deeper neural networks need more data and time to learn a task. As a consequence, researchers training a deep learning model often need to assemble a very large set of training data and specialized computing devices to reduce time demands.</p><p>The team collected an initial <a href="http://wilmabainbridge.com/facememorability2.html">dataset</a> for training that contained over 10,000 faces and included human-coded labels for gender, race, and age, among other attributes. While that number may sound like a lot, a common dataset used for identifying objects in images called <a href="http://www.image-net.org/papers/imagenet_cvpr09.pdf">ImageNet</a> contains millions of images.</p><p>With the limited amount of data available, the team worried that training a neural network from scratch was an insurmountable task. After doing more research on neural networks, we decided to adopt an approach called transfer learning, inspired by tutorials provided by <a href="https://www.fast.ai/">fast.ai</a>, a website dedicated to machine learning education.</p><p>The core idea underlying transfer learning is that researchers can “recycle” the knowledge gained from a large, pre-trained neural network when applying it for a new task. While neural networks are often composed of many different “layers,” the lower layers of the network often contain low-level abstract information about objects in images such as lines and curves, which is useful across many image classification tasks.</p><p>Transfer learning essentially cuts the lower layers out of a pre-trained neural network and pastes them onto new, untrained layers. From there, researchers can train the neural network on a new task, — even if the new task is different from the task the pre-trained neural network was taught to do. In our case, we trained the system to recognize gender patterns, but the pretrained model was originally trained to detect over 1000 objects like banjos, birds and balloons. Many organizations provide access to pre-trained neural networks that identify objects in photos free of charge, so gaining access to an array of pre-trained neural networks was not a barrier.</p><p>Transfer learning still requires some training data, such as the particular classification decisions researchers want to estimate, but it supplements that data by relying on the collective wisdom of “pre-trained” models. The main insight is that by attaching additional layers to the backbone of a pre-trained model, the model does not need to learn low-level features and can jump right into learning our specific classification task. This makes kick-starting a new project or testing an idea much faster than if one were to train a model entirely from scratch.</p><p>In our initial attempt, we used the pre-trained ResNet-50 model from the Python library `Keras` and achieved 90% accuracy. The result was a pleasant surprise and we quickly realized the promise of this approach: it would allow us to answer our original research question with acceptable levels of predictive error. Similar deep learning libraries include <a href="https://pytorch.org/">Pytorch</a>, <a href="https://github.com/fastai">Fastai</a> and <a href="https://www.tensorflow.org/">Tensorflow</a>, which are often available in both Python and R.</p><p>The basic architecture of the transfer learning implementation, using `Keras`, appears below, where the `base_model` is the Resnet-50 pretrained model. In Keras, some of the available pre-trained models include ResNet, VGG and Inception, among others.</p><pre><strong># get output from the pre-trained model<br> x = base_model.output<br> <br> # stack additional layers on top for fine-tuning<br> x = GlobalAveragePooling2D()(x)<br> x = Dense(512, activation=’relu’)(x)<br> predictions = Dense(1, activation=’sigmoid’)(x)<br> model = Model(inputs=base_model.input, outputs=predictions)</strong></pre><p>There are still a lot of parameters in the models that need to be optimized, and different choices will yield better results depending on the application. So even with transfer learning, the best modeling choices are not immediately clear, and researchers should test different model parameters.</p><p>However, the basic idea of using pretrained models as a backbone can allow researchers to quickly decide whether the approach is worth the time. If your transfer learning model does not yield a reasonable level of performance, it might be time to think about re-collecting training data or reexamining the research design altogether.</p><p>For social scientists who are interested in more than just training a model — those who want to answer a specific research question — transfer learning offers a big advantage over training a model from scratch. Transfer learning makes it possible to get a sense of whether an idea is feasible in a matter of hours, rather than the days or weeks it might take to train a model from scratch. And since social scientists are often more interested in making aggregate estimates of populations rather than making production-ready image classifiers, they are unlikely to require true state-of-the-art performance.</p><h3><strong>Evaluating and fine-tuning the model</strong></h3><p>To evaluate the model performance, we employed both <a href="https://towardsdatascience.com/cross-validation-in-machine-learning-72924a69872f">cross-validation</a> and comparisons of model predictions with human decisions. Cross-validation involves holding back part of the labeled data from training, and human validation involves having humans label a small set of data that the model made predictions on. (We used the <a href="http://www.pewinternet.org/2016/07/11/research-in-the-crowdsourcing-age-a-case-study/">Mechanical Turk crowdsourcing service</a> to help us label thousands of faces, and three mTurkers examined each image.) We then tested the model on those labeled data and compared the model predictions with the true values.</p><p>Social scientists are often interested in making subgroup comparisons across different socio-demographic lines. One of the key criteria we imposed on the model performance was to make sure that the accuracy of the prediction had to be broadly consistent across demographic groups. Since we wanted to deploy the model to analyze a diverse set of faces, we did not want the accuracy of the result to be biased against a certain group and lead to incorrect inferences when we made cross-group comparisons.</p><p>In the first few versions of the model we noticed that its performance was noticeably worse on women’s faces when compared to men. Upon reviewing some incorrectly classified images, we noticed that the model did worse with images of darker-skin females (this issue is similar to one raised by researcher MIT Joy Buolamwini and her co-authors, who showed that <a href="http://proceedings.mlr.press/v81/buolamwini18a/buolamwini18a.pdf">off-the-shelf, commercial face recognition suffers from lower accuracy on darker- skin females</a>), as well as those of individuals wearing glasses, which suggested over-fitting of models. Over-fitting is a common problem in machine learning research and is defined as when a model learns quirks from the data instead of broader patterns associated with the task.</p><p>To address this bias, we collected an additional set of images that included specific minority groups and also ensured that certain non-gender-related facial features, such as glasses, should not be a predictive feature of the model. To do that, we queried a list of minority individuals from Google Image Search and saved the returned images as separate training datasets. Another strategy we employed to increase the diversity of our training images was to query Google Image with specific search terms that had the following format: “country” + “men/women” such as “Argentinian men” and “Iraqi women” for 100 of countries. We downloaded up to 100 images for each query and collected more than 20,000.</p><p>The final version of the model was able to achieve 95% cross-validation accuracy and 88% human-validation accuracy. Upon reviewing the misclassified images in the human-validation set, we noticed that many of them were of noticeably lower quality — the faces were often blurred or obstructed. Since our training dataset did not contain any children’s faces, the model also did worse when it comes to making predictions about children.</p><h3><strong>Parting thoughts</strong></h3><p>Deep learning is an exciting and fast-changing field with new methods emerging regularly. It might seem like a daunting task for social scientists to adopt these new tools. However, using transfer learning can lower the costs associated with some of these methods, and social scientists can use them effectively. And the same fundamental approach described in this post can be applied to different types of media, including text and audio data.</p><p>The process of building a neural network for this project highlighted some of the challenges for computational social scientists applying deep learning to research. We needed to understand how the model treated people from different demographic backgrounds in order to avoid bias in our estimates. We also needed to establish ways to test for systematic bias in the model. Every social scientist will confront their own challenges in applying these kinds of models, but deep learning tools will be useful for many researchers interested in image, audio and text data.</p><p><em>This post was written by Onyi Lam, Adam Hughes and Stefan Wojcik, who are computational social scientists focusing on data science at Pew Research Center.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdceeb565cc5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pew-research-center-decoded/how-social-scientists-can-use-transfer-learning-to-kickstart-a-deep-learning-project-fdceeb565cc5">How social scientists can use transfer learning to kickstart a deep learning project</a> was originally published in <a href="https://medium.com/pew-research-center-decoded">Pew Research Center: Decoded</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using fixed and random effects models for panel data in Python]]></title>
            <link>https://medium.com/pew-research-center-decoded/using-fixed-and-random-effects-models-for-panel-data-in-python-a795865736ab?source=rss-96b16f7a5201------2</link>
            <guid isPermaLink="false">https://medium.com/p/a795865736ab</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[econometrics]]></category>
            <category><![CDATA[causal-inference]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Onyi Lam]]></dc:creator>
            <pubDate>Mon, 03 Dec 2018 17:30:22 GMT</pubDate>
            <atom:updated>2019-11-21T22:43:45.943Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*yE5hn-iDac-Z5t3dUKvLGg.png" /></figure><p>Identifying causal relationships from observational data is not easy. Still, researchers are often interested in examining the effects of policy changes or other decisions. In those analyses, researchers will face any number of analytical decisions, including whether to use fixed or random effects models to control for variables that don’t change over time.</p><p>Let’s consider an example. Suppose we’re interested in estimating the effect that a government grant might have had on firms’ product quality (as examined in <a href="https://www.researchgate.net/profile/Harry_Holzer/publication/5119125_Are_Training_Subsidies_for_Firms_Effective_The_Michigan_Experience/links/0deec518bdb0d7cc50000000/Are-Training-Subsidies-for-Firms-Effective-The-Michigan-Experience.pdf">this previous study</a>). In addition to controlling for observed variables like the number of employees the firms had at different time points in the study period, we might also want to control for <em>unobserved</em> variables, such as the management quality of the firms.</p><p>Assuming that the firms’ management quality is constant over time, we can use <a href="https://medium.com/pew-research-center-decoded/how-to-break-regression-f48230f0ca68">regression models </a>to try to account for those unobserved factors — but there isn’t always consensus about the best way to do so. Specifically, researchers often must decide whether to use a fixed or random effects approach in an analysis like this.</p><p>In this post, we’ll discuss some of the differences between fixed and random effects models when applied to panel data — that is, data collected over time on the same unit of analysis — and how these models can be implemented in the programming language Python.</p><h3><strong>Fixed vs. random effects in panel data</strong></h3><p>Broadly speaking, the distinction between a fixed effects approach and a random effects approach concerns the correlation — or lack thereof — between unobserved variables and observed variables. To highlight this difference, let’s go back to the example cited above.</p><p>The key issue in deciding between the two approaches is whether or not the unobserved variables in our analysis — in this case, the firms’ management quality — might be correlated with observed variables. We might use a fixed effects approach if we think that these variables <em>are</em> correlated — for example, if we think firms’ management quality has a role in determining whether the firms receive a grant. But we might use a random effects approach if we think the two variables are <em>not</em> correlated.</p><p>Fixed effects help capture the effects of <strong>all variables</strong> that don’t change over time. In other words, anything else that does not change over time at the firm level, such as its location, would be captured by these fixed effects terms in the model. That means we cannot separately estimate the effect of firms’ location on their performance.</p><p>This is quite restrictive for some applications, so researchers who might be interested in studying the effect of time-invariant variables may want to choose the random effects framework instead, even though these models impose stronger assumptions about the unobserved effects.</p><h3><strong>Using Python to implement the models</strong></h3><p>Next, we’ll illustrate how to implement panel data analysis in Python, using a built-in dataset on firms’ performance from the `linearmodels` library that follows from the example discussed above. Note that `linearmodels` is only supported in Python 3.</p><pre>import numpy as np<br>import pandas as pd<br>from linearmodels import PanelOLS<br>from linearmodels import RandomEffects</pre><p>To implement a random effects model, we call the RandomEffects method and assign the firm code and year columns as the indexes in the dataframe.</p><pre>from linearmodels.datasets import jobtraining<br>data = jobtraining.load()<br>year = pd.Categorical(data.year)<br>data = data.set_index([‘fcode’, ‘year’])<br>data[‘year’] = year</pre><p>For the dependent variable, we use the change in scrap rate between periods as a proxy of the product quality. For the independent variables, we include the grant status in period t (=1 if received grant) and the number of employees at the firm.</p><pre>exog_vars = [‘grant’, ‘employ’]<br>exog = sm.add_constant(data[exog_vars])<br>mod = RandomEffects(data.clscrap, exog)<br>re_res = mod.fit()<br>print(re_res)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/0*OuTZjnsqO9i8ac3W" /></figure><p>To implement the fixed effects model, we use the PanelOLS method, and set the parameter `entity_effects` to be True.</p><p>mod = PanelOLS(data.clscrap, exog)</p><p>re_res = mod.fit()</p><p>print(re_res)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/0*ptnCmeIPn8loSFLR" /></figure><p>The results are quite different between the fixed and random effects models, but neither is statistically significant. However, to the extent that you think the unobserved effect of the firms is uncorrelated with whether the firms received the grant, the random effects model is more appropriate.</p><h3><strong>Equivalence of fixed effects model and dummy variable regression</strong></h3><p>Estimating a fixed effects model is equivalent to adding a dummy variable for each subject or unit of interest in the standard OLS model. To illustrate equivalence between the two approaches, we can use the OLS method in the statsmodels library, and regress the same dependent variable on the categorized variable of firm, and other independent variables:</p><pre>data = jobtraining.load()<br>data[‘year’] = pd.Categorical(data.year)<br>FE_ols = smf.ols(formula=’clscrap ~ 1 + grant + employ + C(fcode)’, data = data).fit()<br>print(FE_ols.summary())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/0*cz9DYQUHtlBLSdCc" /></figure><p>The results from the dummy regression show the separately estimated effect of each firm on change in scrap rate. This is sometimes useful when we want to focus on specific units. In addition, we can compute some sample averages of these estimates to get a sense of how much variation there is across firms.</p><p><em>Onyi Lam</em> <em>is a computational social scientist focusing on data science at Pew Research Center.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a795865736ab" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pew-research-center-decoded/using-fixed-and-random-effects-models-for-panel-data-in-python-a795865736ab">Using fixed and random effects models for panel data in Python</a> was originally published in <a href="https://medium.com/pew-research-center-decoded">Pew Research Center: Decoded</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detecting subjectivity and tone with automated text analysis tools]]></title>
            <link>https://medium.com/pew-research-center-decoded/detecting-subjectivity-and-tone-with-automated-text-analysis-tools-5f0e662224b8?source=rss-96b16f7a5201------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f0e662224b8</guid>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Onyi Lam]]></dc:creator>
            <pubDate>Thu, 26 Jul 2018 12:58:25 GMT</pubDate>
            <atom:updated>2018-07-30T16:47:39.691Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*ijKgGP6KEI-q5VS3S9tRkg.png" /><figcaption>(Photo illustration by Pew Research Center and Petr Vaclavek//Shutterstock.com)</figcaption></figure><p>There are a variety of tools that can help researchers analyze large volumes of written material. In this post, I’ll examine two of these tools: part-of-speech tagging and tone analysis. I’ll also show how to use these methods to find patterns in a large set of Facebook posts created by members of Congress.</p><p>Part-of-speech (POS) tagging is a process that labels each word in a sentence with an algorithm’s best guess for the word’s part of speech (for example, noun, adjective or verb). This is based on both the definition of each word and the context in which it appears. There are several libraries in Python that perform POS tagging, such as <a href="http://www.nltk.org/">NLTK</a>, <a href="https://spacy.io/">SpaCy</a> and <a href="https://textblob.readthedocs.io/en/dev/">TextBlob</a>. These tagging systems are pre-trained using supervised machine learning models, based on a training dataset with labeled text. As a result, the POS tags returned by these models are estimates based on the data that each particular model was trained with.</p><p>One reason researchers might care about parts of speech is that they can help reveal attributes of written text. For example, research has shown the presence of adjectives and adverbs is usually a <a href="https://onlinelibrary.wiley.com/doi/pdf/10.1002/meet.1450410141">good indicator of text subjectivity</a>. In other words, statements that use adjectives like “interesting,” “problematic” and “awesome” might be more likely to convey a subjective point of view than statements that do not include those adjectives. Adjectives and adverbs might also be especially likely to convey tone: Some indicate more positive qualities, while others indicate negative qualities.</p><p>To identify adjectives using a computational model, I’ll use a set of predefined part of speech tags. The set of possible tags comes from the <a href="https://www.ling.upenn.edu/courses/Fall_2003/ling001/penn_treebank_pos.html">Penn Treebank tagset</a>. If the returned tag is either JJ (adjective), JJR (adjective, comparative) or JJS (adjective, superlative), I’ll treat the word as an adjective. Similarly, if a word has the POS tag of RB (adverb), RBR (adverb, comparative) or RBS (adverb, superlative), I’ll consider it an adverb.</p><p>The code below is a simple function in Python that returns a list of all adjectives and adverbs, and the total number of adjectives and adverbs for a given text using the <a href="https://textblob.readthedocs.io/en/dev/">TextBlob</a> library:</p><pre>from textblob import TextBlob<br>from collections import Counter</pre><pre>def textblob_adj(text):<br>    blobed = TextBlob(text)<br>    counts = Counter(tag for word,tag in blobed.tags)<br>    adj_list = []<br>    adv_list = []<br>    adj_tag_list = [‘JJ’,’JJR’,’JJS’]<br>    adv_tag_list = [‘RB’,’RBR’,’RBS’]<br>    for (a, b) in blobed.tags:<br>        if b in adj_tag_list:<br>           adj_list.append(a)<br>        elif b in adv_tag_list:<br>           adv_list.append(a)<br>        else:<br>            pass<br>    return adj_list, adv_list, counts[‘JJ’]+counts[‘JJR’]+counts[‘JJS’], counts[‘RB’]+counts[‘RBR’]+counts[‘RBS’]</pre><p>To show how part-of-speech recognition works in practice, I analyzed over 700,000 Facebook posts created between Jan. 1, 2015, and Dec. 30, 2017, by members of the U.S. Congress, collected using Facebook’s public API. (This is part of a larger <a href="http://www.people-press.org/2017/02/23/partisan-conflict-and-congressional-outreach/">body of research</a> that Pew Research Center has conducted about lawmakers’ Facebook posts.) My goal was to understand how adjective and adverb use in partisan speech changed across this period of time. The analysis shows that after President Donald Trump took office, Democrats in Congress started using more adjectives than Republicans in their Facebook posts. Democrats’ ratio of positive to negative adjectives also decreased after Trump took office.</p><p>I applied the function above to each Facebook post. Some of the adjectives that were used mostly by Democrats in Congress include “wealthiest”, “richest” and “reproductive,” whereas “unborn,” “libertarian” and “Islamist” are among the adjectives used mostly by Republicans. The adjective ratio — defined as the number of adjectives divided by the total number of words in the post — was slightly higher for Republicans than Democrats in the early part of 2015. It was very similar for the two parties across most of 2016. But starting with Trump’s 2016 election victory, Democrats became much more likely to use adjectives in their posts. This finding aligns with a previous Pew Research Center <a href="http://www.people-press.org/2018/07/18/taking-sides-on-facebook-how-congressional-outreach-changed-under-president-trump/">analysis</a> that shows that congressional Democrats expressed political opposition more frequently under Trump. It is also consistent with the hypothesis that adjective use is linked with stronger emotions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/0*yt5_s4SpUt2H4c5q" /></figure><p>I also examined the tone of particular adjectives by comparing the words that appeared in the congressional posts with a list of adjectives that usually have a positive or negative association. This association is based on a polarity dictionary: a list of positive and negative words. If an adjective appears in the list of positive or negative words in the dictionary, it is classified as such. The plot produced here uses the <a href="http://www.wjh.harvard.edu/~inquirer/homecat.htm">Harvard IV-4 dictionary</a>, which contains 1,915 positive and 2,291 negative words (the list is also used in the <a href="http://onlinelibrary.wiley.com/doi/10.1111/j.1540-6261.2008.01362.x/full">academic community</a>).</p><p>Using that measure, the ratio of positive to negative adjectives declined in congressional Democrats’ Facebook posts after Trump was inaugurated, but it increased slightly in Republicans’ posts (I added 1 to the denominator to avoid dividing by 0). For much of the first half of 2015, Republicans had a lower positive-to-negative adjective ratio, but the partisan difference was absent across most of 2016.</p><p>Adjective analysis using off-the-shelf packages and dictionaries can provide an accessible and inexpensive way to explore sentiment and subjectivity in texts, without the need to obtain a large labeled training set. However, researchers should be cautious when drawing inferences from the tools described here. There’s no guarantee that adjectives provide a valid measure of important concepts like subjectivity across diverse contexts, and the link between particular adjectives and sentiment may not generalize across different domains. It’s always necessary to validate a given model — either by using human coders, or by supplementing the analysis with other measures of subjectivity — before drawing strong conclusions about what text tells us.</p><p><em>Onyi Lam</em> <em>is a computational social scientist focusing on data science at Pew Research Center.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f0e662224b8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pew-research-center-decoded/detecting-subjectivity-and-tone-with-automated-text-analysis-tools-5f0e662224b8">Detecting subjectivity and tone with automated text analysis tools</a> was originally published in <a href="https://medium.com/pew-research-center-decoded">Pew Research Center: Decoded</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using APIs to collect website data]]></title>
            <link>https://medium.com/pew-research-center-decoded/using-apis-to-collect-website-data-b7fc340d59e3?source=rss-96b16f7a5201------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7fc340d59e3</guid>
            <category><![CDATA[api-integration]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Onyi Lam]]></dc:creator>
            <pubDate>Wed, 27 Jun 2018 17:59:33 GMT</pubDate>
            <atom:updated>2019-05-06T20:21:10.716Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EMcpH_7vFbCb1cR_uBNccg.png" /></figure><p>Many researchers are interested in obtaining new kinds of data directly from websites. But collecting large amounts of data from a website can be impractical. When done manually, this approach is prone to human error. When automated, it may violate a website’s terms of service.</p><p>Instead, researchers typically rely on a tool called an API, which stands for Application Programming Interface. Web APIs provide a means of communication between websites and users, structured by rules. In particular, they allow users to obtain clearly defined kinds of data quickly, by requesting it directly from the database underlying a particular website. (This isn’t the only kind of API. For example, smartphone apps frequently use APIs to send data back and forth between your device and the application’s database. In this blog post, however, we’re focusing on APIs that deliver data from websites to users.)</p><p>Many major companies, as well as government agencies, have created public APIs. These organizations provide easy access to their data to encourage developers to use their platforms. At Pew Research Center, we regularly use APIs to collect information for the studies we produce. For example, we’ve used APIs in reports about <a href="http://www.people-press.org/2017/02/23/partisan-conflict-and-congressional-outreach/">online congressional communication</a>, <a href="http://www.pewinternet.org/2018/04/09/bots-in-the-twittersphere/">bots in social media</a>, <a href="http://www.pewresearch.org/fact-tank/2018/03/16/what-google-searches-can-tell-us-about-americans-interest-in-guns/">Google searches about guns</a>, <a href="http://www.pewinternet.org/2018/03/21/the-science-people-see-on-social-media/">science pages on Facebook</a>, and <a href="http://www.pewinternet.org/2017/11/29/public-comments-to-the-federal-communications-commission-about-net-neutrality-contain-many-inaccuracies-and-duplicates/">public comments on government policy</a>.</p><h3>How APIs provide data</h3><p>APIs provide data in various formats, but JSON is the most popular. JSON is a useful file format for structuring data because it preserves more hierarchical structure and meta information about a dataset than tab- or comma-separated files (such as .tsv and .csv files). Depending on the programming language you’re using for your data analysis, there are libraries that make JSON data manipulation intuitive. For example, in the R statistical language, you can use the jsonlite library to transform data from APIs into familiar R objects and classes.</p><h3>APIs can be used in different programming languages</h3><p>In order to interact with an API efficiently across a variety of computer programs written in different languages (such as Java, Python, R, etc), researchers rely on API “wrappers.” These tools — which exist for most popular APIs — allow a researcher to request data directly from an API while using their own programming language of choice. Below, we use the World Bank’s API as an example and access the data using R.</p><h3>Example: How to interact with the World Bank’s API</h3><p>The <a href="https://datahelpdesk.worldbank.org/knowledgebase/articles/889392-api-documentation">World Bank API</a> gives researchers access to hundreds of variables about the health, wealth and culture of countries around the world. To show how to use this API, we can write a script to get a couple of variables and plot them. In this case, we’ll search for variables using the identifying codes provided by the World Bank, and then pull the variables into memory in R.</p><p>The code below uses the WDI <a href="https://cran.r-project.org/web/packages/WDI/WDI.pdf">package</a>, an R package that includes a wrapper for the World Bank API. (A wrapper, as noted above, is a function or set of functions to execute calls to the API and convert the results into something more usable than what the API may return on its own.) To execute this code, you first have to install the WDI package, as well as <a href="https://cran.r-project.org/web/packages/devtools/index.html">devtools</a>,<a href="https://cran.r-project.org/web/packages/ggplot2/index.html">ggplot2</a>, <a href="https://www.ggplot2-exts.org/gganimate.html">gganimate</a>, <a href="https://cran.r-project.org/web/packages/data.table/">data.table</a>, and <a href="https://cran.r-project.org/web/packages/dplyr/vignettes/dplyr.html">dplyr</a>. You can install these functions for R with the following commands:</p><pre>install.packages(c(“WDI”, “ggplot2”, “devtools”, “data.table”, “dplyr”))</pre><p>We’ll also install the gganimate add-on package for animation:</p><pre>devtools::install_github(“dgrtwo/gganimate”)</pre><p>Now that these packages are installed, let’s load them into working memory:</p><pre>library(WDI)<br>library(gganimate)<br>library(ggplot2)<br>library(data.table)<br>library(dplyr)<br>library(devtools)</pre><p>The WDI package provides a convenient way to search the World Bank API for variables that might be interesting for research. Below, we specify the word we want to search for after the “string” field, and where to look for it — the “name” field. Doing so, we can see all the variables related to road infrastructure, immunization rates, and any other variables measured on a per capita basis.</p><pre>#This code to search the API<br>WDIsearch(string=”roads”, field=”name”)<br>WDIsearch(string=”immunization”, field=”name”)<br>WDIsearch(string=”per capita”, field=”name”)</pre><p>The search returns lists of variables and their corresponding codes. Now that we know the codes for the variables we’re interested in, we can call for the data from the API. We do this with the WDI function. Within this function call, we supply as arguments the countries we want (which is all of them), the variable codes, the first year of data, the last year of data, and an optional “extra” set of fields. The “extra” fields are country metadata — try turning this option off and on to see what happens.</p><pre># Interesting Variables to plot<br># mortality per 1K women: SP.DYN.AMRT.FE<br># immunization rates of DPT: SH.IMM.IDPT<br># income per capita (constant): NY.ADJ.NNTY.PC.KD<br># population: SP.POP.TOTL</pre><pre># Getting the preliminary variables, using the code above<br>dat&lt;-data.table(WDI(country=”all”, indicator=c(“SP.DYN.AMRT.FE”, “SH.IMM.IDPT”, “NY.ADJ.NNTY.PC.KD”, “SP.POP.TOTL”), start=1980, end=2017, extra=T))</pre><p>The data are loaded into memory as a data.table object, which is a type of rectangular data frame that’s easy to interact with and analyze. One problem is that the variable names are not easy to interpret, so let’s convert them to something more intuitive. We do this with thedplyr package, which provides a set of tools for manipulating data. It has a convenient and readable syntax. We will use the “rename” command to rename the variables.</p><pre>ndat = dat %&gt;%<br> dplyr::rename(mortality = SP.DYN.AMRT.FE, immunization = SH.IMM.IDPT, <br> income_cap = NY.ADJ.NNTY.PC.KD, population = SP.POP.TOTL)</pre><p>Next, let’s remove the missing observations so we can plot the data. Of course, you should think carefully about which countries are missing and why.</p><pre>ndat = na.omit(ndat)</pre><pre>ndat = ndat[ndat$region!=”Aggregates”, ]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/0*DsUaoGZwHPHWwyY1" /></figure><p>We can create a visual representation of the relationship between income and immunization rates for a particular year. We’ll plot one point for each country, sized by the log of the country’s population. We’ll plot a <a href="https://en.wikipedia.org/wiki/Local_regression">LOESS</a> line of the general relationship, too.</p><p>Here is a static plot using ggplot2:</p><pre>p &lt;- ggplot(filter(ndat, year==1980), aes(income_cap, immunization, size = log(population))) +</pre><pre>geom_point(aes(col=country), show.legend = FALSE) +</pre><pre>geom_smooth(aes(group = year), method = “loess”, show.legend = FALSE) + scale_x_log10()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/0*KPLm7VC445dD7mEm" /></figure><p>Finally, we’ll create an animation of the same relationship over time. To do so, first install <a href="https://www.imagemagick.org/script/install-source.php">ImageMagick</a>. Then create a plot that includes all the years in the data:</p><pre>p &lt;- ggplot(ndat, aes(income_cap, immunization, size = log(population), frame = year)) +<br> geom_point(aes(col=country), show.legend = FALSE) + <br> geom_smooth(aes(group = year), method = “loess”, show.legend = FALSE) + scale_x_log10()</pre><pre>gganimate(p)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*XA51waYrzBqSWt2M" /></figure><h3>Some useful APIs</h3><p>In addition to the World Bank’s API, here are some others that we’ve interacted with and found useful:</p><ul><li><a href="https://developer.twitter.com/en/docs/tweets/search/overview.html">Twitter</a></li><li><a href="https://projects.propublica.org/api-docs/congress-api/">ProPublica Congress</a></li><li><a href="https://datahelpdesk.worldbank.org/knowledgebase/articles/889392-api-documentation">World Ban</a>k</li><li><a href="https://developers.facebook.com/docs/graph-api/">Facebook</a></li><li><a href="https://www.census.gov/developers/">U.S. Census Bureau</a></li><li><a href="https://developer.oxforddictionaries.com/">Oxford Dictionaries API</a></li><li><a href="http://data.un.org/Host.aspx?Content=API">United Nations Data</a></li></ul><p><em>This post was written by Onyi Lam, Adam Hughes and Stefan Wojcik, who are computational social scientists focusing on data science at Pew Research Center.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7fc340d59e3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pew-research-center-decoded/using-apis-to-collect-website-data-b7fc340d59e3">Using APIs to collect website data</a> was originally published in <a href="https://medium.com/pew-research-center-decoded">Pew Research Center: Decoded</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning: A Toy Example for Practitioner]]></title>
            <link>https://medium.com/@onyilam/machine-learning-a-toy-example-for-practitioner-3f9f3a216a34?source=rss-96b16f7a5201------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f9f3a216a34</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Onyi Lam]]></dc:creator>
            <pubDate>Tue, 13 Dec 2016 19:15:47 GMT</pubDate>
            <atom:updated>2016-12-13T19:55:21.096Z</atom:updated>
            <content:encoded><![CDATA[<p>Machine learning has generated a lot of buzz in the last few years. From self-driving car to product recommendation, tools developed in AI have been integrated into different aspects of our day-to-day and shaping future way of our life. The technology has tapped into public policy as well. The Economist magazine has a <a href="http://www.economist.com/news/finance-and-economics/21705329-governments-have-much-gain-applying-algorithms-public-policy">recent article</a> that examines how machine learning can be used to improve policy design which for social scientists and practitioners, presents enormous research opportunity.</p><p>This post illustrates how to use the machine learning library <strong><em>sklearn</em></strong> in python to solve a binary prediction problem that are relevant to many social science/policy problems. For example, educators may be interested in knowing which students may not graduate on time; an urban planner may want to know <a href="https://www.drivendata.org/competitions/7/">which infrastructure is prone to degradatio</a>n so she can send inspector to them early on before any accidents take place.</p><h4>The Data</h4><p>To apply a supervised predictive model, we need to tell the computer the label of each data point in the training yet. For example, if we are interested in predicting who is likely to be a donor to a political party using existing data as a training set, we need to tell the computer who have been donors in the past (donors = 1 if yes, 0 otherwise).</p><p>For this tutorial, I use the Credit approval dataset, available at the<a href="https://archive.ics.uci.edu/ml/datasets/Credit+Approval"> UCI Mahine Learning Repository</a>. The data set concerns credit card applications and has 690 data points. We want to come up with a best that predicts whether one will receive credit approval or not.</p><p>To read the data file, we run the following line:</p><pre>cred = pd.read_csv(&#39;crx.data&#39;, delimiter=&#39;,&#39;, names = [&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;,&#39;e&#39;,&#39;f&#39;,&#39;g&#39;,&#39;h&#39;,&#39;i&#39;,&#39;j&#39;,&#39;k&#39;,&#39;l&#39;,&#39;m&#39;,&#39;n&#39;,&#39;o&#39;,&#39;y&#39;])</pre><p>Since the data file does not have column headers, I add “names”.</p><h4>Preprocessing</h4><p>In many <strong><em>sklearn</em></strong> tutorials that I have seen, few have touched on how do we pre-process the data before sending it to the model. This is an absolutely critical step. Before applying any models to the data, we need to ensure our data is of good quality. The thing we want to check is to see if there is any missing values in the data.</p><pre>cred.isnull().sum()</pre><p>Looks like there is no missing value — but let’s see if there is any funky non-numeric character. The below line lists the unique value of column 1 in the dataset.</p><pre>cred.ix[:,1].unique()</pre><p>ah-ha, looks like ‘?’ is present. So what do we do with it? One option is to simply remove all rows with ‘?’ in it, but that seems to be throwing away a lot of potentially useful information. Instead, what we do is to replace ‘?’ with the mean of the column:</p><pre>cred[‘b’] = cred[‘b’].replace(‘?’, np.nan)<br>cred[‘b’] = cred[‘b’].astype(float)<br>cred.loc[:, &#39;b&#39;] = cred.fillna(cred.mean()[&#39;b&#39;])</pre><p>Next, we want to examine whether any of the columns is non-numeric. We need to convert all non-numeric variables into numeric. One option is to generate a dummy variable for each value in each column:</p><pre>categorical_var = [‘a’,’d’,’e’,’f’,’g’,’i’,’j’,’l’,’m’,’n’]<br>cred = pd.get_dummies(cred, columns = categorical_var)</pre><p>Finally, we want to replace the ‘+’ and ‘-’ of the outcome variable to ‘1’ and ‘0’</p><pre>cred.ix[cred[‘y’] ==’+’, ‘y’] = 1<br>cred.ix[cred[‘y’] ==’-’, ‘y’] = 0<br>cred[‘y’] = cred[‘y’].astype(int)</pre><h4>How do we split our data into training set and test set?</h4><p>How we split our data into test and training set matters a lot. Suppose you are interested in using the machine learning model to predict whether a student is going to graduate high school. What you might want is to split your data by year, i.e. if you have data from 2010 to 2014, you might want to use all the data up to 2013 for training and test your model on 2014. This strategy makes sense because you want to make sure that your model captures some time-variant component of student behavior.</p><p>In other cases, this strategy might not be ideal. Suppose you are interested in predicting which student is likely to fall behind schedule by next year, you might want to split your data by student cohort instead. The point is that you want to think very carefully about your cross-validation strategy because it can significantly affect your model performance.</p><p>In this toy example, we simply randomly assign 70% of data point to train set and the rest to the train set. sklean has a nice module that does that:</p><pre>from sklearn.cross_validation import train_test_split</pre><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)</pre><h4>Choosing a model</h4><p>There are many different classification algorithms/models that one can use and there is no right answer which model is the best a-priori so the best thing to do is to loop over different models and decide which one performs best based on the metric you care most. In this example, we simply use a most common classifier Logistic Regression to illustrate the working of the code.</p><pre>clf = LogisticRegression(C=1.0, penalty=’l2&#39;, tol=1)<br>y_pred_probs = clf.fit(X_train, y_train).predict_proba(X_test)[:,1]</pre><p>The first line calls the classifier we want to use and the second line fits the model on our training set and generate a predicted probability on the test set.</p><h4>Evaluating Performance</h4><p>So now that we have trained the model and run it on the test set, how do we evaluate how well our model does? In a nutshell, it depends on what you care about. AUC is a common metric to evaluate performance of prediction model, and is equal to the probability that the classifier will rank a randomly chosen positive example higher than a randomly chosen negative example:</p><pre>metrics.roc_auc_score(y_test, y_pred_probs)</pre><p>In general, the larger the AUC, the better the model performs. Another common metrics is the confusion matrix. The confusion matrix has the following 4 values:</p><p><strong>true positives (TP):</strong> These are cases in which we predicted yes (yes, they will get credit) and they do get the credit.</p><p><strong>true negatives (TN):</strong> We predicted no, and they don’t get the credit</p><p><strong>false positives (FP):</strong> We predicted yes, but they don’t actually have the credit (Also known as a “Type I error.”)</p><p><strong>false negatives (FN):</strong> We predicted no, but they actually do have the credit. (Also known as a “Type II error.”)</p><pre>k = 0.5<br>threshold = np.sort(y_pred_probs)[::-1][int(k*len(y_pred_probs))]<br>y_pred = np.asarray([1 if i &gt;= threshold else 0 for i in y_pred_probs])<br>metrics.confusion_matrix(y_test, y_pred)</pre><p><strong><em>Feature Importance</em></strong></p><p>We might want to know which features are the most predictive in credit approval. To find out, we can examine the coefficients on the features and rank them by their value:</p><pre>importances = clf.fit(X_train, y_train).coef_<br>indices = np.argsort(importances)[::-1]<br>X = cred.drop(&#39;y&#39;, 1)<br>X.columns[indices]</pre><p>I hope this post can get you started on applying tools in machine learning to your research! The full code can be found on my <a href="https://github.com/onyilam/credit/blob/master/Workshop.ipynb">github page</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f9f3a216a34" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>