<?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 Sharon Woo on Medium]]></title>
        <description><![CDATA[Stories by Sharon Woo on Medium]]></description>
        <link>https://medium.com/@sharonwoo?source=rss-975582c6574b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4W4ro9zgDVl77s7WD5f0eg.jpeg</url>
            <title>Stories by Sharon Woo on Medium</title>
            <link>https://medium.com/@sharonwoo?source=rss-975582c6574b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 07:09:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sharonwoo/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[environments in Anaconda]]></title>
            <link>https://medium.com/@sharonwoo/environments-in-anaconda-49045928d20d?source=rss-975582c6574b------2</link>
            <guid isPermaLink="false">https://medium.com/p/49045928d20d</guid>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Sharon Woo]]></dc:creator>
            <pubDate>Tue, 06 Nov 2018 07:09:40 GMT</pubDate>
            <atom:updated>2018-11-06T07:57:34.695Z</atom:updated>
            <content:encoded><![CDATA[<p>So I stumbled onto a <a href="https://stackoverflow.com/questions/52979322/matplotlib-3-0-0-cannot-import-name-get-backend-from-matplotlib">Python 3.7 bug</a> where calling</p><pre>import matplotlib</pre><p>broke my Jupyter kernel, and rolling back to 3.6 didn’t quite help me either.</p><p>It was my second day slinging code full time. (Hooray!) And, being new and having a nice shy new computer to work with, I used Anaconda to quickly get everything installed properly… and which comes by default with Python 3.7 now.</p><p>What’s a girl to do? At work, I installed miniconda with 3.7, and used environments to setup Python 3.6 environments. One problem solved.</p><p>Shortly after that my lovely new Mac decided it, too, would throw errors with Matplotlib and Seaborn (<a href="https://stackoverflow.com/questions/51846948/seaborn-lineplot-module-object-has-no-attribute-lineplot/51847295">this one</a>). I’m still reinstalling everything, the right way this time —</p><p><a href="https://docs.anaconda.com/anaconda/install/uninstall/">Uninstall Python</a></p><pre>conda install anaconda-clean<br>anaconda-clean --yes<br>rm -rf ~/anaconda</pre><p><a href="https://www.davidculley.com/installing-python-on-a-mac/">Install Miniconda</a> and create an environment to install Anaconda in</p><pre>brew install wget<br>wget <a href="https://repo.continuum.io/miniconda/Miniconda3-latest-MacOSX-x86_64.sh">https://repo.continuum.io/miniconda/Miniconda3-latest-MacOSX-x86_64.sh</a><br>bash <a href="https://repo.continuum.io/miniconda/Miniconda3-latest-MacOSX-x86_64.sh">Miniconda3-latest-MacOSX-x86_64.sh</a><br><a href="https://stackoverflow.com/questions/47246350/conda-activate-not-working">echo &quot;conda activate&quot; &gt;&gt; ~/.bash_profile</a></pre><pre>conda create --name home36 <br>conda activate home36<br>conda install anaconda </pre><p>Useful links:</p><p><a href="https://medium.com/@anyuhang/setting-up-python-environment-with-anaconda-and-homebrew-8c4963604df0">Setting up Python environment with Anaconda and Homebrew</a></p><p>AAAARGH it didn’t work:</p><p><a href="https://github.com/conda/conda/issues/7403">https://github.com/conda/conda/issues/7403</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49045928d20d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[14 months — milestones]]></title>
            <link>https://medium.com/@sharonwoo/14-months-milestones-1e4ff9f26086?source=rss-975582c6574b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e4ff9f26086</guid>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Sharon Woo]]></dc:creator>
            <pubDate>Wed, 03 Oct 2018 06:30:57 GMT</pubDate>
            <atom:updated>2018-10-03T06:31:36.205Z</atom:updated>
            <content:encoded><![CDATA[<h3>14 months — milestones</h3><ul><li>My NLTK post is the top hit for “facebook nltk” search string in Google and has been linked by another tutorial lol. Whodathunkit? And that was before I learned a lot more in text analytics/machine learning classes. Formal education ftw.</li><li>Reading up on recommender systems now — watch this space. (The best learning comes from doing, I believe…)</li></ul><p>Recommender references:</p><ul><li>Charu Agarwal’s textbook</li><li><a href="https://github.com/manugarri/pydata_2016_talk_recommenders/blob/master/Slides.pdf">Scrapinghub</a> talk</li><li><a href="http://subhrajitroy.com/wp-content/uploads/2016/03/reco_ebook.pdf">http://subhrajitroy.com/wp-content/uploads/2016/03/reco_ebook.pdf</a></li><li><a href="https://medium.com/@m_n_malaeb/singular-value-decomposition-svd-in-recommender-systems-for-non-math-statistics-programming-4a622de653e9">https://medium.com/@m_n_malaeb/singular-value-decomposition-svd-in-recommender-systems-for-non-math-statistics-programming-4a622de653e9</a></li><li><a href="https://www.computer.org/csdl/mags/ic/2017/03/mic2017030012.html">https://www.computer.org/csdl/mags/ic/2017/03/mic2017030012.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e4ff9f26086" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[data.table and joins in R]]></title>
            <link>https://medium.com/@sharonwoo/data-table-and-joins-in-r-ac3d45074e7c?source=rss-975582c6574b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac3d45074e7c</guid>
            <dc:creator><![CDATA[Sharon Woo]]></dc:creator>
            <pubDate>Fri, 30 Mar 2018 09:20:17 GMT</pubDate>
            <atom:updated>2018-03-30T09:20:17.434Z</atom:updated>
            <content:encoded><![CDATA[<p>Or how I learned to love SQL and stop worrying.</p><p><a href="https://rstudio-pubs-static.s3.amazonaws.com/52230_5ae0d25125b544caab32f75f0360e775.html">https://rstudio-pubs-static.s3.amazonaws.com/52230_5ae0d25125b544caab32f75f0360e775.html</a></p><p><a href="https://stackoverflow.com/questions/12773822/why-does-xy-join-of-data-tables-not-allow-a-full-outer-join-or-a-left-join">https://stackoverflow.com/questions/12773822/why-does-xy-join-of-data-tables-not-allow-a-full-outer-join-or-a-left-join</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac3d45074e7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Plotly for graphs in R]]></title>
            <link>https://medium.com/@sharonwoo/plotly-for-graphs-in-r-9ec28af93aac?source=rss-975582c6574b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ec28af93aac</guid>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Sharon Woo]]></dc:creator>
            <pubDate>Thu, 22 Mar 2018 15:26:06 GMT</pubDate>
            <atom:updated>2018-03-22T15:26:06.987Z</atom:updated>
            <content:encoded><![CDATA[<p>I tried to replicate Excel’s graphs in R, but found it rough going initially — ggplot2 didn’t seem to have the functionality I needed, which is just plotting a value for each category I was interested in.</p><p>Enter plotly.</p><pre>x &lt;- c(</pre><pre>&quot;HHI&quot;, &quot;SHI&quot;, &quot;DSME&quot;)</pre><pre>y1 &lt;- c(5196,2385,2846)</pre><pre>y2 &lt;- c(3489,1413,2493)</pre><pre>rev_d &lt;- data.frame(x,y1,y2)</pre><pre>ax &lt;- list(</pre><pre>  type =&quot;category&quot;,</pre><pre>  categoryorder = &quot;array&quot;,</pre><pre>  categoryarray = c(&quot;HHI&quot;,&quot;SHI&quot;,&quot;DSME&quot;),</pre><pre>  title = &quot;&quot;</pre><pre>           )</pre><pre># the categoryarray part took the most time, because I needed my graph in a specific order and couldn&#39;t figure out how to do so. </pre><pre>rev_p &lt;- rev_d %&gt;%</pre><pre>plot_ly() %&gt;%</pre><pre>add_trace(x = ~x, y = ~y1, type = &#39;bar&#39;, text=y1, name=&#39;4Q16&#39;, textposition = &#39;outside&#39;) %&gt;%</pre><pre>add_trace(x = ~x, y = ~y2, type = &#39;bar&#39;, text=y2, name=&quot;4Q17&quot;, textposition = &#39;outside&#39;) %&gt;%</pre><pre>layout(title = &quot;Revenue (KRW b)&quot;,</pre><pre>barmode = &#39;group&#39;,</pre><pre>xaxis = ax,</pre><pre>yaxis = list(title = &quot;&quot;))</pre><pre>rev_p</pre><p>References:</p><ul><li><a href="https://plot.ly/r/bar-charts/">https://plot.ly/r/bar-charts/</a></li><li><a href="http://r-statistics.co/Top50-Ggplot2-Visualizations-MasterList-R-Code.html">http://r-statistics.co/Top50-Ggplot2-Visualizations-MasterList-R-Code.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ec28af93aac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JPM AI/Semiconductor primer]]></title>
            <link>https://medium.com/@sharonwoo/jpm-ai-semiconductor-primer-cd152d63ce6d?source=rss-975582c6574b------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd152d63ce6d</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Sharon Woo]]></dc:creator>
            <pubDate>Mon, 19 Mar 2018 05:59:47 GMT</pubDate>
            <atom:updated>2018-03-19T06:00:26.718Z</atom:updated>
            <content:encoded><![CDATA[<p>General note: Primer editing appears done for the layman. Anyone who’s tried a Udemy course will know that “training” and “inference” are two sides of the same coin — why organise it this way? Happy to be corrected if wrong.</p><p>Summary:</p><ul><li>Current AI is done largely in the cloud and dominated by FAMG. This will drive data centre growth. <strong>Currently 6% of all data centres, JPM thinks go up to 33% by 2022 (of hyperscale DCs)</strong></li><li>Data architecture: GPU dependent due to parallel processing. Other bottleneck: memory</li><li>Growth areas: smartphone (embedded in processor), driverless cars, surveillance</li><li>How this flows into existing semi value chain: it’s a small component, but JPM posits will get bigger. In other words, old wine in new and MOAR bottles.</li></ul><p>What’s currently being done, layman-style:</p><blockquote>We have witnessed rising adoption of AI servers in datacenters for the large Internet players (Google, Amazon, Facebook, Microsoft etc.) with a key focus on AI training for different applications. Most large internet companies are already using their substantial databases and self-built IP in DNN algorithms in areas such as Natural Language Processing (NLP), computer vision, payment processing, targeted customer management and marketing. …. While on-premises AI training is a costly exercise (an NVIDIA DGX1 GPU server costs $149k), the widespread offering of deep learning training instances by various public cloud providers should make it much more affordable for a vast number of enterprises.</blockquote><p>Key stocks pitched:</p><ul><li>Foundry: TSMC</li><li>FAMG</li></ul><blockquote>There is a virtuous circle at work here, in our view, since credible AI use cases will incentivize enterprises and even governments to collect more data and install more IoT devices for machine learning.</blockquote><p>Exactly — people still have no idea what this is now. Much like the Internet in the late 90s.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd152d63ce6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[dplyr // R]]></title>
            <link>https://medium.com/@sharonwoo/dplyr-r-1b914c0d4b1d?source=rss-975582c6574b------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b914c0d4b1d</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[rstudio]]></category>
            <dc:creator><![CDATA[Sharon Woo]]></dc:creator>
            <pubDate>Fri, 09 Mar 2018 07:25:11 GMT</pubDate>
            <atom:updated>2018-03-09T07:25:11.735Z</atom:updated>
            <content:encoded><![CDATA[<p>aka I am having a Yuki Nagato moment.</p><p>Working on subsetting a table using SQL in R, but then giving up because SQL cannot be iterated through a do loop, and then moving to dplyr.</p><p>This doesn’t work in Windows, because the special characters get dropped. Trying is fun, though…</p><pre>library(tidyverse)<br>library(stringr)</pre><pre>setwd(&quot; &quot;)<br>df &lt;- read_csv(&quot; &quot;)<br># read in the database</pre><pre>colnames(df)[(names(df) == &quot;text&quot;)] &lt;- &quot;tweets&quot;<br># change TEXT to TWEETS -- otherwise next steps throw errors. WHY?</pre><pre>library(data.table)</pre><pre>clist &lt;- c(&quot;YahooCare&quot;, <br>           &quot;XboxSupport&quot;<br>           ) #this breaks for &gt;&gt;10 companies.</pre><pre>for (i in clist) {<br>  <br>  name &lt;- paste(i, sep = &quot;&quot;)<br>  #this step names each data table by the company name in clist. </pre><pre>  in_l &lt;- filter(df, author_id == i) #outbound tweets <br>  out_l &lt;- df %&gt;% filter(str_detect(tweets,i)) #@mentions<br>  <br>  fwrite(assign(name,unique(rbind(in_l,out_l))), name)</pre><pre>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b914c0d4b1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running]]></title>
            <link>https://medium.com/@sharonwoo/running-fe9c4ae0bc9c?source=rss-975582c6574b------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe9c4ae0bc9c</guid>
            <category><![CDATA[running]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Sharon Woo]]></dc:creator>
            <pubDate>Tue, 19 Dec 2017 15:13:45 GMT</pubDate>
            <atom:updated>2017-12-19T15:46:19.016Z</atom:updated>
            <content:encoded><![CDATA[<p>A picture says a thousand words.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*qaK-sTlkSop2Hy7wFd6vAw.png" /></figure><p>These are just the sub-10KM runs. Data from Smashrun, cleaned in R Studio (added year of run, converted distance to KM and created pace field), graph done with GGplot2.</p><p>Here’s to next year.</p><pre>library(tidyverse)<br>data &lt;- read_csv(&quot;data.csv&quot;)</pre><pre>data$Year &lt;- substr(data$Key,6,9)<br>data$Timing &lt;- data$Duration / 60000 # convert to minutes<br>data$Distance &lt;- data$Distance *1.6 # convert to KM<br>data$Pace &lt;- data$Timing/data$Distance</pre><pre>plot1 &lt;- ggplot (data=data,aes(x=Distance,y=Pace,color=Year))+<br>  geom_point()<br>plot1 # including outlier full marathon</pre><pre>library(dplyr)<br>shortdata &lt;- filter(data, Distance&lt;11)</pre><pre>plot2 &lt;- ggplot (data=shortdata,aes(x=Distance,y=Pace,color=Year))+<br>  geom_point()+<br>  scale_x_continuous(name=&quot;Distance (KM)&quot;)+<br>  scale_y_continuous(name=&quot;Pace (minutes/KM)&quot;,trans = &quot;reverse&quot;)<br>plot2</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe9c4ae0bc9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coursera — Algorithmic Toolbox]]></title>
            <link>https://medium.com/@sharonwoo/coursera-algorithmic-toolbox-3f2a49dfd3f9?source=rss-975582c6574b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f2a49dfd3f9</guid>
            <dc:creator><![CDATA[Sharon Woo]]></dc:creator>
            <pubDate>Wed, 16 Aug 2017 12:22:54 GMT</pubDate>
            <atom:updated>2017-08-16T12:29:38.260Z</atom:updated>
            <content:encoded><![CDATA[<p>Things I learnt from assignment 1 — max pairwise product problem:</p><ul><li>The dreaded <strong>O(N)</strong></li><li><a href="https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list">Copying a list</a> in Python is as simple as list.copy()</li><li>What a “naive solution” means</li></ul><pre>numbers = [20,67,3,2.6,7,74,2.8,90.8,52.8,4,3,2,5,7]<br>numbers2 = numbers.copy()<br>numbers2.remove(max(numbers2))<br>max(numbers) * max(numbers2)<br>Out[29]: 6719.2</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f2a49dfd3f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning A-Z with Python and R]]></title>
            <link>https://medium.com/@sharonwoo/machine-learning-a-z-14f189a415dd?source=rss-975582c6574b------2</link>
            <guid isPermaLink="false">https://medium.com/p/14f189a415dd</guid>
            <category><![CDATA[r]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Sharon Woo]]></dc:creator>
            <pubDate>Mon, 24 Jul 2017 02:48:19 GMT</pubDate>
            <atom:updated>2017-08-02T08:44:14.251Z</atom:updated>
            <content:encoded><![CDATA[<h3>Function cheat sheet</h3><p>Status update — New to R, figuring out R studio. Revising Python and learning new functions.</p><h3><strong>Data pre-processing</strong></h3><p>Here we replace missing values in datasets with the mean of other values.</p><blockquote><strong>Python — sklearn Imputer</strong></blockquote><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>import pandas as pd</pre><pre>dataset = pd.read_csv(&quot;Data.csv&quot;) <br>X = dataset.iloc[: , :-1].values<br>Y = dataset.iloc[:, 3].values</pre><pre># function replaces NaN values with what you tell it to<br>from sklearn.preprocessing import Imputer<br>imputer = Imputer(missing_values = &quot;NaN&quot;, strategy = &quot;mean&quot;, axis = 0)<br>imputer = imputer.fit(X[:,1:3] # .fit() trains the model using n_samples, n_features<br>X[:,1:3] = imputer.transform(X[:,1:3] # applies the changes</pre><pre># encoding categorical data with dummy variables<br>from sklearn.preprocessing import LabelEncoder <br>labelencoder_X = LabelEncoder()<br>countryencoder = countryencoder(categorical_features = [0]) # creates dummy variables - 3 columns to replace country <br>X = countryencoder.fit_transform(X).toarray() # toarray() as there are 3 columns in place of 1 <br>labelencoder_Y = LabelEncoder()<br>Y = labelencoder_Y.fit_transform(Y)</pre><pre># function replaces text labels with category indices 0,1,2...<br># labelencoder_X.fit_transform([X[:,0]) <br># to fit the labelencoder_X object to the first column of X</pre><blockquote><strong>R</strong></blockquote><pre># each index has to have missing values replaced separately<br># note TRUE has to be written this way, else it becomes an object and you get this error - Error in mean.default(x, na.rm = True) : object &#39;True&#39; not found</pre><pre>dataset$Age = ifelse(is.na(dataset$Age), <br>                     ave(dataset$Age, FUN = function(x) mean (x,<br>na.rm = TRUE)), <br>                     dataset$Age)<br>dataset$Salary = ifelse(is.na(dataset$Salary), <br>                     ave(dataset$Salary, FUN = function(x) mean (x,<br>na.rm = TRUE)), <br>                     dataset$Salary)</pre><pre># encoding categorical data with factor function <br># if empty arguments then error so check<br>dataset$Country = factor(dataset$Country, <br>                         levels = c(&#39;France&#39;, &#39;Spain&#39;,&#39;Germany&#39;), <br>                         labels = c(1,2,3)) <br>dataset$Purchased = factor(dataset$Purchased, <br>                         levels = c(&#39;No&#39;, &#39;Yes&#39;), <br>                         labels = c(0,1))</pre><h4>Splitting into training and test sets</h4><blockquote><strong>Python</strong></blockquote><pre>from sklearn.cross_validation import train_test_split <br>X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, random_state = 0) # train_size = 1 - test_size, random state is random sampling</pre><blockquote><strong>R</strong></blockquote><pre># install.packages(&quot;caTools&quot;)<br>library(caTools)<br>set.seed(123)<br>split = <strong>sample</strong>.split(dataset$Purchased, SplitRatio = 0.8)<br>training_set = subset(dataset, split == TRUE)<br>test_set = subset(dataset, split == FALSE)</pre><h4>Features scaling</h4><blockquote><strong>Python</strong></blockquote><pre>from sklearn.preprocessing import StandardScaler<br>sc_X = StandardScaler()<br>X_train = sc_X.fit_transform(X_train)<br>X_test = sc_X.fit_transform(X_test)</pre><pre># do you need to scale dummy variables? <br># do you need to scale the dependent variable? no - classification problems. yes - regression problems </pre><blockquote><strong>R</strong></blockquote><pre>training_set[,2:3] = scale(training_set[,2:3]) <br>test_set[,2:3] = scale(test_set[,2:3]) <br># a factor in R is not a numeric instance, so columns 1 and 4 are not numeric </pre><h3>Simple linear regression</h3><blockquote><strong>Python</strong></blockquote><pre># fit regression to training set<br>from sklearn.linear_model import LinearRegression<br>regressor = LinearRegression()<br>regressor.fit(X_train,Y_train) # fits the regressor to the training data </pre><pre># predicting test set results<br>Y_pred = regressor.predict(X_test) </pre><pre># visualisation of training set results - uses matplotlib<br>plt.scatter(X_train, Y_train, color = &quot;red&quot;) <br>plt.plot(X_train, Y_pred, color = &quot;blue&quot;) <br>plt.title(&quot;Salary vs Experience (Training Set)&quot;<br>plt.xlabel(&quot;Years of Experience&quot;)<br>plt.ylabel(&quot;Salary&quot;) <br>plt.show()</pre><pre># visualisation of test set results - uses matplotlib<br>plt.scatter(X_test, Y_test, color = &quot;red&quot;) <br>plt.plot(X_train, Y_pred, color = &quot;blue&quot;) <br>plt.title(&quot;Salary vs Experience (Test Set)&quot;<br>plt.xlabel(&quot;Years of Experience&quot;)<br>plt.ylabel(&quot;Salary&quot;) <br>plt.show()</pre><blockquote><strong>R</strong></blockquote><pre># R is a lot stricter on typos. Make sure you check for additional spaces etc else code will break!</pre><pre>dataset = read.csv(&quot;Salary_Data.csv&quot;)</pre><pre># splitting dataset into train x test <br># install.packages(&quot;caTools&quot;)<br>library(caTools)<br>set.seed(123)<br>split = sample.split(dataset$Salary, SplitRatio = 0.8)<br>training_set = subset(dataset, split == TRUE)<br>test_set = subset(dataset, split == FALSE)</pre><pre># salary proportional (~) to years experience <br>regressor = lm(formula = Salary ~ YearsExperience, data = training_set) <br># optional - shows the P values as *s<br># summary(regressor)</pre><pre>Y_pred = predict(regressor, newdata = test_set)</pre><pre>#install.packages(&quot;ggplot2&quot;)<br>library(ggplot2)<br>ggplot() + <br>  geom_point(aes(x = training_set$YearsExperience, y = training_set$Salary),<br>             colour = &quot;red&quot;) +<br>  geom_line(aes(x =training_set$YearsExperience, y = predict(regressor, newdata = training_set)), <br>            colour = &quot;blue&quot;) + <br>  ggtitle(&quot;Salary vs Experience (Training Set)&quot;) +<br>  xlab(&quot;Years of experience&quot;) + <br>  ylab(&quot;Salary&quot;)</pre><pre>ggplot() + <br>  geom_point(aes(x = test_set$YearsExperience, y = test_set$Salary),<br>             colour = &quot;red&quot;) +<br>  geom_line(aes(x =training_set$YearsExperience, y = predict(regressor, newdata = training_set)), <br>            colour = &quot;blue&quot;) + <br>  ggtitle(&quot;Salary vs Experience (Test Set)&quot;) +<br>  xlab(&quot;Years of experience&quot;) + <br>  ylab(&quot;Salary&quot;)</pre><h3>Building a model</h3><ol><li>Use all variables</li><li>Backward elimination</li><li>Forward selection</li><li>Bidirectional elimination</li><li>Score comparions</li></ol><blockquote><strong>Python</strong></blockquote><p>Revision — use Encoder to create dummy variables to replace state text string (New York etc).</p><pre># code here is largely repeated from simple linear regression<br># only new code is put in </pre><pre># avoid the dummy variable trap <br>X = X[:, 1:]</pre><pre># building the optimal model using backward elimination <br>import statsmodels.formula.api as sm<br>X = np.append(arr = np.ones(50,1).astype(int), values = X, axis=1) <br># adds a matrix of ones as the first column to existing matrix</pre><h3>Polynomial Regression</h3><blockquote><strong>R</strong></blockquote><ol><li>Create first quadratic variable — e.g. dataset$Level2 = dataset$Level^2</li><li>Fit polynomial regression to the dataset — poly_reg = lm(formula = Salary ~ ., data = dataset)</li><li>Visualise results with ggplot 2 — geom_point for actual points, geom_line for prediction (aes(x = dataset$Level, y = predict(poly_reg, newdata = dataset)</li><li>Predict new result with polynomial regression — y_pred = predict(poly_reg, data.frame(Level = … <em>insert levels here corresponding to number of corresponding quadratic variables))</em></li></ol><h3>Support Vector Regression</h3><p>Python</p><ol><li>New: import SVR in scikitlearn. Kernel — linear/poly/rbf/sigmoid etc.</li><li>Perform feature scaling (standardscaler in scikitlearn) and transform them</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14f189a415dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sentiment analysis with NLTK /VADER — Comments on Lee Hsien Loong’s Facebook post]]></title>
            <link>https://medium.com/@sharonwoo/sentiment-analysis-with-nltk-422e0f794b8?source=rss-975582c6574b------2</link>
            <guid isPermaLink="false">https://medium.com/p/422e0f794b8</guid>
            <category><![CDATA[nltk]]></category>
            <category><![CDATA[big-data-analytics]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[facebook]]></category>
            <category><![CDATA[python3]]></category>
            <dc:creator><![CDATA[Sharon Woo]]></dc:creator>
            <pubDate>Fri, 14 Jul 2017 06:59:05 GMT</pubDate>
            <atom:updated>2017-07-15T07:21:27.522Z</atom:updated>
            <content:encoded><![CDATA[<p>Too lazy to read through 2000 comments on Facebook? You’ve come to the right place. Here I’ll use NLTK’s VADER (a Python module) to sift through these comments and see what the hive mind thinks. Warning: it’s surprisingly cheery, like this gif:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F1HPUSulSOHDpe%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F1HPUSulSOHDpe%2Fgiphy.gif&amp;image=http%3A%2F%2Fgiphygifs.s3.amazonaws.com%2Fmedia%2F1HPUSulSOHDpe%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="223" frameborder="0" scrolling="no"><a href="https://medium.com/media/0300d5f2284dea5ddb8a1fdd9d8a1a7a/href">https://medium.com/media/0300d5f2284dea5ddb8a1fdd9d8a1a7a/href</a></iframe><h4>Why?</h4><p>A post by SUTD student <a href="https://medium.com/u/89346f096b53">Jiayu Yi</a> piqued my interest a month ago with its timely and step-by-step method for sentiment analysis of a certain Facebook post — perfect for a beginner like myself to replicate as a toy project. However, instead of using Google Cloud Natural Language API, I will attempt to use <strong>NLTK</strong> to classify comments as positive, negative or neutral instead.</p><p>Having grown up here, besides my intrinsic interest in understanding this and extreme laziness — who has the time to read 2000 comments on Facebook?! — I also wanted to see if using NLTK and running the analysis 1 month later would yield different results.</p><p>The post in question:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*wWDOhpz_qRcpi3eBt0GmhQ.png" /></figure><h4>Goals</h4><ul><li><strong>scraping comments</strong> using the <a href="https://developers.facebook.com/docs/graph-api">Facebook Graph API</a>, and adapting a Python script to collect comments into a text file</li><li>simple <strong>natural language processing</strong> through NLTK and VADER to classify comments as positive/negative/neutral</li></ul><h3>Part 1: Scraping</h3><p>Following Jiayu’s method, I was able to scrape roughly 2.2k comments from the target page into a CSV file. However, instead of using the access token found in the screenshot below, I had to use the Access Token Debugger to fill in the token value in the script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6bNw3t-xOY7k_R7Dr2a-Lg.png" /><figcaption>Your access token is in another castle!</figcaption></figure><h4>Code for scraping</h4><pre>import requests</pre><pre>graph_api_version = &#39;v2.9&#39;<br># paste your access token below<br>access_token = &#39; &#39;</pre><pre># LHL&#39;s Facebook user id<br>user_id = &#39;125845680811480&#39;</pre><pre># the id of LHL&#39;s response post at <a href="https://www.facebook.com/leehsienloong/posts/1505690826160285">https://www.facebook.com/leehsienloong/posts/1505690826160285</a><br>post_id = &#39;1505690826160285&#39;</pre><pre># the graph API endpoint for comments on LHL&#39;s post<br>url = &#39;<a href="https://graph.facebook.com/%7B%7D/%7B%7D_%7B%7D/comments&#39;.format(graph_api_version,">https://graph.facebook.com/{}/{}_{}/comments&#39;.format(graph_api_version,</a> user_id, post_id)</pre><pre>comments = []</pre><pre>r = requests.get(url, params={&#39;access_token&#39;: access_token})<br>while True:<br>    data = r.json()</pre><pre># catch errors returned by the Graph API<br>    if &#39;error&#39; in data:<br>        raise Exception(data[&#39;error&#39;][&#39;message&#39;])</pre><pre># append the text of each comment into the comments list<br>    for comment in data[&#39;data&#39;]:<br>        # remove line breaks in each comment<br>        text = comment[&#39;message&#39;].replace(&#39;\n&#39;, &#39; &#39;)<br>        comments.append(text)</pre><pre>print(&#39;got {} comments&#39;.format(len(data[&#39;data&#39;])))</pre><pre># check if there are more comments<br>    if &#39;paging&#39; in data and &#39;next&#39; in data[&#39;paging&#39;]:<br>        r = requests.get(data[&#39;paging&#39;][&#39;next&#39;])<br>    else:<br>        break</pre><pre># save the comments to a file<br>with open(&#39;comments.txt&#39;, &#39;w&#39;, encoding=&#39;utf-8&#39;) as f:<br>    for comment in comments:<br>        f.write(comment + &#39;\n&#39;)</pre><p>This gives me a text file with one comment on each row.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rYMEm3p1eGbHnif1ZZqyjQ.png" /><figcaption>First comment … …</figcaption></figure><p>Looking through the Facebook page and comparing it with the scraped comments, the symbols in the text file are usually either comments in Mandarin or emojis.</p><h3>Part 2: Quick &amp; Dirty Sentiment Analysis</h3><p>I am going to try to perform this analysis without cleaning it on a small sub-set of data, just to make sure everything works and that it is logical when the comment is read. And voila — although it took a while thanks to my not having installed the lexicon for VADER:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HjyMdrBqB4GiTDucAJ3YAA.png" /><figcaption>Testing took quite a while, thanks to VADER’s missing lexicon</figcaption></figure><h4>Final code for sentiment analysis</h4><pre>import nltk # be sure to have stopwords installed for this using nltk.download_shell()<br>import pandas as pd <br>import string</pre><pre>messages = [line.rstrip() for line in open(&quot;<strong>filepath goes here</strong>&quot;)]</pre><pre>from nltk.sentiment.vader import SentimentIntensityAnalyzer<br># install Vader and make sure you download the lexicon as well<br>sid = SentimentIntensityAnalyzer()<br># this step will return an error if you have not installed the lexicon</pre><pre>summary = {&quot;positive&quot;:0,&quot;neutral&quot;:0,&quot;negative&quot;:0}<br>for x in messages: <br>    ss = sid.polarity_scores(x)<br>    if ss[&quot;compound&quot;] == 0.0: <br>        summary[&quot;neutral&quot;] +=1<br>    elif ss[&quot;compound&quot;] &gt; 0.0:<br>        summary[&quot;positive&quot;] +=1<br>    else:<br>        summary[&quot;negative&quot;] +=1<br>print(result)</pre><p>You should get:</p><pre>{&#39;positive&#39;: 1206, &#39;neutral&#39;: 601, &#39;negative&#39;: 270}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*pCLalv8NMTpCwSA1ur6rOg.png" /><figcaption>Pie chart generated with Excel in approx 5 seconds… Matplotlib another day</figcaption></figure><p>Using this method, with very few lines of code and for <strong><em>absolutely free</em></strong>, I was able to analyse a similar volume of comments.</p><p>However, the results were quite different. Instead of 68% positive, VADER found only 58% of comments were positive; also, instead of 18% negative, VADER was surprisingly upbeat finding only 13% of comments negative.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fjd6TVgsph6w7e%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fjd6TVgsph6w7e%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fjd6TVgsph6w7e%2Fgiphy.gif&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/0cee6de2bd345b762e82e92f4307bb56/href">https://medium.com/media/0cee6de2bd345b762e82e92f4307bb56/href</a></iframe><h4>Odds &amp; Ends</h4><p>Comments were anonymised for this basic analysis. A good follow-up — to identify frequent posters and the tone of their comments.</p><p>Could the differences in my results vs Jiayu’s be due to time, with the later comments shading towards incrementally positive and neutral, or is this due to VADER being ever more sunny than Google? (I am totally loving the pun. Can you tell?)</p><h3>References</h3><ul><li><a href="https://medium.com/google-cloud/sentiment-analysis-of-comments-on-lhls-facebook-page-9db8b3a60eb3">https://medium.com/google-cloud/sentiment-analysis-of-comments-on-lhls-facebook-page-9db8b3a60eb3</a></li><li><a href="http://www.learndatasci.com/sentiment-analysis-reddit-headlines-pythons-nltk/">http://www.learndatasci.com/sentiment-analysis-reddit-headlines-pythons-nltk/</a></li><li><a href="http://nlpforhackers.io/sentiment-analysis-intro/">http://nlpforhackers.io/sentiment-analysis-intro/</a></li><li><a href="https://medium.com/@aneesha/quick-social-media-sentiment-analysis-with-vader-da44951e4116">https://medium.com/@aneesha/quick-social-media-sentiment-analysis-with-vader-da44951e4116</a></li><li><a href="http://www.learndatasci.com/sentiment-analysis-reddit-headlines-pythons-nltk/">http://www.learndatasci.com/sentiment-analysis-reddit-headlines-pythons-nltk/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=422e0f794b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>