<?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 Sophie Zhao on Medium]]></title>
        <description><![CDATA[Stories by Sophie Zhao on Medium]]></description>
        <link>https://medium.com/@sophiezhao713?source=rss-b0c1ee233084------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*quugFfnrczjBGT6oAVuMQQ.jpeg</url>
            <title>Stories by Sophie Zhao on Medium</title>
            <link>https://medium.com/@sophiezhao713?source=rss-b0c1ee233084------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 13:56:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sophiezhao713/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[Improving Road Safety]]></title>
            <link>https://medium.com/swlh/improving-road-safety-d0866ee1d9c4?source=rss-b0c1ee233084------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0866ee1d9c4</guid>
            <category><![CDATA[mathematical-modeling]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[road-safety]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[3d-modeling]]></category>
            <dc:creator><![CDATA[Sophie Zhao]]></dc:creator>
            <pubDate>Sun, 27 Nov 2022 14:04:48 GMT</pubDate>
            <atom:updated>2022-11-27T18:32:25.329Z</atom:updated>
            <content:encoded><![CDATA[<h3>Scheduling Patrol Officers to Improve Road Safety</h3><h3>Context of this story</h3><p>The Cornell Mathematical Contest in Modeling (CMCM) is an annual contest for undergraduate students at Cornell University propose a solution to a real-world mathematical modeling problem. <strong>This year (2022) we are asked to support the Tompkins County Sheriff’s Office in enforcing traffic laws on the roads in Tompkins County. </strong>The following story covers our approach to an algorithm to identify the optimal placements of officers as well as an evaluation model for this algorithm.</p><figure><img alt="Data Visualization of Past Accidents in Tompkins County" src="https://cdn-images-1.medium.com/max/694/0*eL9WyB1h0jLLCYTf" /><figcaption>Data Visualization of Past Accidents in Tompkins County</figcaption></figure><h3>Introduction</h3><p><strong>We want to find a data-driven algorithm to reduce road accidents by scheduling patrol officers throughout the county</strong>. Our algorithm uses past data of <a href="https://docs.google.com/spreadsheets/d/1q54V0sPHYs5b_x0AdwNEq3POJOiOHw_O/edit#gid=397135590">accidents recorded in Tompkins County</a> to do the following:</p><ol><li>model the expected accidents on a certain day of the week</li><li>assign officers to locations in Tompkins County with the highest probability of experiencing an accident</li></ol><p>We incorporated the K-Means Clustering Algorithm to achieve this. We also developed an evaluation model that would score our algorithm by the percentage of accidents we expect it to reduce. The end of this paper features the benefits of our schedule as well as the limitations of our model.</p><h3>1. Scheduling Speed Checks Based on Past Accidents</h3><p>We want to visualize the time and location of past accidents over different days of the week. This shows us where the ideal locations of officers are based on the most dense areas since, these areas represent where we expect accidents to have the highest probability of happening.</p><h4>Visualizing Past Accidents</h4><p>We obtained the latitude and longitude coordinates of past accidents. Then, for each day of the week, we plotted the coordinates against the time of day that the accident happened.</p><figure><img alt="3D scatter plot representing the location and time of accidents recorded on Mondays from
 January 1st to November 1st, 2022" src="https://cdn-images-1.medium.com/max/856/1*Ooam5ZqpQSPZLAYfl0lp7w.png" /><figcaption>Figure 1. 3D scatter plot representing the location and time of accidents recorded on Mondays from January 1st to November 1st, 2022</figcaption></figure><p>In the figure above, we combined data from all Mondays between January 1st to November 1st, 2022 and generated a graph of the location of accidents and the time that they happened. The time axis is scaled such that 0 represents the start of the day (12am) and 1 represents the end of the day (11:59pm). <strong>We then assume that the denser the area, the higher probability that an accident will reoccur there.</strong></p><h4>Applying K-Means Clustering Algorithm</h4><p>Knowing the probability density of accidents in Tompkins County over a day, we want to assign officers such that they can cover a certain space in our location vs. time plots. This represents when and where we ideally want their shift.</p><p>The K-Means Clustering Algorithm partitions the data we have into k clusters, each with a mean such that every point in the plot is assigned to the cluster with the nearest mean. We call each of these means the centroid of its respective cluster.</p><p>We ran this algorithm on our previous plot with k = 3 because Tompkins County currently assigns up to three officers a day to partake in traffic-related activities. <strong>The clusters labeled by the k-means algorithm thus represents the area that we assign to each officer in the case that an accident or incident happens at a certain time with the centroids as the officers.</strong></p><figure><img alt="The result of applying the K-means Clustering Algorithm to the plot in Figure 1." src="https://cdn-images-1.medium.com/max/1024/1*S0DjDJile7moTkfTBMi7Ww.png" /><figcaption>Figure 2. The result of applying the K-means Clustering Algorithm to the plot in Figure 1.</figcaption></figure><p>The yellow centroids in the plot have latitude and longitude coordinates corresponding to locations in Tompkins County where the officers should be deployed.</p><h4>Results</h4><p>After applying the K-means algorithm, our results were to assign officers to handle accidents at the three 8-hour blocks of a 24-hour day at the location with the highest probability of an accident occurring within those 8 hours. We modified these results since it is infeasible to assign an officer to traffic-related activities for 8 hours a day. Instead, we found 2-hour intervals with the highest probability of having road accidents within these 8-hour intervals. The location we suggest they be deployed at is based on the location of the centroid of their respective cluster on the plot.</p><figure><img alt="Time and location to deploy three officers per day over a week." src="https://cdn-images-1.medium.com/max/1024/1*3F-2-ql7RDUqrDC3Bz9_-A.png" /><figcaption>Figure 3. Figure 3: Time and location to deploy three officers per day over a week.</figcaption></figure><p>We should note that the roads given in the schedule above is not the exact coordinate of the centroid but the nearest road or intersection. This is due to the limitation of our algorithm that the centroid does not necessarily map to a road but any point of location in Tompkins County.</p><h3>2. Evaluating the Algorithm</h3><p>To evaluate the effectiveness of our algorithm, we consider the coverage of the deployed officers and assume that their presence will decrease the likelihood of accidents and incidents happening within a certain radius.</p><h4>The Basic Evaluation Model</h4><p>We used the following model to evaluate the effectiveness of our algorithm:</p><figure><img alt="The Basic Evaluation Model" src="https://cdn-images-1.medium.com/max/309/1*LobS-SVGEFbp9kvIG4_QXQ.png" /><figcaption>Figure 4. The Basic Evaluation Model</figcaption></figure><ul><li>n ~ total number of accidents over the desired time interval to evaluate</li><li>y_i, z_i ~ longitude, latitude of the accident</li><li>y_0, z_0 ~ longitude, latitude of the officer</li><li>R ~ radius of region where the presence of an officer has an effect.</li></ul><p>To better interpret this model, take value of the square root term as r, the distance from a past accident to where we want to deploy an officer. The model then evaluates to a summation of (1-r/R). This says <strong>the closer the officer is to the accident, the more likely they are to decrease the chances that another accident happens there.</strong></p><h4>Applying the Basic Model</h4><p>We applied our model to the algorithm with n as the total number of accidents recorded from January 1st to November 1st, 2022. The r values for each data point is the distance to the centroid (officer) of their cluster.</p><p>We estimated a value for R assuming that, if someone is aware of a nearby officer, it will affect their behavior in the area with radius around the incident of about 0.01 latitude distance. This number was estimated with the assumption that someone would be more cautious of their actions and reduce the chance of causing an incident if they were roughly five roads down from an officer or less. In future research, this assumption should be tested and adjusted.</p><p>We also assumed that, if someone were within five roads away from two different, officers, their chances of reducing the probability of an accident decreases by double the amount.</p><p>With these assumptions, we calculated the percent decrease of total number of accidents in Tompkins County and obtained about a <strong>4.6% decrease of number of accidents</strong>.</p><h4>Incorporating Fairness — Prioritizing Specific Incident Types</h4><p>Math modeling aims to produce feasible solutions that can be incorporated in real life. Thus, we considered the fairness of our algorithm and the way we evaluated it. Most importantly, we noticed that there are different types of accidents and incidents that we have thus far treated the same. However, in the law, there are some types of situations that officers would take more priority in resolving than others. For example, a crash that causes more injury or an accident that blocks a highway from being used would take priority over a smaller dispute in a parking lot. With this in mind, we factored in a quantified value of “importance,” I, for each incident i:</p><figure><img alt="Factoring the “importance” of an incident into the evaluation model" src="https://cdn-images-1.medium.com/max/246/1*4yok6R9t1ntPxKKLLmgyiA.png" /><figcaption>Figure 5. Factoring in the “importance” of an incident into the evaluation model</figcaption></figure><p>The importance I of each incident represents the relative importance of that type of incident, decided by the legal system. For example, if officers believe that accidents with “Alcohol Involvement” are the highest priority incidents to take are of, then I(alcohol involvement) = 1. If speeding takes the second highest priority, I(speeding) = 2, etc.</p><p>Factored into the evaluation model, <strong>the algorithm will score higher if priority incidents are reduced</strong>. In this way, we reward our algorithm for reducing higher priority cases.</p><h4>Improving the Evaluation Model</h4><p>Furthermore, to be more accurate in evaluating our algorithm, we want to differentiate between the types of incidents that occur and how likely they are to be avoided when officers are more systematically deployed in areas of high accident concentration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*pDsR46cHOU1SWRENff0-Bw.png" /><figcaption>Figure 6. Factoring in the “control” of an incident</figcaption></figure><p><strong>We included a variable c to represent the amount of control someone has over a type of incident i.</strong> For example, people are less likely to be able to control whether or not they are experienced in driving while they are more likely to stop themselves from drunk driving. Therefore, the control value of “inexperienced driving” will be lower than that of “drunk driving.” We let c vary between 0 (no control) to 1 (full control).</p><p>This variable is important in reflecting which accidents will be reduced more when people are aware of officers in a certain area. For example, if we deploy an officer in an area, we believe that the number of drunk driving accidents will decrease more than the number of inexperienced driving accidents.</p><h3>3. Robustness of the Algorithm</h3><p>In our algorithm, we determined the ideal location and time to deploy three officers for each day of the week. However, we want to be respectful of officers’ personal schedules. In the case that officers are not able to be at the specific times and locations we originally hoped, we would change our algorithm so it does not depend on time but instead prioritizes the locations for officers to go relative to their personal schedules.</p><p>As in our original algorithm, we used the clustering but without regards to time, only location, by finding the longitude and latitude coordinates of each cluster’s centroid. This gives us locations where we would suggest the officers be deployed no matter at what time. Realistically, this allows for more flexibility in officers’ schedules.</p><figure><img alt="Heat maps of the probability density of an accident occurring from 12–8am, 8am-4pm, and 4pm-12am in Tompkins County" src="https://cdn-images-1.medium.com/max/793/1*Fjkbu2XsDiccLZtNfW4GbA.png" /><figcaption>FIgure 7. Heat maps of the probability density of an accident occurring from 12–8am, 8am-4pm, and 4pm-12am in Tompkins County</figcaption></figure><p><strong>The brightest spots in the heatmaps above are the locations where we would deploy officers because these locations have the highest probability of having accidents based on past data</strong>. These maps only consider the priority locations where we might want to deploy officers without regards to specific times of the day.</p><h3>4. The Value of Our Algorithm and Model</h3><h4>Systematic Assignment</h4><p>Based on records of past accidents and incidents, our algorithm gives a <strong>data-driven prediction of the probability of future incidents</strong>. This allows us to assign officers in a more systematic way by identifying regions with the highest probability of needing an officer present, which also allows us to determine the ideal locations and times to deploy an officer.</p><h4>Prioritizing Incidents</h4><p>Our evaluation model holds our algorithm up to higher standards by allowing us to <strong>set priorities for the incidents we want to reduce the most</strong>. In this way, we factor in fairness based on what our society prioritizes and allows us to incorporate more subjective perspectives on what “Road Safety” means in terms of reducing specific types of accidents.</p><h4>Incorporating Officer Schedules</h4><p>In a more robust version of our model, we only considered the location where we want officers to be. In this case, by forgoing the time requirement, <strong>we allow officers more freedom in the time of their shifts by simply giving priority to locations</strong>, even if they cannot be there at the ideal hour we predict to have an accident.</p><h3>5. Future Improvements</h3><p>Finally, we want to discuss the assumptions and simplifications we have made. They are factors we would address and aim to improve if given more time and resources.</p><h4>Assignment by Road, not Region</h4><p>Assuming that it would be easier and more convenient for an officer to drive on a long road rather than take on a certain region of parallel roads, for example, we would try to cluster or group roads by travelling feasibility and convenience rather than flat distance. Moreover, our results currently might identify a centroid that does not land on a drivable road. Therefore, we want our algorithm to identify the nearest road or important intersection to assign the officer to.</p><h4>Movement of Officers</h4><p>In our algorithm, we assigned an officer a certain area and assume that they would stay there for the duration of their shift. However, officers are mobile people that can drive up and down roads. Their location would also change if they went to take care of an accident. Thus, an improved model would account for the movement of the deployed officers throughout their assigned shift and area by simulating the most likely accidents and how the officers would move relative to them.</p><h4>Data Collection and Usage</h4><p><strong>We obtained the latitude and longitude of the data through the Google Extension, Geocode</strong>. Geocode identifies the latitude and longitude of a specific address, but the data we have access to is not a specific location but an entire road. Therefore, when pinpointing the location of that road, Geocode will find a generally random point on that road, not necessarily representing the exact location of the accident. However, this data is usable because it tells us the roads that are most prone to accidents and thus it still makes sense to deploy officers to these locations on the map.</p><p>Additionally, the Tompkins County Sheriff’s Office also includes data on smaller incidents that may not have as much weight as accidents, but considering them would more accurately allow us to determine when and where we expect officers to be called by the residents of Tompkins County.</p><h4>Verifying Accident Trends</h4><p>Another assumption we are making in using the data is that the trend of accidents happen weekly. Therefore, we assumed that we are able to use the data from past days of the week (e.g. Mondays, Tuesdays, etc.) to predict accidents in future days of the week. The accuracy of this should be evaluated by plotting the patterns of accidents and looking for the most consistent pattern over a different time intervals.</p><h4>Incorporating Officers’ Personal Schedules</h4><p>To make our algorithm more robust, we allowed it to forgo the consideration of time and instead only show the locations that are the most in need of officers. However, if given the officers’ personal schedules, we would find the area most likely in need of an officer during that time period when they are on duty and assign them to that location. Our algorithm would find the location over a certain time period that has the highest probability of experiencing an accident or incident and assign the officer to that area. The algorithm would also detect if there is already an officer deployed to an area. Then we would lower the priority of assigning another officer there and focus on areas farther away from officers already deployed.</p><h4>Evaluating Variations of the Algorithm</h4><p>Given more time to modify our data and algorithm, we would use our evaluation model on data that removes outliers, prioritizes areas of highest probability of accidents, and also finding a more accurate value of R. Recall that the value of R considers how far away a person has to be for the presence of an officer to stop influencing their actions of reducing accidents. This information would do well to be updated based on real world data collected overtime in response to the development of a more centralized planning for patrol officers.</p><p>Note: this submission to the 2022 Cornell Mathematical Contest in Modeling (CMCM) received an Honorable Mention.</p><p>References:</p><ul><li>E.F. Sam, How effective are police road presence and enforcement in a developing country context?, Humanities and Social Sciences Communications, 9 (2022), no. 5</li><li>M.D. Thomas, Deployment of state traffic law enforcement officers for Homeland Security, Masters thesis, Naval Postgraduate School, Monterey.</li><li>E. Hardy, Data-Driven Policing: How Geographic Analysis Can Reduce Social Harm, Geography and Public Safety, 2 (2010), no. 3</li><li>M. Rezapour, S. Wulff, K. Ksaibati, Effectiveness of enforcement resources in the highway patrol in reducing fatality rates, International Association of Traffic and Safety Sciences, 42 (2018), no. 4, 259–264</li><li>Abdishakur, Geocode with Python, Towards Data Science, <a href="https://towardsdatascience.com/">https://towardsdatascience.com/</a> geocode-with-python-161ec1e62b89</li><li>G. Hopping, Modeling the Risk of Traffic Accidents in New York City, Towards Data Science, <a href="https://towardsdatascience.com/modeling-the-risk-of-traffic-accidents-in-new-york-city9292c5ae4ab4">https://towardsdatascience.com/modeling-the-risk-of-traffic-accidents-in-new-york-city9292c5ae4ab4</a></li></ul><p>Contest Team: Grace Liu, Julia Zeng, Sophie Zhao</p><p>Contest Webpage: <a href="https://e.math.cornell.edu/sites/mcm/">https://e.math.cornell.edu/sites/mcm/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0866ee1d9c4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/improving-road-safety-d0866ee1d9c4">Improving Road Safety</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Secret Santa Organizer]]></title>
            <link>https://sophiezhao713.medium.com/secret-santa-organizer-bebb2c2fd905?source=rss-b0c1ee233084------2</link>
            <guid isPermaLink="false">https://medium.com/p/bebb2c2fd905</guid>
            <category><![CDATA[christmas-gifts]]></category>
            <category><![CDATA[randomnamepicker]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[automated-email]]></category>
            <category><![CDATA[secret-santa]]></category>
            <dc:creator><![CDATA[Sophie Zhao]]></dc:creator>
            <pubDate>Sat, 18 Dec 2021 20:01:08 GMT</pubDate>
            <atom:updated>2022-12-23T04:36:08.473Z</atom:updated>
            <content:encoded><![CDATA[<h3>Automated Emailing</h3><p>Last Christmas, I was organizing a Secret Santa activity for students in my high school’s book club. This activity assigns every student as someone else’s Secret Santa. Each Santa would then choose a book as a present to the person they were assigned. Thus, every student would receive a book suggestion from a secret member of the club. The full rules of Secret Santa can be found here: <a href="https://www.elfster.com/secret-santa-rules/">https://www.elfster.com/secret-santa-rules/</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vs8yuBzI6mCqxojEqUtcYg.jpeg" /><figcaption><a href="https://www.xperiencedays.com/a-guide-to-secret-santa-dos-and-donts">https://www.xperiencedays.com/a-guide-to-secret-santa-dos-and-donts</a></figcaption></figure><p>The problem was assigning Secret Santas. We could not meet in person due to COVID-19, so we could not randomize the Secret Santas with a hat draw. However, if I had was to assign them myself, I could not join in on the game, because I would have to assign my own Secret Santa. Therefore, <strong>I programmed a Python program to help me assign Secret Santas to each student.</strong></p><p>My code had two major parts: the algorithm to assign Secret Santas, and the sending of emails through Python. The email would tell each person who they are the Secret Santa for. In other words, they would be sent the person they should choose a book for.</p><h3>Assigning Secret Santas</h3><p>My requirements to assign Secret Santas was to 1) randomize the assignments and 2) make sure no one is assigned to themselves. To do this, I used the random library and pandas library to organize the participants.</p><pre>import random<br>import pandas as pd</pre><pre><strong><em>#Participants.xlsx is an excel file of names to emails</em></strong><br>file = pd.read_excel(&#39;Participants.xlsx&#39;)<br>names = file[&quot;Name&quot;]<br>emails = file[&quot;Email&quot;]</pre><p>With a list of names and emails from the Participants excel file, I created a dictionary to map people’s emails to their names. This dictionary would look like this:</p><p>{“Student A”: “Email A”,</p><p>“Student B”: “Email B”,</p><p>“Student C”: “Email C”, …}</p><pre>data = {}<br>for i in range(len(names)):<br>    data[names[i]] = emails[i]</pre><p>The next block of code is the algorithm that allowed me to randomly assign Secret Santas based on the data. This information was stored in a dictionary that would email a student the person they need to send a book to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kIGeSkT8QeeLm5cH7welvQ.gif" /><figcaption><a href="https://blog.elfster.com/2020/08/19/how-to-use-a-pick-names-out-of-a-hat-app/">https://blog.elfster.com/2020/08/19/how-to-use-a-pick-names-out-of-a-hat-app/</a></figcaption></figure><p>For example, if assignment looked like this:</p><p>{“Email A”: “Student C”,</p><p>“Email B”: “Student A”,</p><p>“Email C”: “Student B”…}</p><p>then the program would tell Student A (Email A) to choose a book for Student C. And send Student B (Email B) an email to choose a book for Student A, etc.</p><pre>assignments = {}<br>length = len(data)<br><br>for n in range(length):<br>    index = random.randint(0, length-1)<br>    person = names[index]<br>    assignments[data[names[n]]] = person<br>    while names[n] == assignments[data[names[n]]]:<br>        index = random.randint(0, length-1)<br>        person = names[index]<br>        assignments[data[names[n]]] = person<br>    del data[names[n]]<br>    length = len(data)</pre><p>With the assignments decided, it’s time to send the emails.</p><h3>Sending Emails — Automated</h3><p>In order for my program to send automated emails through Python, I used the smtplib module. Here is a more detailed article explaining the steps to sending emails with Python: <a href="https://realpython.com/python-send-email/">https://realpython.com/python-send-email/</a>.</p><pre>import smtplib, ssl<br>port = 465  <strong><em>#For SSL</em></strong><em><br></em>smtp_server = &quot;smtp.gmail.com&quot;</pre><pre>organizer_email = &quot;email&quot; <strong><em>#Your gmail</em></strong><br>organizer_password = &quot;password&quot; <strong><em>#Your gmail password</em></strong><br><br>for email in assignments:<br>    message = &quot;&quot;&quot;\ <br>    <strong><em>#message content sent to each student</em></strong></pre><pre>    Subject: Secret Santa Assignment<br><br>    The person you should send a book to for Secret Santa is &quot;&quot;&quot; +<br>    assignments[email]<br><br>    context = ssl.create_default_context()<br>    with smtplib.SMTP_SSL(smtp_server, port, context=context) as <br>    server:<br>        server.login(organizer_email, organizer_password)<br>        server.sendmail(organizer_email, email, message)</pre><h3>Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*cx9hbrNs3ohGLYf1qctZTQ.png" /><figcaption><a href="https://justcreative.com/ecommerce-email-automation/">https://justcreative.com/ecommerce-email-automation/</a></figcaption></figure><p>Using a Python algorithm, I was able to randomize assignments for a Secret Santa activity. All I needed to have was a spreadsheet of participants and their emails. The program is then able to automatically send each participant an email containing the person they were assigned. This program allowed me, the organizer, to be able to join the game as well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bebb2c2fd905" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Email Tool for Recruiters and Marketers]]></title>
            <link>https://medium.com/codex/email-tool-for-recruiters-and-marketers-25b7753938d5?source=rss-b0c1ee233084------2</link>
            <guid isPermaLink="false">https://medium.com/p/25b7753938d5</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[email-marketing]]></category>
            <category><![CDATA[recruiting]]></category>
            <category><![CDATA[marketing-tools]]></category>
            <category><![CDATA[email-generator]]></category>
            <dc:creator><![CDATA[Sophie Zhao]]></dc:creator>
            <pubDate>Sat, 20 Mar 2021 21:29:20 GMT</pubDate>
            <atom:updated>2021-03-23T14:15:36.666Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="http://medium.com/codex">CODEX</a></h4><h3>Deducing Emails for Recruiting and Marketing</h3><p>Mentor: Sining Chen</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JgMMwzOo38aUncvmKCWDdA.png" /><figcaption><a href="https://hipwallpaper.com/marketing-wallpapers/">https://hipwallpaper.com/marketing-wallpapers/</a></figcaption></figure><h3>Introduction</h3><p>Linkedin allows recruiters to contact potential candidates through messages and emails. However, not only does this tool require a paid recruiters account, but not everyone on Linkedin provides their email, either. I wanted to create a tool that deduces email addresses from a person’s name and affiliation (company/university).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*aSRQ5wo7rnH1grw7SDtsTA.png" /><figcaption><a href="https://resources.workable.com/tutorial/recruiting-linkedin">https://resources.workable.com/tutorial/recruiting-linkedin</a></figcaption></figure><h3>How it Works</h3><p><strong>Given a person’s name and affiliation, my tool will generate an email based on templates derived from known emails.</strong></p><p>For example, if I were a worker at Facebook, my email might look like sophiezhao@fb.com. My Python code would deduce that the <strong>template </strong>for a Facebook email is [first_name][last_name]@fb.com. It would then be able to generate an email for John Smith as johnsmith@fb.com. Note that emails are formatted as handle.domain (we need to be given the company’s <strong>domain </strong><em>fb.com</em> to deduce the <strong>handle </strong><em>johnsmith).</em></p><p>We start by deducing the templates from known emails (<strong>seeding emails</strong>), which are saved in a database starting with emails from our personal contacts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WLqHU4nNzQxQh7G7xFh3Fg.png" /><figcaption>Example for generating emails from templates based on the seeding database</figcaption></figure><p>I used a variety of libraries and functions in Python to do this. First, I used a downloaded spreadsheet from Gmail with information regarding people’s names and emails. This data needed to be cleaned in a <strong>CSV </strong>file to remove empty entries and non-existent names like “Notifications” or “2293ef1a80fb00de1631299.” Next, I saved this data into a dictionary of <strong>profiles</strong>, which mapped each person’s information to the <strong>company </strong>their email originates from. Finally, the Python algorithm generated templates from these profiles and map them to each company’s email domain. These templates allowed me to generate hypotheses of a person’s <strong>email address</strong> as long as I had their name and company’s domain.</p><h3>Cleaning Data from the Seeding Database</h3><p>Gmail saves data on the people I have emailed before. By exporting my Contacts to a Google CSV, I have a spreadsheet of information including the people’s names and emails.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iEYK__6dB8mToduP8bl5-w.png" /><figcaption>Export Contacts from Gmail from the app</figcaption></figure><p>However, the file does not have accurate names for every user, and many entries are empty. There are many reasons for this: Google does not have all possible information on everyone, some people will use an alias, and many emails are from sales or automatic replying machines. Therefore,<strong> I needed to clean the data until it only contained known full names, first names, last names, and emails.</strong></p><p>I first read in the CSV file with raw data from Gmail. The encoding statement allows the program to read all characters in the file.</p><pre>import csv<br>csv = csv.reader(open(&#39;Gmail-contacts&#39;, encoding=&#39;utf-8&#39;))</pre><p>I removed the first row of the data, which are labels for each column. I then wrote two functions to check for 1) empty entries and 2) non-alphabetical names.</p><pre><em>#</em><strong><em>checks if null value exists in row</em></strong><em><br></em>def isNotNull():<br>    if row[0] != <strong>&#39;&#39; </strong>and row[1] != <strong>&#39;&#39; </strong>and row[2] != <strong>&#39;&#39; </strong>and row[3] != <br>    <strong>&#39;&#39;</strong>:<br>        return True<br>    return False<br><br><em>#</em><strong><em>checks if first and last name are string</em></strong><em><br></em>def rowIsString():<br>    if all(x.isalpha() or x.isspace() for x in row[0]) and<br>    row[1].isalpha() and row[2].isalpha():<br>        return True<br>    return False</pre><p>To remove names that are aliases or not real names in general, I used the NameDataset from names_dataset, which can be found in the following github page: <a href="https://github.com/philipperemy/name-dataset">https://github.com/philipperemy/name-dataset</a></p><pre>from names_dataset import NameDataset<br>n = NameDataset()</pre><p>The dataset checks if the first names and last names given by Gmail are existing names as opposed to words like “Reply” or “Notification” or random strings like “2293ef1a80fb00de1631299.”</p><pre>#<strong><em>checks if firstname is a known first name<br></em></strong>n.search_first_name(firstname)</pre><pre>#<strong><em>checks if lastname is a known last name<br></em></strong>n.search_last_name(lastname)</pre><p>Next, the following code uses these cleaning functions to generate profiles of people in a dictionary.</p><pre>profiles = [] #<strong><em>list of dictionary of profiles<br></em></strong>domain_handle = {} #<strong><em>dictionary that maps domains to handles</em></strong></pre><pre>for row in csv:</pre><pre>    profile = {&quot;name&quot;: row[0].lower(), &quot;firstname&quot;: row[1].lower(), <br>    &quot;lastname&quot;: row[2].lower(), &quot;email&quot;: row[3].lower(), &quot;handle&quot;: <br>    row[3].split(&quot;@&quot;)[0].lower(), &quot;domain&quot;: row[3].split(&quot;@&quot;)<br>    [1].lower()}</pre><pre>    profiles.append(profile)<br>    domain = profile[&quot;domain&quot;]</pre><pre>    #<strong><em>mapping profiles to domains<br>    </em></strong>if domain in domain_handle.keys():<br>        domain_handle[domain].append(profile)<br>    else:<br>        domain_handle[domain] = [profile]</pre><p>An example of a profile:</p><pre>#<strong><em>dictionary containing a person&#39;s full name, first name, last name, and email information.</em></strong></pre><pre>{&quot;name&quot;: &quot;sophie zhao&quot;,<br>&quot;firstname&quot;: &quot;sophie&quot;,<br>&quot;lastname&quot;: &quot;zhao&quot;,<br>&quot;email&quot;: &quot;sophiezhao@fb.com&quot;,<br>&quot;handle&quot;: &quot;sophiezhao&quot;,<br>&quot;domain&quot;: &quot;fb.com&quot;}</pre><p>And an example key value pair in the domain_handle dictionary:</p><pre>#<strong><em>mapping email domains to their profiles</em></strong></pre><pre>{&quot;fb.com&quot;:[{&quot;name&quot;: &quot;sophie zhao&quot;, &quot;firstname&quot;: &quot;sophie&quot;,<br>            &quot;lastname&quot;: &quot;zhao&quot;, &quot;email&quot;: &quot;sophiezhao@fb.com&quot;, <br>            &quot;handle&quot;: &quot;sophiezhao&quot;, &quot;domain&quot;: &quot;fb.com&quot;},</pre><pre>           {&quot;name&quot;: &quot;sining chen&quot;, &quot;firstname&quot;: &quot;sining&quot;,<br>            &quot;lastname&quot;: &quot;chen&quot;, &quot;email&quot;: &quot;s.chen@company.com&quot;,<br>            &quot;handle&quot;: &quot;siningchen&quot;, &quot;domain&quot;: &quot;company.com&quot;}]}</pre><p>After sorting each person’s information into such dictionaries, I could move on to generating the templates for each domain.</p><h4>Generating Handle Template</h4><p>To generate a template from each email handle, I separated the handle by types of characters. This allows me to identify each part of the handle separately based on whether it is a string, special character, or number. This used Python’s regular expression (regex) library to separate the different types of characters.</p><pre>import re</pre><pre>def chartype(char):</pre><pre>    #<strong><em>checks if char is in the alphabet<br></em></strong>    if re.findall(&quot;[a-zA-Z]&quot;, char.lower()):<br>        return &quot;string&quot;</pre><pre>    #<strong><em>checks if char is any of the listed special characters<br></em></strong>    elif char in &quot;!#$%&amp;&#39;*+-/=?^_`{|}~.&quot;:<br>        return &quot;special&quot;</pre><pre>    #<strong><em>otherwise, char is a number<br></em></strong>    else:<br>        return &quot;num&quot;</pre><p>As I iterate through the handle, it splits where the character type of two adjacent characters differ.</p><pre>split_handle = [] #<strong><em>list of handle parts split by character type</em></strong></pre><pre>for i in range(len(handle) - 1):<br>    if chartype(handle[i]) != chartype(handle[i + 1]):<br>        split_handle.append(handle_copy[start:i + 1])<em><br>        </em>start = i + 1<br>split_handle.append(handle_copy[start:])</pre><p>Examples:</p><p>sophie.zhao → [“sophie”, “.”, “zhao”]</p><p>sophiezhao70 → [“sophiezhao”, “70”]</p><p>I can now tackle each part of the handle individually to create the template. Each part of an email’s handle will either be a string, special character(s), or number(s).</p><p><strong>Case 1: The handle part is a string</strong></p><p>I assume that strings in a handle is composed of the person’s first name, last name, both, or parts of their name. The template thus needed to reflect how many characters of each name is in the handle and in what order.</p><p>Examples for Sophie Zhao:</p><p>Handle: <strong>zsoph</strong>→ 1 letter of last name, 4 letters of first name</p><p>Template: [[“lastname”, 1], [“firstname”, 4]]</p><p>Handle: <strong>zhao </strong>→ full last name (use length 0)</p><p>Template: [[“lastname”, 0]]</p><p>There are two functions I used to deduce the template for a string.</p><p>1. <strong>num_match(haystack, needle)</strong> finds the substring <em>needle</em> in a longer string <em>haystack.</em> This function would return the length of the first name that exists in the handle part. I would find that there is 4 letters of <em>sophie </em>in <em>zsoph</em>. Note that this function assumes that we would only take the first part of the haystack. I made this assumption based on how emails tend not to use the middle or end of a name as the handle (it would more likely be <em>zsoph</em> instead of z<em>phie</em>).</p><pre>def num_match(haystack, needle):<br>    if needle[0] in haystack:<br>        for i in range(len(needle)+1):<br>            needle_part = needle[:len(needle)-i+1]<br>            start = haystack.find(needle_part)<br>            if start &gt; -1:<br>                return len(needle_part)<br>    return 0</pre><p>2. <strong>matchname(string)</strong> finally adds the identified parts of the string to the template in order.</p><pre>def matchname(string):<br>    template = []<br>    match_len = num_match(string, profile[&quot;firstname&quot;])<br>    #<strong><em>checks if the part of the first name identified comes <br>    before or after the part of the last name<br></em></strong>    if string[:match_len] == profile[&quot;firstname&quot;][:match_len]:<br>        template.append([&quot;firstname&quot;, match_len])<br>        template.append([&quot;lastname&quot;, len(string)-match_len])<br>    else:<br>        template.append([&quot;lastname&quot;, len(string) - match_len])<br>        template.append([&quot;firstname&quot;, match_len])<br>    return template</pre><p><strong>Case 2: The handle part is a special character</strong></p><p>For special characters, the corresponding part of the template will simply be that special character.</p><p>Example:</p><p>sophie.zhao → [[“firstname”, 0], “.”, [“lastname”, 0]]</p><p><strong>Case 3: The handle part is a number</strong></p><p>When dealing with numbers, I indicate how many numbers are present in the handle using “num”. When generating future emails, num values will be substituted with 0s.This is because the program could not deduce where the numbers come from. The numbers could be to separate people of different names or simply be random. Therefore, I simply used 0 as a placeholder.</p><p>Example:</p><p>sophiezhao70 → [[“firstname”, 0], [“lastname”, 0], [“num”, 2]]</p><p>The code below translates each part of the handle to their corresponding place in the template.</p><pre>for element in split_handle:</pre><pre>    if chartype(element[0]) == &quot;string&quot;:<br>        for i in range(len(matchname(element))):<br>            template.append(matchname(element)[i])</pre><pre>    elif element[0] in &quot;!#$%&amp;&#39;*+-/=?^_`{|}~.&quot;:<br>        template.append(element)</pre><pre>    else:<br>        template.append([&quot;num&quot;, len(element)])</pre><p><strong>Additional Notes: </strong>If the algorithm was not able to find instances of a name, its length will be 0, so I removed these. Also, if the part of the name was in fact the full first name or last name, I replaced the length with 0 to indicate that the full length should be used.</p><p>Once each handle was translated into a template and mapped to its corresponding domain, I could then use these templates to generate new email addresses.</p><h4>Generating New Emails</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*9iYrQi2aADswPZy5YwmVHQ.png" /><figcaption><a href="https://marketingland.com/7-email-trends-die-2016-160925">https://marketingland.com/7-email-trends-die-2016-160925</a></figcaption></figure><p>The prerequisites of generating an email is to have the person’s first name, last name and company email domain. Assuming I have a template of the domain’s handles, I can simply convert each part based on the information I have of the person’s name and domain template.</p><pre>#<strong><em>domain_template is a dictionary of templates mapped to domains</em></strong></pre><pre>#<strong><em>profile is where I would store the information of the person whom I&#39;m generating an email for.</em></strong></pre><pre>#<strong><em>Generates all possible emails based on templates that exist for each domain</em></strong></pre><pre>for template in domain_template[profile[&#39;domain&#39;]]:</pre><pre>    email_handle = &quot;&quot;</pre><pre>    for element in template:<br>        try:<br>            #<strong><em>if part is a special character, simply add the <br>            element to the handle<br>            </em></strong>email_handle = email_handle + element</pre><pre>        except:<br>            length = element[1]<br>            #<strong><em>add 0s in instances of numbers<br></em></strong>            if element[0] == &quot;num&quot;:<br>                email_handle = email_handle + &quot;0&quot;*length</pre><pre>            #<strong><em>add full or parts of first and last names <br></em></strong>           elif length == 0:<br>                part = profile[element[0]]<br>                email_handle = email_handle + part</pre><pre>            else:<br>                part = profile[element[0]]<br>                email_handle = email_handle + part[:length]</pre><pre>    #<strong><em>finally, add on given domain</em></strong><br>    email = email_handle + &quot;@&quot; + email_domain</pre><p>Examples for full name John Smith:</p><p>[[“firstname”, 0], “.”, [“lastname”, 0]] → john.smith@fb.com</p><p>[[“lastname”, 2], [“firstname”, 4], [“num”, 2]] → smjohn00@fb.com</p><p>With this algorithm, I could successfully generate hypotheses of people’s email addresses based on their name and company domain.</p><h3>Success Rate</h3><p>The key word in my success statement is “hypotheses”. There were many assumptions I made along the way, and there are factors of email addresses that I am simply unable to deduce without excessive infomation and details.</p><p>My dataset of email addresses contained 405 testable email addresses. I created templates using this dataset, then tested the templates against the same email addresses to see if I could reproduce them.</p><p>Using all the emails, I could successfully reproduce <strong>45.9%</strong> emails.</p><p>I then only used the 131 emails that ended in .edu. In other words, I only tested emails of university institutions, which eliminates personal emails with Gmail and Yahoo domains as well as other companies.</p><p>Using emails from university institutions, the success rate was <strong>48.1</strong>%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*1-p0iIiTB2XMezpMUvSRag.jpeg" /><figcaption><a href="https://clipartstation.com/steps-to-success-clipart-9/">https://clipartstation.com/steps-to-success-clipart-9/</a></figcaption></figure><p>Although the second success rate did not seem like a big difference, it is much more accurate. The first success rate of 45.9% included personal emails. My algorithm stores all possible templates for each domain, so it produced many templates for Gmail and Yahoo addresses. Therefore, although it could successfully reproduce those emails, the correct email would be hidden among a dozen other possibilities. On the other hand, the .edu emails have less variety in their formats making the success rate more meaningful and likely to be accurate in a real world situation.</p><p>This leads us into the limitations and assumptions of my program.</p><h3>Limitations and Assumptions</h3><p>Although the program can successfully generate templates and reproduce just under 50% of the emails, it is flawed by the assumptions and limitations below.</p><h4>1. Multiple Possibilities</h4><p>As previously mentioned, the program generates possible emails for each person based on the templates I found for each domain. Therefore, we would not actually know which email is correct. However, this is not a major problem if one does not mind emailing all the possibilities since the correct one is likely to be among them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*rl5XpY4a-6e4UvNnsWet-g.png" /><figcaption><a href="https://www.pngkey.com/detail/u2q8w7o0o0q8o0o0_dice-vector/">https://www.pngkey.com/detail/u2q8w7o0o0q8o0o0_dice-vector/</a></figcaption></figure><h4>2. Arbitrary Numbers</h4><p>A major setback of trying to generate emails is numbers. Since it is very difficult and sometimes impossible to determine the reasons for numbers in a person’s email, this limits the template. For example, if John Smith’s email was johnsmith7@fb.com, the number 7 might be random, John’s preference, or based on a system generating Facebook emails, but essentially I do not know where the 7 came from. The success rate is thus reduced by every email template including numbers that needed to be replaced by 0s.</p><h4>3. Aliases</h4><p>Especially for personal emails, a person’s email handle does not necessarily reflect their real name, either. These cases include internet aliases like magic.unicorn@gmail.com and variations of names like j.m.smith@gmail.com where the first “m” comes from John’s middle name, which was not taken into consideration. For my data specifically, there were a number of emails that used a person’s native name when Gmail only gave me their English name. These are all issues that make the algorithm inaccurate.</p><h3>Summary</h3><p>Ultimately, for companies and intuitions whose emails are made up of purely parts of a person’s first name, last name, and special characters, my program has great successes. However, due to the complexity of emails, the success rate of the program is decreased. This story shows my attempt at deducing emails, inspired by Linkedin’s recruiter tools.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*US-9b3JMQvY3ekH2rxInSg.png" /><figcaption><a href="https://www.pinclipart.com/maxpin/TRxbT/">https://www.pngkey.com/detail/u2q8w7o0o0q8o0o0_dice-vector/</a></figcaption></figure><h3>Next Steps</h3><p>Ideally, a web application would take in a person’s full name and company and deduce their email. This application must be backed by a large database that has deduced templates for the necessary companies and their domains.</p><p>Perhaps by setting more guidelines to the types of emails this program could successfully deduce, the algorithm will have a higher success rate with a certain category of institutions to focus on. This is a topic worth researching further.</p><p>Moreover, a factor not covered in this story is the connection of companies to their domains. Normally, we would know someone by their name and company, but what is the email domain associated with their company? Therefore, an additional layer would be coming up with a company’s domain from its name, which may use similar strategies like regular expression and string similarity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25b7753938d5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/email-tool-for-recruiters-and-marketers-25b7753938d5">Email Tool for Recruiters and Marketers</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LinkedIn Scraper]]></title>
            <link>https://levelup.gitconnected.com/linkedin-scrapper-a3e6790099b5?source=rss-b0c1ee233084------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3e6790099b5</guid>
            <category><![CDATA[beautifulsoup]]></category>
            <category><![CDATA[scraping]]></category>
            <category><![CDATA[linkedin]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[selenium]]></category>
            <dc:creator><![CDATA[Sophie Zhao]]></dc:creator>
            <pubDate>Sat, 12 Sep 2020 20:59:00 GMT</pubDate>
            <atom:updated>2020-09-26T23:20:13.923Z</atom:updated>
            <content:encoded><![CDATA[<h3>How I Scraped LinkedIn Data Using Selenium and Beautiful Soup</h3><p>Mentor: Sining Chen</p><p><strong>LinkedIn </strong>is a social network designed for professional networking and is greatly employment-oriented. Its website and applications include hundreds of millions of professional user profiles as well as job postings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RfN2twgXUiJFmNnbL1d1hw.png" /><figcaption>Image taken from <a href="https://aeroleads.com/blog/linkedin-lead-extractor/">https://aeroleads.com/blog/linkedin-lead-extractor/</a></figcaption></figure><p>In order to gain insight into the job market as demonstrated by LinkedIn, we used web scraping tools written in Python: <strong>Selenium </strong>and <strong>Beautiful Soup</strong>. This story covers how you may install a selenium <strong>webdriver </strong>and Beautiful Soup onto your computer with pip in order to access the information we see on LinkedIn. Especially by using a webpage’s <strong>source code</strong>, we created automated functions like <strong>inputting text</strong> in a search box, clicking <strong>buttons</strong>, and <strong>scraping</strong> <strong>text</strong>. To do this, we had to overcome a few challenges including <strong>differentiating between Selenium and Beautiful Soup</strong>, <strong>locating the elements</strong> we needed to access, and avoiding the errors brought by the <strong>messaging</strong> <strong>pop-up</strong>.</p><p>We also visualized the trends shown by our data. Our graphs are displayed in our other story, which is linked below: <a href="https://medium.com/@sophie14159/linkedin-job-trends-2dd64f1d4541">https://medium.com/@sophie14159/linkedin-job-trends-2dd64f1d4541</a></p><h4>Selenium</h4><p>Selenium Python provides an API that allows you to access webdrivers including Firefox, Internet Explorer, and Chrome, which will be demonstrated later on.</p><h4>Beautiful Soup</h4><p>Beautiful Soup is a python library that allows us to scrape information from web pages by accessing their source code. This uses an HTML or XML parser.</p><p>More information can be found with other resources at the end of this story.</p><h3>Installations</h3><p>In order to scrape from a webpage like those in LinkedIn, we must install selenium, Beautiful Soup and a webdriver.</p><ol><li><strong>Installing pip</strong></li></ol><p>I needed to install both pip and selenium onto my laptop, and I did this using the Command Prompt. I first installed pip.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*U8F7tA5_W6JcZndDY39WJA.png" /><figcaption>Installing pip and redirecting path using Command Prompt on Windows</figcaption></figure><p>Note: Since I already had pip downloaded, it was uninstalled and reinstalled to have the newest version. Then, to access pip and install selenium, I needed to use “pip install selenium”. However, as the warning suggests, I also needed to change the path with “cd” to access pip.</p><p><strong>2. Installing Selenium and Beautiful Soup</strong></p><p>With pip successfully installed and able to be accessed, I simply used the commands “pip install selenium” and “pip install bs4”. Thus, Selenium and Beautiful Soup were successfully installed as well. We are now able to use them in our python scripts.</p><p><strong>3. Download webdriver</strong></p><p>In my case, I decided to use a chromedriver although, as mentioned before, Selenium is not limited to Chrome. Depending on which version of Chrome I had, I used the following site to download the chromedriver: <a href="https://chromedriver.chromium.org/downloads">https://chromedriver.chromium.org/downloads</a>.</p><p>Note: If you are unsure which version of chrome you have, you may follow the instructions <a href="https://help.zenplanner.com/hc/en-us/articles/204253654-How-to-Find-Your-Internet-Browser-Version-Number-Google-Chrome#:~:text=1)%20Click%20on%20the%20Menu,number%20can%20be%20found%20here.">here</a>.</p><p>With Selenium, Beautiful Soup, and a webdriver set up, we are ready to write our code!</p><h3>Python Script</h3><pre><strong>#import chrome webdriver<br></strong>from selenium import webdriver</pre><pre>browser = webdriver.Chrome(&#39;chromedriver_win32/chromedriver.exe&#39;)</pre><p>In the code above, we imported the chromedriver, which will now allow us to access webpages from the chrome browser. Next, I logged into my LinkedIn account to access those webpages.</p><pre><strong>#Open login page</strong><br>browser.get(&#39;https://www.linkedin.com/login?fromSignIn=true&amp;trk=guest_homepage-basic_nav-header-signin&#39;)<br><br><strong>#Enter login info:</strong><br>elementID = browser.find_element_by_id(&#39;username&#39;)<br>elementID.send_keys(username)<br><br>elementID = browser.find_element_by_id(&#39;password&#39;)<br>elementID.send_keys(password)</pre><pre><strong>#Note: replace the keys &quot;username&quot; and &quot;password&quot; with your LinkedIn login info</strong></pre><pre>elementID.submit()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tjuJv_A9gsyXkA3HpZxDow.png" /><figcaption>Automated login page</figcaption></figure><p>An automatic webpage should open and the program will automatically input your username and password as you had set up in the code.</p><p>Something to keep in mind is that, since you are using your own LinkedIn account, the webpages and information you can access from LinkedIn are limited to what your profile can access. For example, specific users you are not connected with may not be visible to you.</p><p>Successfully logged in, we are now able to perform many functions, a few of which that I have used are listed below:</p><h4>1. Inputting in a search box</h4><pre><strong>#Go to webpage</strong><br>browser.get(&#39;https://www.linkedin.com/jobs/?showJobAlertsModal=false&#39;)</pre><pre><strong>#Find search box</strong><br>jobID = browser.find_element_by_class_name(&#39;jobs-search-box__text-input&#39;)</pre><pre><strong>#Send input</strong><br>jobID.send_keys(job)</pre><p>In the instance above, I accessed the page where I am able to search for jobs. The element that I needed the browser to find was the search box. I found the class name by right-clicking on the page and going into “inspect” which shows me the source code of any webpage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*PlxAoFThlis4IpbsSuwoaA.png" /><figcaption>Source code from inspect option</figcaption></figure><p>In fact, making use of the source code was the more important key to performing the functions in my code. By clicking the arrow on the top left corner of the source code window, I could see the code of any element I clicked on the LinkedIn page. I would then insert the class name into my python code to access it.</p><h4>2. Clicking a button</h4><p>Clicking a button can be submitting the input you entered in the search box above but is definitely not limited to that. For my own purposes, I needed to click a button to open the list of filters that were applied to a job search.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*opUvhSREdlnSTlIPH-AMsw.png" /><figcaption>All LinkedIn job function filters</figcaption></figure><p>This is a simple, two-step, process:</p><ol><li>Find the element and</li><li>Perform the click method on the element</li></ol><pre>browser.find_element_by_class_name(&quot;search-s-facet__button&quot;).click()</pre><p>I found the element class name through the source code, as explained in the previous function, then applied the click method. I wrote this code in one line but it can also be done in two with a variable:</p><pre><strong>#These two lines of code are not clicking the same button as the previous instance</strong></pre><pre>search = browser.find_element_by_class_name(&#39;jobs-search-box__submit-button&#39;)<br>search.click()</pre><h4>3. Scraping text</h4><p>In the code after the image, I tried to obtain the number of job postings that resulted from a search for a specific type of career. This number was first stripped as a string, so I had converted it into an integer, as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XTdECUSi2qUyP8BfL0LZVg.png" /><figcaption>Scraping number of job postings</figcaption></figure><pre><strong>#Get page source code</strong><br>src = browser.page_source<br>soup = BeautifulSoup(src, &#39;lxml&#39;)</pre><pre><strong>#Strip text from source code</strong><br>results = soup.find(&#39;small&#39;, {&#39;class&#39;: &#39;display-flex t-12 t-black--light t-normal&#39;}).get_text().strip().split()[0]<br>results = int(results.replace(&#39;,&#39;, &#39;&#39;))</pre><h3>Errors and Solutions</h3><p>Selenium and Beautiful Soup can work together to perform many functions that are definitely not limited to what I have used above. However, I would like to address a few errors I have run into while writing my own code and also explain my solutions.</p><h4>1. Selenium v.s. Beautiful Soup</h4><p>Since my code made use of both Selenium and Beautiful Soup, I often confused which one I needed to use depending on my purposes. I once tried to find and click an element by searching for it in the html code before realizing that I was trying to perform a Selenium function using Beautiful Soup!</p><p>Although the two work together, Beautiful Soup allowed me to scrape the data I could access on LinkedIn. Meanwhile, Selenium is the tool I used to automate the process of accessing those webpages and elements on the website.</p><h4>2. Unable to locate element</h4><p>This was perhaps the most frustrating error as there are elements in the source code that my code could not seem to access.</p><p>The following is a block of code that helped me fix this problem:</p><pre>last_height = browser.execute_script(&#39;return document.body.scrollHeight&#39;)<br>for i in range(3):<br>    browser.execute_script(&#39;window.scrollTo(0, document.body.scrollHeight);&#39;)<br>    time.sleep(SCROLL_PAUSE_TIME)<br>    new_height = browser.execute_script(&#39;return document.body.scrollHeight&#39;)<br>    last_height = new_height</pre><p>The block of code above acts as a page loader that allowed me to reach more of the source code to find the elements I needed. For example, when you first load a page, you cannot see much of the website until you scroll down. The code above allows you to automate that “scrolling down” action.</p><p>A link to the YouTube channel that introduced me to this code is linked at the end of this story along with other resources.</p><h4>3. Messaging pop-up</h4><p>One of the first issues I ran into was the way my messages would pop-up and essentially block a chunk of the webpage that I wanted to be able to see.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*kWmYDNYtZAC8zXTaF0ORWw.png" /><figcaption>Example of a pop-up messages. Image taken from <a href="https://www.fastcompany.com/40405918/linkedins-new-instant-conversations-are-a-major-messaging-upgrade">https://www.fastcompany.com/40405918/linkedins-new-instant-conversations-are-a-major-messaging-upgrade</a></figcaption></figure><p>This seemed to be an automatic function in LinkedIn so I needed a way around it. If I were manually using LinkedIn, I would simply click the messaging tab once and the pop-up would minimize itself. I needed to perform this action in my code.</p><p>My solution below checks to see if the pop-up has already been minimized, in which case it would not block the other elements on the page. If my code cannot find the minimized messages then I look for the case where it which it is in fact a pop-up and click it away.</p><pre><strong>#Import exception check</strong><br>from selenium.common.exceptions import NoSuchElementException</pre><pre>try:<br>    if browser.find_element_by_class_name(&#39;msg-overlay-list-bubble--is-minimized&#39;) is not None:<br>        pass<br>except NoSuchElementException:<br>    try:<br>        if browser.find_element_by_class_name(&#39;msg-overlay-bubble-header&#39;) is not None:<br>            browser.find_element_by_class_name(&#39;msg-overlay-bubble-<br>header&#39;).click()<br>    except NoSuchElementException:<br>        pass</pre><h3>Conclusion</h3><p>Selenium and Beautiful Soup allows us to perform many different functions including scraping the data I obtained from LinkedIn. Using the data I was able to collect using the functions in this story, I was able to obtain the data necessary to generate graphs reflecting the job market as suggested by LinkedIn.</p><h3>Resources:</h3><p>Selenium: <a href="https://selenium-python.readthedocs.io/">https://selenium-python.readthedocs.io/</a></p><p>Beautiful Soup: <a href="https://pypi.org/project/beautifulsoup4/">https://pypi.org/project/beautifulsoup4/</a></p><p>Relevant YouTube Channel: <a href="https://www.youtube.com/channel/UCTiWgVtEGSY4cuduJbMPblA">https://www.youtube.com/channel/UCTiWgVtEGSY4cuduJbMPblA</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3e6790099b5" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/linkedin-scrapper-a3e6790099b5">LinkedIn Scraper</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LinkedIn Job Trends]]></title>
            <link>https://medium.com/swlh/linkedin-job-trends-2dd64f1d4541?source=rss-b0c1ee233084------2</link>
            <guid isPermaLink="false">https://medium.com/p/2dd64f1d4541</guid>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[job-hunting]]></category>
            <category><![CDATA[linkedin]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Sophie Zhao]]></dc:creator>
            <pubDate>Sat, 12 Sep 2020 20:58:39 GMT</pubDate>
            <atom:updated>2020-09-20T20:18:20.550Z</atom:updated>
            <content:encoded><![CDATA[<p>Mentor: Sining Chen</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c3hp3bq3kGev_f3Iva8XAQ.png" /></figure><p>LinkedIn has a community of professionals and is also a fitting online platform for job hunting, especially during a pandemic. In this story, we saved a <strong>data set</strong> of the number of job postings for the 35<strong> job functions</strong> that LinkedIn is able to filter. These “functions” include broad categorizations for jobs like “design”, “business development”, “engineering”, and more. By <strong>visualizing </strong>this data on line graphs and pie charts, we could <strong>observe</strong> <strong>similarities </strong>between the types of jobs and also gain insight into the distribution of the categories or jobs.</p><p>The technical specifics of our process can be found at the link to our other story where we explain how to use Selenium and Beautiful Soup for scrapping data or performing automated functions: <a href="https://medium.com/@sophie14159/linkedin-scrapper-a3e6790099b5">https://medium.com/@sophie14159/linkedin-scrapper-a3e6790099b5</a></p><h3>Our Dataset</h3><p>As a Canadian resident, the information I gathered with our program focuses on jobs located in Canada. With this location filter on LinkedIn, I ran my code to search these following types of jobs on LinkedIn.</p><p>Below is the list of how many job postings are categorized in a specific type of job function that LinkedIn filters. This is an example of the data gathered from August 15</p><pre>2020-08-15 Management 53147<br>2020-08-15 Manufacturing 49236<br>2020-08-15 Information Technology 44666<br>2020-08-15 Other 36069<br>2020-08-15 Sales 34510<br>2020-08-15 Business Development 24167<br>2020-08-15 Health Care Provider 19360<br>2020-08-15 Engineering 18664<br>2020-08-15 Customer Service 11247<br>2020-08-15 Finance 10042<br>2020-08-15 Administrative 8847<br>2020-08-15 Marketing 6185<br>2020-08-15 Design 5374<br>2020-08-15 Education 5210<br>2020-08-15 Training 5124<br>2020-08-15 Art/Creative 4919<br>2020-08-15 Project Management 4669<br>2020-08-15 Accounting/Auditing 4510<br>2020-08-15 Analyst 4108<br>2020-08-15 Science 3354<br>2020-08-15 Human Resources 2633<br>2020-08-15 Quality Assurance 2485<br>2020-08-15 Consulting 1983<br>2020-08-15 Research 1915<br>2020-08-15 Writing/Editing 1814<br>2020-08-15 Public Relations 1738<br>2020-08-15 Legal 1671<br>2020-08-15 General Business 1391<br>2020-08-15 Supply Chain 1173<br>2020-08-15 Product Management 897<br>2020-08-15 Purchasing 728<br>2020-08-15 Production 698<br>2020-08-15 Strategy/Planning 684<br>2020-08-15 Distribution 303<br>2020-08-15 Advertising 174</pre><p>The data is stored in a text file that can be accessed in order to visualize the data onto either a series of line graphs or combined into a single one.</p><h3>Visualizing the Data</h3><p>With data gathered daily from August 15th to September 11th, we obtained graphs that demonstrated the trends of each job function. For example, the graph for “Health Care Provider” is posted below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b-fWUpMvR-I8fOGoqSlRwA.png" /></figure><p>Despite using a smaller dataset, we could make observations from the 35 categories.</p><h4>1. Similar trends</h4><p>Although there are more jobs related to manufacturing function as opposed to management, it was interesting to see that their graphs almost seem to be a copy and paste of each other as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6WKnqO_fDZp-ychb48sDXw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ewoS23ZgoU4uM6J-IegqxA.png" /></figure><p>Something similar can be said for the job postings in the finance v.s. sales sectors. This is interesting because one might associate finance and sales to be in a similar grouping of jobs, except their graphs don’t match as exactly as manufacturing and management do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BPbPh-8u_x0IbMul7RKYtQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rc2UIVd24qRXVkrjc633mA.png" /></figure><p>What can most obviously be observed is the common trend of subtle fluctuations that somehow led to a sudden rise in the number of postings from September 1st to 2nd. It is unfortunate that our data does not allow us to explain such changes in the trends!</p><h4>2. General Consistencies</h4><p>With all the different job functions, we decided to plot them on the same graph in order to compare them more easily. We used a logarithmic y-axis scale so that the trends we visualized would be of the same scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pti-fLlqasxnqYGK86Q1hA.png" /></figure><p>The graph above looks busy due to the large number of lines we plotted. However, it is easy to observe that, spare the few abnormal fluctuations, the general trend of the number of job functions appear to remain flat and consistent.</p><h3>Gathering Data — Courtesy of Selenium and BeautifulSoup</h3><p>Going back to the data gathering process, our major tools were Selenium and BeautifulSoup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*dFgJsR7DCy8uKuhELYGfzg.png" /><figcaption>Right-clicking on a web page opens its HTML source code</figcaption></figure><p>Selenium is a web-based automation tool that works well with Python. In our program, Selenium allows us to access a browser (Chrome) and web pages, specifically to reach LinkedIn pages.</p><p>We combined this tool with Beautiful Soup, which is a Python library that can scrape texts from the source code of a web page. The source code can be accessed with a simple right-click to find the Inspect (CTRL+SHIFT+I) option as shown in the figure on the left. Accessing this source code is the key to using Python commands to navigate in a web page and to scrape the data we needed.</p><p>More about the technical specifics of our process, you may find segments of our code and other explanations at the link to our other story which is linked near the top of the story.</p><h3>Summary</h3><p>The information we could gain from a web page using Python code enabled us to visualize job posting trends on LinkedIn from the number of postings per job function over time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2dd64f1d4541" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/linkedin-job-trends-2dd64f1d4541">LinkedIn Job Trends</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Natural Language Processing]]></title>
            <link>https://medium.com/swlh/nlp-11ff6aeb8259?source=rss-b0c1ee233084------2</link>
            <guid isPermaLink="false">https://medium.com/p/11ff6aeb8259</guid>
            <category><![CDATA[nmt]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Sophie Zhao]]></dc:creator>
            <pubDate>Thu, 02 Jul 2020 02:04:51 GMT</pubDate>
            <atom:updated>2020-07-09T22:11:39.500Z</atom:updated>
            <content:encoded><![CDATA[<h3>Natural Language Processing — Neural Machine Translator</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*vKBsFlAM35KwtaI6nDakxg.png" /></figure><p>Natural Language Processing (NLP) is a combination of computer science, information engineering, and artificial intelligence (AI). While people use words to communicate, computers operate with the language of numbers. Yet these numbers can act as a bridge between the diverse languages in our world. Using NLP, we can create a translation system to lead us towards open and effective communication. The computers’ emerging ability to understand and analyze human language is Natural Language Processing.</p><p>In order for the computer to understand the words we use in our languages, we break up paragraphs and sentences into units of language. These units are converted into numbers then back into words, but those of a different language, thus completing the translation process. There are a number of concepts and algorithms involved in this process, which we will go through in this story:</p><ul><li><strong>Preprocessing</strong>: Tokenization and UNK Replacement</li><li><strong>Word Embeddings</strong>: Vectors and Dimension Reduction</li><li><strong>Sequence to Sequence</strong>: Encoding and Decoding</li></ul><p>These topics cover the general idea of translation. However, in order to perform this process, we made use of a recent adaptation to machine translation: Neural Machine Translation. This approach is largely based on the neurons in our brain and how we learn as humans. It uses the following concepts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*3antvlbccai8qDwKoOwTzg.png" /></figure><ul><li><strong>Datasets</strong>: Training, Validation, Testing</li><li><strong>Neural Networks</strong>: Recurrent Neural Networks</li><li><strong>Long Short Term Memory</strong> and <strong>Attention</strong></li><li><strong>Parallel Corpus</strong></li><li><strong>Forward and Backward Propagation</strong></li><li><strong>Loss Function</strong></li><li><strong>Teacher Forcing</strong></li></ul><p>With a number of concepts to talk about, without further ado, let’s dive in!</p><h3>PREPROCESSING</h3><p>Preprocessing occurs at the start of machine translation, converting text in raw data into a form that the machine will understand. There are two major parts to this process: tokenization and UNK replacement. Preprocessing may even consist of converting the data into lowercase so that the machine treats words that are in uppercase as the same word.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*IxbXpIHtpflraZBX7lJmrg.png" /></figure><h4>Tokenization</h4><p>Tokenization is the breaking down of the larger data in the form of paragraphs and sentences into “tokens” or units of language. These units are often individual words and punctuations. Two extra tokens that we introduce mark the Start of a Sentence (SOS) and End of a Sentence (EOS).</p><h4>UNK Replacement</h4><p>When training the machine with datasets, some words do not appear enough times for the program to learn their meanings. Thus, when it does not recognize or understand a word, it replaces it with UNK as in unknown, then continues with the translation. These gaps in the sentences may be filled in later by post-processing instead.</p><h3>WORD EMBEDDINGS</h3><p>After preprocessing, machine translation uses word embeddings. These are vector representations of texts. Basically, each sentence is assigned a series of numbers, also known as a vector, with an arbitrary number of dimensions. These dimensions help describe the words of a sentence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*wNUvtgJIb97sWTmTZGMG_A.jpeg" /></figure><p>For example, imagine that you have just witnessed a robbery and the police ask you to describe the robber. You may recall the culprit’s appearance: height, body type, hair color, skin color, etc.</p><p>The more descriptive you are, the better understanding the police will have of who they are looking for. However, there is a limit to how descriptive you would be. You should not try to describe the length of every piece of hair on the robber’s head. Such details only become irrelevant. This is the same with dimensions. A word’s meaning becomes more clear with more dimensions, but too much information becomes unnecessary.</p><p>In fact, at times we may want to graph words and their meanings onto a graph. This allows us to visualize the vectors and words with similar or dissimilar meanings; words with more similar meanings are plotted closer together. An example might be “man” and “boy”; they will likely have similar numerical values, allowing the computer to understand that they are related. If we had more than two dimensions in these vectors, we would have to go through Dimension Reduction to narrow it down to two dimensions: an x value and a y value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*KRLQVORSwdEpkVf7hFDQsg.png" /></figure><p>Vectors are so important when it comes to word embeddings because the values allow the language to change while their meanings remain the same. The translator will focus on those numerical values rather than string values or definitions. Vectors become more interesting when we analyze them to find relationships between words. We can even use mathematical operations on them including addition and subtraction. This allows us to identify similarities and differences among words and sentences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*YBSDoMIJTcUzHJBuhVw_5g.png" /></figure><p>For example in the following equation: King — Man + Woman = Queen, we understand that the meaning of a queen resembles a King and a Woman, more so than a Man.</p><h4>SEQUENCE TO SEQUENCE</h4><p>The system that uses vectors to translate a sentence or sequence of words is called sequence to sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*kI4d276IZ7sYdnVe" /></figure><p>It is made up of an encoder and decoder. Encoding allows the program to convert the original sentence into a vector for comprehension. This is much like describing the culprit’s appearance to a sketch artist. Then, decoding turns the values in the vector back into human language, but this time into the new language we wanted to translate them into.</p><h3>Neural Machine Translation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*ShIF3uwvemrN_xwx3Xi4ww.png" /></figure><p>Next, we will go over Neural Machine Translation (NMT) and its tactics. As mentioned previously, it utilizes the concept of Neural Networks to translate sentences by taking in large amounts of trained data.</p><h4>Datasets</h4><p>In order for the AI to learn the languages, we provide it with different datasets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*6tQgEI6CEMsNvBWZIZs9WA.png" /></figure><p>The data it first uses to learn is the <strong>training dataset</strong>. This is the majority of the data we have that is given to the program. Next, we use <strong>validation data</strong> to provide an unbiased evaluation of the model. This second set checks if the model is working correctly. After tuning the model with validation data, <strong>testing data</strong> is the final evaluation given to the program.</p><h4>Neural Networks</h4><p>We know that NMT relies on Neural Networks (NN), but what are NNs? These are connections to nodes that are inspired by the neurons in our brains. The input that goes into the network is processed and analyzed by the network’s hidden layers to extract certain features. What is extracted is then used to obtain an output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/0*TNB_3bB0RJwAo6N8" /></figure><h4>Recurrent Neural Networks</h4><p>More specifically, we made use of a type of NN called Recurrent Neural Networks (RNN). This is often used in text recognition. The network learns in a sequential manner, one word at a time. It remembers its previous learnings with a stored memory and uses them to process new inputs.</p><h4>Long Short Term Memory</h4><p>Narrowing it down even further, Long Short Term Memory (LSTM) is a type of RNN. Based on context gates, the AI knows what to remember, what to forget, and when to do either of these actions. For example, we might give the program a short story to read. Instead of trying to store every little detail, it will remember selected parts of the story. There are two main advantages of this system. First, it draws out only the most important information since the smallest details are often irrelevant when we try to learn something. Second, only focusing on the big picture limits the mistakes that the program might make when trying to retain too much information.</p><h4>Attention</h4><p>So how does the program know what to remember and what to forget? We help the NN pay attention to the most important features by assigning only certain values to vectors. This ties into the number of dimensions we would include in the vector. Moreover, we can assign “weights” to certain words based on their importance in a sentence. The following sentence shows one way in which words of a sentence might be weighted”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*KChLmwMIxub4QxZR5fAdhg.png" /></figure><p>Weights allow the network to know what is or isn’t important, and it will understand the sentences better. If it then wanted to process the next sentence that said: “I love eating them”. It will try and figure out what “them” is referring to. Since cheese and sandwiches are weighted more, the program is more likely to understand that those are the antecedents for “them”. Attention is especially important in longer sentences since they are more susceptible to having the values be forgotten. Thus we want to make sure the most important features are remembered.</p><h4>Parallel Corpus</h4><p>There are a few other tactics we can use to help the program learn. Parallel Corpus is one of the simple ways.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*iJoxlmrkT2YGVeaQiK2gfQ.png" /></figure><p>We feed the machine a series of sentences or phrases in one language and their perfect translation in another language. The machine can then use this data as a reference.</p><h4>Forward and Backward Propagation</h4><p>Forward Propagation and Backward Propagation are more processes involved in a machine’s learning. We can imagine this learning process as one that is very similar to ours. Let’s take a look at the sketch of a chair.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/1*emhcBS-AKjqUMBXsRUeHSg.jpeg" /></figure><p>What if we tried to draw this picture ourselves? We would look at the picture and try to remember for ourselves how a chair looks. For a machine, this is called Forward Propagation: we are putting newly acquired data into our memory. Next, we may try to draw the chair without seeing it. Our product will be an approximation of what the chair looks like, much like testing the data that we obtained. In order to improve our drawing, we will pull out the picture of the chair again and compare it with our drawing. Knowing what we are missing or could do better, our future drawings will most likely be more accurate. This is backwards propagation. The program is able to compare the model it currently has and its target side by side and determine the amount of “loss”. Its goal is then to limit the amount of loss.</p><h4>Loss Function</h4><p>To measure the amount of loss, we use what is called the Loss Function. To illustrate this, we can use the following sample sentence “Father has a dog”. The translator may return “A father has a wolf”. We see that ⅗ words actually appear in the original sentence. Thus we have a loss of two.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/0*5V_G9IsUIr6k7MXQ" /></figure><p>As seen on the left, PPL is a unit of measuring loss. Obviously, the less loss we have, the better translation we have. We see that the PPL value decreases as the program trains itself overtime. This seems simple enough. However, our greatest problem may be minimizing this loss but without overcomplicating the system. Sometimes we make the mistake of overfitting, meaning that we used too many dimensions in attempt to make the data match perfectly. This may cause us to exclude other data simply because there was not a 100% match.The program is best trained with the right combination that we try to obtain in our process.</p><h4>Teacher Forcing</h4><p>Another method of helping our program is called Teacher Forcing. One of our main problems is that words of a sentence rely on the context established in the previous words in the sentence. Therefore, one error can propagate throughout the network. The teacher forcing algorithm solves this problem by having a translated “answer” to help feed in a reference word. We ensure in this way that the machine is learning with the proper context. For example, our sentence might be “the cat ate the lasagna”. Our program may translate like the following:</p><ol><li>The</li><li>The car</li><li>The car ???</li></ol><p>The word “ate” doesn’t seems to make much sense after “car”, which confuses our program. This is precisely where teacher forcing can come into play. We simply feed in the word “cat” as the answer, allowing our program to continue its translation. The program is now able to continue its training while it finds other ways to see the difference between “car” and “cat”.</p><h3>Summary</h3><p>Our goal is to create a functional translator in order to bridge language barriers. Natural Language Processing allows us to do this. This process involves concepts like preprocessing, word embeddings, and sequence to sequence encoding and decoding. To improve the learning procedures for our program, we used an approach called Neural Machine Translation based on neural networking. Thus we could implement strategies that include long short term memory, attention, parallel corpus, forward and backward propagation, and teacher forcing. These concepts help us reduce the number of loss that can be demonstrated through the loss function.</p><h3>Final Product</h3><p>The strategies covered in this story were only the basics to a high level, multilayer translator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*H0s4UaCN1MEDb5YF" /><figcaption>How our translator converts the English sentence on the left into German</figcaption></figure><p>By importing datasets with both words and vectors, the code could make much use of these sets. It is able to translate multiple sentences with zero loss. We were able to create a semi-functional language translator that has high potential and functions well for shorter, simple sentences. It learns from its mistakes and corrects texts that it has completed. We can say that this was good progress as we had only trained the program for a day to obtain these results.</p><h3>Future</h3><p>A Google Translate level translator takes much more time to create. Moreover, we would try to import even more datasets for the AI to learn. In our case, the data used were mostly from news articles, limiting the amount of conversational vocabulary that the machine would understand. To improve this machine, we can check our data for fundamental errors. Furthermore, our translator focuses less on common words when deciphering meaning, again limiting its understanding of everyday language. In a short amount of time, we were introduced to a variety of methods and saw the potential of such a machine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/0*HaMEdPPdkBQQI9AX" /></figure><p>Translating programs create many opportunities for communication, used with tourists and many businesses. With improved programs, the spreading of knowledge and information around the globe may no longer need to be as expensive or time consuming. Needless to say, Natural Language Processing is an expansive system that has the ability to contribute much to our modern society.</p><h3>ABOUT</h3><p><strong>Program</strong>: Invent the Future AI Scholars Program hosted by Simon Fraser University and supported by AI4ALL</p><p><strong>Date</strong>: July 15th — July 26th, 2019</p><p><strong>Team Members</strong>: Linda Bian, Olivia Chan, Skylar Hildebrand, Ines Khouider, Elizabeth Wong, Sophie Zhao</p><p><strong>Mentors</strong>: Carolyn Chen (TA), Nishant Kambhatla, Pooya Moradi</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11ff6aeb8259" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/nlp-11ff6aeb8259">Natural Language Processing</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Instagram Scraper — How “Popular” Am I Compared to My Friends?]]></title>
            <link>https://sophiezhao713.medium.com/ig-popularity-scraper-2e72cca77a0e?source=rss-b0c1ee233084------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e72cca77a0e</guid>
            <category><![CDATA[popularity]]></category>
            <category><![CDATA[instagram-scraper]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Sophie Zhao]]></dc:creator>
            <pubDate>Sat, 27 Jun 2020 19:44:37 GMT</pubDate>
            <atom:updated>2020-07-12T03:36:44.788Z</atom:updated>
            <content:encoded><![CDATA[<h3>Instagram Scraper — How “Popular” Am I Compared to My Friends?</h3><p>By Sophie Zhao and Mentor: Sining Chen</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*lpK_xGssEwuu7YlU8iQ51A.jpeg" /><figcaption><a href="https://wallpaperaccess.com/full/274089.jpg">https://wallpaperaccess.com/full/274089.jpg</a></figcaption></figure><p>Did you know that your Instagram friends are, on average, more popular than you are? This is according to the <a href="https://en.wikipedia.org/wiki/Friendship_paradox">Friendship Paradox</a>, mathematically proven characteristics of social networks. Being an avid Instagram user, I wanted to study this phenomenon on my Instagram network. I proceeded to ask the following question:</p><blockquote><strong><em>Am I less “popular” </em></strong><em>(have fewer followers)</em><strong><em> than the people I follow </em></strong><em>(my followees)</em><strong><em>?</em></strong></blockquote><p>Since I am not an influencer, it seems like I should expect to be “less popular” as suggested by the Friendship paradox. Is this true for the other users as well? In any case, let’s prove it with numbers!</p><p>What you will see in this story:</p><ul><li>How to scrape data from Instagram, specifically using Instaloader.</li><li>Workings of a virtual network through Instagram profiles</li><li>Using scraped data and coded algorithm to determine “popularity”</li><li>Limitations and topics of further inquiry</li></ul><h4>Steps I took to answer my questions:</h4><ol><li>Import Instaloader</li><li>Access user profile</li><li>Save followees</li><li>Obtain followers of followees</li><li>Calculate average followers</li><li>Compare results</li></ol><h3>Step 1: Import Instaloader</h3><p>The coding language I used was Python. I needed to obtain data from Instagram, including user profiles, numbers of followers, and numbers of followees. To do this, I used a Python package called Instaloader; it is a free open source software written in Python.</p><pre><strong>import </strong>instaloader</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*V-dpRy7kE3IJQ-LC3LVjbQ.png" /><figcaption><a href="https://github.com/instaloader/instaloader">https://github.com/instaloader/instaloader</a></figcaption></figure><p><strong>Instaloader can download…</strong></p><ul><li>…pictures and videos along with their captions and other metadata from Instagram</li><li>…profiles (public and private), hashtags, user stories, feeds and saved media</li><li>…comments, geotags and captions of each post</li></ul><p><strong>It can also…</strong></p><ul><li>automatically detect profile name changes and rename the target directory accordingly</li><li>allow fine-grained customization of filters and where to store downloaded media</li></ul><p>For more information about instaloader: <a href="https://instaloader.github.io/"><em>https://instaloader.github.io/</em></a></p><p>To install instaloader: <a href="https://instaloader.github.io/installation.html"><em>https://instaloader.github.io/installation.html</em></a></p><p>*<strong>Important Update</strong>: As of May 2020, there have been issues regarding the use of Instaloader in the way used in this story. More specifics touched on in the following closed discussion: <a href="https://github.com/instaloader/instaloader/issues/615">https://github.com/instaloader/instaloader/issues/615</a></p><h3>Step 2: Accessing a user profile</h3><p>In the following code, &lt;username&gt; and &lt;password&gt; are the login info of the account wanting to access a desired user’s (&lt;user&gt;) data.</p><pre><em># Login info</em></pre><pre>L = instaloader.Instaloader()</pre><pre>L.login(<strong>&lt;username&gt;</strong>, <strong>&lt;password&gt;</strong>)</pre><pre><em># Desired user</em></pre><pre>user = &lt;<strong>user</strong>&gt;</pre><p>For example, when I wanted to access my own information, I would put my username “sz_713” as &lt;username&gt; and enter my password in &lt;password&gt;. My desired user, myself, would also be “sz_713”</p><pre><em># Login info</em></pre><pre>L = instaloader.Instaloader()</pre><pre>L.login(&quot;sz_713&quot;, &quot;my_password&quot;)</pre><pre><em># Desired user</em></pre><pre>user = &quot;sz_713&quot;</pre><p>*<strong>Note</strong>: To be able to access data from &lt;user&gt;, the account you log in from must have permission to see the profile. This means that if &lt;user&gt; is blocking you or is a private account you do not follow, you are unable to access their information from your account.</p><h4>The Anatomy of an Instagram User Profile</h4><p>Each instagram user profile contains the number of followers, followees, and their usernames and links. This enables us to crawl through the network from any user represented by a node (see Step 4: Obtain the number of followers of the followees). Instaloader allows us to obtain such data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*msjo6mHPymUkzwMlgNKGvA.png" /><figcaption><a href="https://www.instagram.com/sz_713/?hl=en">https://www.instagram.com/sz_713/?hl=en</a></figcaption></figure><h3>Step 3: Save followees</h3><p>Using methods in instaloader, we can gather a list of &lt;user&gt;’s followees. The list of followees is printed into a text file for later use.</p><pre><em># Print list of followees into txt file</em></pre><pre>profile = instaloader.Profile.from_username(L.context, user)</pre><pre>list_followees_txt = open(<strong>&quot;list_followees&quot;</strong>, <strong>&quot;w&quot;</strong>)</pre><pre><strong>for </strong>followee <strong>in </strong>profile.get_followees():</pre><pre>list_followees_txt.write(<strong>&quot;%s \n&quot; </strong>% followee.username)</pre><pre>list_followees_txt.close()</pre><p>In the code above, I accessed a user profile (which was my own) and opened a text file called “list_followees”. I am then able to write the usernames of profile I follow into “list_followees”.</p><h4>Basics of A Social Network</h4><p>In a social network, the users are <em>nodes </em>or <em>vertices. </em>The relationships between the users are <em>edges. </em>A network is called “directed” when edges have directions to them. For example, the act of user A following user B, without B necessarily following A. Twitter and Instagram could be “directed networks” as I might follow Taylor Swift who does not necessarily follow me back. On the other hand, Facebook consists of “undirected” networks where all edges are mutual friendships and bi-directional.</p><h4>Directed network</h4><p>In this case from left to right, perhaps Grace follows Jack who follows Aries. Also note that a total of five other users follow Jack, and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DVCRXn5R1oaY0QY3J0ZB-w.gif" /><figcaption><a href="https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcQSOtAhc7EQs75-tNU8ODsFWhpkj67BCv8J3Q&amp;usqp=CAU">https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcQSOtAhc7EQs75-tNU8ODsFWhpkj67BCv8J3Q&amp;usqp=CAU</a></figcaption></figure><h4>Un-directed network</h4><p>We can visualize a social network in Instagram without the arrows as well, assuming that each numbered node represents a user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1DfACVGfKyMHr4wdKbA_PA.png" /><figcaption><a href="https://upload.wikimedia.org/wikipedia/commons/thumb/5/5b/6n-graf.svg/1200px-6n-graf.svg.png">https://upload.wikimedia.org/wikipedia/commons/thumb/5/5b/6n-graf.svg/1200px-6n-graf.svg.png</a></figcaption></figure><h3>Step 4: Obtain followers of followees</h3><p>Next, I want to get the total number of followers of the followees in the list to later calculate their average. Instead of getting the number of followers for every single followee, the following code scrapes the data of about 30 random followees to do this calculation.</p><pre><em># Get number of followers of followees from txt file</em></pre><pre><strong>with </strong>open(<strong>&#39;list_followees&#39;</strong>) <strong>as </strong>f:</pre><pre>content = f.readlines()</pre><pre>total_followees = len(content)</pre><pre>content = [x.strip() <strong>for </strong>x <strong>in </strong>content]</pre><pre>sum = 0</pre><pre>count = int(total_followees/30)</pre><pre>num_followees = 0</pre><pre><strong>for </strong>username <strong>in </strong>content:</pre><pre><strong>if </strong>count == 0:</pre><pre>profile = instaloader.Profile.from_username(L.context, username)</pre><pre>followers = profile.followers</pre><pre>sum += followers</pre><pre>num_followees += 1</pre><pre>count = int(total_followees / 30)</pre><pre><strong>else</strong>:</pre><pre>count -= 1</pre><p>I take a random sample as opposed to a full set of data for each user due to limitations of scraping data from Instagram. If I try to scrape too much data, there is a request timeout that will terminate the code, which I don’t want.</p><h4>Approach to a Network</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*ZXk_5g_QjcIHNX57D5CO2w.png" /><figcaption><a href="http://www.caib.es/sites/suportalvoluntariat/ca/enxarxats_connectar_a_les_entitats_amb_els_ambits_del_voluntariat/">http://www.caib.es/sites/suportalvoluntariat/ca/enxarxats_connectar_a_les_entitats_amb_els_ambits_del_voluntariat/</a></figcaption></figure><p>Considering the undirected network of Instagram profiles above, to find the friends of my friends requires me to crawl a network from myself (the ego node) out to at least two degrees. We needed an algorithm. This doesn’t sound like much. However, in my case for example, each of the numbers in the picture above are the number of followers, and each of them have their own number of followers and so on. Therefore, in reality, the further out we move, the number of nodes needed to be crawled explodes exponentially.</p><h3>Step 5: Calculate average followers</h3><p>After obtaining the sum of the number of followers, I can easily divide that by the number of followers we used (30) to calculate the average number of followers.</p><pre><em># Get average num followers</em></pre><pre>average = sum / num_followees</pre><pre>print(<strong>&quot;The average number of followers is &quot; </strong>+ str(average))</pre><p>My results say “The average number of followers is 29178.48275862069”</p><h3>Step 6: Compare results</h3><p>Finally, to answer my original question, I compare the average number of followers I calculated (29178.48275862069) to the number of followers that &lt;user&gt; has. If &lt;user&gt; has more followers than its followees do on average, I declare it more popular than its followees. Otherwise, is followees are more popular than itself.</p><pre><em># Compare user num followers to average</em></pre><pre>user_followers = (instaloader.Profile.from_username(L.context, user)).followers</pre><pre><strong>if </strong>(average &gt; user_followers):</pre><pre>print(<strong>&quot;On average, &quot; </strong>+ user + <strong>&quot;&#39;s followees have more followers than&quot; </strong>+ user +<strong> &quot;.&quot;</strong>)</pre><pre><strong>else</strong>:</pre><pre>print(<strong>&quot;On average, &quot; </strong>+ user + <strong>&quot;has more followers than their followees.&quot;</strong>)</pre><p>My output says “On average, sz_713’s followees have more followers than themselves.” It compared the 29178.48275862069 followers that my followees have on average to the 427 followers I have.</p><h3>Summary</h3><p>I used instaloader as a way of scraping data from Instagram users. Using its methods, we can answer the question of whether a specific user is more or less popular than the people he or she follows. Instaloader allows us to use an appropriate account to access our desired user to test. We can then gather those followees’ number of followers and compare their average to the user’s number of followers, therefore we can answer our original question through a simple comparison.</p><h3>Limitation</h3><ul><li>Avoids request time out issue by limiting data gathered → results are not completely accurate, but are more of an estimate.</li></ul><h3>Related topics for further investigation:</h3><p>— How popular do I have to be for my results to differ?</p><p>— If we count all of the pairs who mutually follow each other as “friends”, does the Friendship Paradox hold in my immediate circle?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e72cca77a0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>