<?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 Jonathan Lee on Medium]]></title>
        <description><![CDATA[Stories by Jonathan Lee on Medium]]></description>
        <link>https://medium.com/@shanchinlee?source=rss-5d480ee7cf67------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*RGS407XGZnpVbfhc</url>
            <title>Stories by Jonathan Lee on Medium</title>
            <link>https://medium.com/@shanchinlee?source=rss-5d480ee7cf67------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 19:18:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shanchinlee/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[Predicting NBA’s Most Valuable Player Using Python]]></title>
            <link>https://shanchinlee.medium.com/predicting-nbas-most-valuable-player-and-corresponding-data-analytics-using-python-880dfc884cfc?source=rss-5d480ee7cf67------2</link>
            <guid isPermaLink="false">https://medium.com/p/880dfc884cfc</guid>
            <category><![CDATA[nba]]></category>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Jonathan Lee]]></dc:creator>
            <pubDate>Mon, 24 May 2021 06:10:12 GMT</pubDate>
            <atom:updated>2021-05-28T03:48:39.793Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kqyaMbnjNomAYvvD" /><figcaption>Photo by <a href="https://unsplash.com/@deanbennett?utm_source=medium&amp;utm_medium=referral">Dean Bennett</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong><em>A tutorial with full code to demonstrate how to predict NBA’s next MVP using machine learning techniques started from scratch, showing all steps including data collection, cleaning/merging, statistical modeling and model training.</em></strong></p><p><a href="https://github.com/scleeza/NBA"><strong><em>Full Code</em></strong></a></p><h4>Table of Contents</h4><ol><li>Data Collection</li><li>Merging and Cleaning Data</li><li>Feature Selection</li><li>Model Training and Hyper-parameter Tuning</li></ol><h4>1. Data Collection</h4><p>The data comes from NBA’s official website, they’ve build a comprehensive database on all kinds of tabular data like the player’s career stats, game’s box scores, team’s performance, etc. In this article, I use a popular open source python package called<em> </em><a href="https://pypi.org/project/nba-api/"><strong><em>nba-api</em></strong></a><strong><em> </em></strong>to extract data from the database, the package has implemented the most annoying web-scrapping part for us and built functions that can easily access to specific data. More detail can be found on its GitHub page in the link above. Here I will collect 3 of particular tabular data using the package and them are:</p><p>1. Player’s career stats data, representing how player’s performance in each season.</p><p>2. Team’s performance, so we can know how much games they won and their final/current ranking.</p><p>3. Awards that player has won, creating target variable.</p><p>Before started, we need some key index like player ID, team ID, season ID as arguments in API functions. So first, listing all the players that have been played in NBA during season 2000 to 2020 and the code can found in following block</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/007341eab4d2a62d426d39f8f21e1f46/href">https://medium.com/media/007341eab4d2a62d426d39f8f21e1f46/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*US8ysfNyvzKjC_nUli0itg.png" /><figcaption>players data frame</figcaption></figure><p>Once the list of players was created, the player’s career data can be queried through entering PERSON_ID <em>to</em><strong><em> </em></strong>API function. Noted That, one may got block by website if too many queries at the same time so an one-second pause is added to each query to avoid that. In addition, an error log is also added since queries may still fail due to unknown issues, so it would be better to record missing queries so it can be re-queried later.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4775fbdf535805cd81bd52deb7118e44/href">https://medium.com/media/4775fbdf535805cd81bd52deb7118e44/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tpt1h7R57F0H2kK3mBopkA.png" /><figcaption>data frame of player’s career stats</figcaption></figure><p>Querying team’s data would be the same to querying player’s data. Listing all the teams and then use their IDs to extract information through API functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08d501de9e41175964f4f07c99fa9cbb/href">https://medium.com/media/08d501de9e41175964f4f07c99fa9cbb/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qm1Qa9ZNreIOE9Fap7LTKw.png" /><figcaption>data frame of teams performance</figcaption></figure><p>Again, same steps for player’s award data frame. The querying process may take a while, so don’t forget to save results into local environment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67b7d1e8eadb28a400b038bb8137ce74/href">https://medium.com/media/67b7d1e8eadb28a400b038bb8137ce74/href</a></iframe><h4>2. Merging and Cleaning Data</h4><p>In this section, I’m trying to create a training data for our model and it requires to merge all the data we have. First, players data will be merged with team’s performance data(we only take some columns like wins, losses, winning percentage). All the data will be merged together through their key index, ‘TEAM_ID’ and ‘SEASON_ID’. In addition, I think within season awards like the player of the week and the player of the month are potentially to be good features. So some aggregate calculations are added to count how many times a player has won the award in a single season.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0d249b055e3e8a59b184e961011f030/href">https://medium.com/media/f0d249b055e3e8a59b184e961011f030/href</a></iframe><p>After all the tables are integrated into one single data set, some trivial features like TEAM_ABBREVIATION, TEAM_CITY and duplicated columns will be dropped out, data will be standardized season by season, so the implicit rank information can still be preserved.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b94d40f6be594946a077392eebcc531a/href">https://medium.com/media/b94d40f6be594946a077392eebcc531a/href</a></iframe><h4>3. Feature Selection</h4><p>After the training set was created, we would like to know whether these features are feasible predictors or not. A typical way to do this is to build a multivariate regression model and show its statistical significant evidence of each predictor, also known as p-values. In this case, our target variable is a binary data (1/0 for winning MVP or not), so it is suitable to solve this using logistic regression model.</p><p>Before applying the model, one more step should be taken to check collinearity of the data. This is because if rows or columns are proportionally interrelated to each other, it will lead the covariance matrix toward singularity and will cause no-solution when solving the inverse matrix in regression model. A prevention way is dropping highly correlated features. The following code will demonstrate how to do drop these features and fit into logistic regression model to get p-values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95709bebd178fdbdd45370057dfa52a5/href">https://medium.com/media/95709bebd178fdbdd45370057dfa52a5/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dXybYwAW1nNYFHPqUxTwew.png" /><figcaption>Summary table of logistic regression</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*bNT1SXZ1fqAWy9ay86EWQw.png" /><figcaption>Significant features with their p-values (level of 0.05)</figcaption></figure><p>As the table shows, there have 12 features that have been considered significant in this multivariate model. And we can see that most of offensive stats like field goal percentage and 3 point shot percentage have been included. In addition, stats like minutes, games played, games as starter also been included to reflect whether this player is important to the team or not. So basically, the result here has proven that most of the features shown statistically significant and also make sense to the popular opinion when coming to select a MVP player.</p><p>Next, we would like to know what features are playing more important roles in this model. Noted that the size of p-value is not equal to the contribution of the feature, it just means the confidence of getting an non-zero value on feature’s coefficient. The way to find out importance can be done by fitting data into a model and check the coefficient like I already did in the logistic regression. However, some slight change can be made to improve the result, since not all features are considered significant.</p><p>The first one is doing with Lasso regression which tend to reduce number of predictors by adding penalty term (magnitude of penalty ’C ’ is a user controlled parameter which is 0.5 in this case, smaller C means higher penalty and cause less features), less important features will be eliminated so as to achieve robuster coefficient estimations. Checking fitting score of the model, because sometimes linear model doesn’t fit well, if so then we should move to next way.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28ed8e04dd50030f3610269e52ba5f89/href">https://medium.com/media/28ed8e04dd50030f3610269e52ba5f89/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*0UjJF0ZYhgYZFwd7Sw9qXg.png" /><figcaption>Feature importance in Lasso Regression</figcaption></figure><p>The second way is using random forest. In this way, the algorithm will check which features are having higher average on getting more impurity reduction. I personally like this one better, since sometimes linear regression doesn’t fit that well, so RF can be a more suitable choice.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef138f8394cd50dbf48320ec0ad72132/href">https://medium.com/media/ef138f8394cd50dbf48320ec0ad72132/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*nczi9ocgdiU35RZocEidVA.png" /><figcaption>Feature importance of RF</figcaption></figure><p>From the above results, it seems that winning percentage and times of getting player of week affect the most.</p><h4>4. Model Training and Hyper-parameter Tuning</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*XI9FduEawAITgmhr_9n6uQ.png" /><figcaption>Imbalance target variable</figcaption></figure><p>First, the distribution of the target variable is extremely imbalanced as shown in above figure (only 20 MVP we can have at all). To solve this, you can either re-sample the minority data using techniques like SMOTE or giving minority class a heavy weight by adding class_weight=”balanced” in the estimator.</p><pre>rfc = RandomForestClassifier(class_weight=&quot;balanced&quot;)</pre><p>Another important thing is deciding what metric for evaluating model. In here, ROC-AUC score will more better to evaluate model with imbalanced data, since it consider both precision and recall score which can best reflect prediction of minority class . I will use random forest to obtain final model. In addition, hyper parameters setting will be selected through grid search to get optimal combination. If computation time is a great concern, try on max_depth only would save bunch of time and still have good CV score.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/788a4b5dc3b492919c7111254b908791/href">https://medium.com/media/788a4b5dc3b492919c7111254b908791/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*zCZMaH-UUHTPX93QICgnFg.png" /><figcaption>best combination and its score</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71da99e93e446251bbdf0890c2530b12/href">https://medium.com/media/71da99e93e446251bbdf0890c2530b12/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*74txDURGXHlhLK7ebwNj0Q.png" /><figcaption>Confusion matrix of final model</figcaption></figure><p>After all the work were done, it’s time to predict who will going to win this season’s MVP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*vRwyLjs8tCs0ET89DjhRBg.png" /></figure><p>And result shows that Jokic may have the best change to win his first MVP, and surprisingly Curry though having a tough season for Warriors, his excellent play still managed him to get into Top4.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=880dfc884cfc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extract Text From Unsearchable PDFs For Data Analysis Using Python]]></title>
            <link>https://medium.com/social-impact-analytics/extract-text-from-unsearchable-pdfs-for-data-analysis-using-python-a6a2ca0866dd?source=rss-5d480ee7cf67------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6a2ca0866dd</guid>
            <category><![CDATA[social-impact]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pytesseract]]></category>
            <category><![CDATA[ocr]]></category>
            <dc:creator><![CDATA[Jonathan Lee]]></dc:creator>
            <pubDate>Fri, 09 Apr 2021 07:18:19 GMT</pubDate>
            <atom:updated>2021-04-17T00:01:11.865Z</atom:updated>
            <content:encoded><![CDATA[<h3>Extract Text From Unsearchable PDFs Using OCR, Tesseract, and Python</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TR2l3KPCnHCiLM0Q" /><figcaption>Photo by <a href="https://unsplash.com/@loverna?utm_source=medium&amp;utm_medium=referral">Loverna Journey</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>At <a href="https://www.siainstitute.org/"><strong><em>Social Impact Analytics Institute</em></strong></a>, we do a lot of text extraction on PDF files. Problems arise when the PDF files are scanned documents, because that means general extraction libraries like Pdfminer, PyPDF2, or PyMuPDF are not able to extract text correctly. In order to read the files, make the text content of the files searchable, and be able to do further NLP data analysis, an OCR process must be used.</p><p>In this article, I’m going to demonstrate how to use an open source OCR engine (Optical Character Recognition) called <strong><em>Tesseract </em></strong>and its<strong><em> Python APIs</em></strong> to conduct text extraction and then put the text into a pandas data frame for further data analysis.</p><h4>Quick view of Contents</h4><ol><li>Install Tesseract engine.</li><li>Install Python Packages: PyTesseract, OCRmyPDF.</li><li>Code Example for Text Extraction</li></ol><h4>Tesseract Installation</h4><p>Tesseract is a free command line application powered by Google. It has been widely used for OCR tasks, however, it is not a python library so it must be installed separately<em>. </em>I suggest installing Tesseract on <strong><em>Mac OS, Ubuntu</em></strong> or another Linux-like system. However, if you are using Windows, <a href="https://medium.com/quantrium-tech/installing-and-using-tesseract-4-on-windows-10-4f7930313f82">this article</a> shows how to install it on Windows 10.</p><p><strong>Mac : </strong>brew install tesseract</p><p>If you already have homebrew, simply enter this code on your terminal and then you are done. If not, check homebrew’s <a href="https://brew.sh/">home page</a> to install it.</p><p><strong>Ubuntu: </strong>sudo apt-get install tesseract-ocr</p><h4>Python Packages</h4><p>There are 2 ways to use the Tesseract engine in this article: through<strong><em> Pytesseract</em></strong> or through <strong><em>OCRmyPDF. </em></strong>Both require the installation of additional libraries. I will show how these work together in the following sections. First, install the packages through the pip command in a python environment:</p><pre>pip install ocrmypdf</pre><pre>pip install pytesseract</pre><pre>pip install opencv-python</pre><pre>pip install pdf2image</pre><h4>1. Pytesseract</h4><p>Pytesseract reads the input file as an image, so <strong><em>opencv-python</em></strong> and <strong><em>pdf2image</em></strong> are included to help transfer PDF files into images. The steps will look like this:</p><ol><li>Read PDF files</li><li>Convert PDFs into images</li><li>Image preprocessing to check orientation, deskew, gray scale, etc.</li><li>Run OCR function from its API</li><li>Extract all/part of the text</li></ol><p>The syntax of the main OCR function is:</p><pre>pytesseract.image_to_string(page_arr)</pre><p>The code, including image processing steps and how to put the resulting text into a pandas data frame, is shown below. The code for the deskew function is referenced <a href="https://www.pyimagesearch.com/2017/02/20/text-skew-correction-opencv-python/">here</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f1d7118afb441fb2e60d407ff5a56e2/href">https://medium.com/media/2f1d7118afb441fb2e60d407ff5a56e2/href</a></iframe><p>To show the result:</p><pre>OCR_dic[file_list[0]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*zISVX5uNecAoCbL93VrDig.png" /><figcaption>Seems odd that all the text files start with identical wording. This is a clue that a header may be in use.</figcaption></figure><h4>2.1 Remove Header and Footer</h4><p>After displaying the result, it seems that the header was included and it may not be wanted or required. Here I will show a simple code to exclude certain contents from our extraction results by using <strong><em>pytesseract</em></strong>.<strong><em>image_to_data</em></strong> syntax, which generates meta-data like box boundaries, confidence and other information.</p><pre>pytesseract.image_to_data(page_arr,output_type=Output.DICT)</pre><p>The keys of the output dictionary will look like this:</p><pre>dict_keys([&#39;level&#39;, &#39;page_num&#39;, &#39;block_num&#39;, &#39;par_num&#39;, &#39;line_num&#39;, &#39;word_num&#39;, &#39;left&#39;, &#39;top&#39;, &#39;width&#39;, &#39;height&#39;, &#39;conf&#39;, &#39;text&#39;])</pre><p>Note that <strong><em>level</em></strong> is critical to interpret these results. It will be an integer between 1~5 and each of them stands for</p><ol><li>page</li><li>block</li><li>paragraph</li><li>line</li><li>word</li></ol><p>Let see how it works on the PDF. Here I use a file’s first page as an example. I want to see how many blocks will be generated and want to see if it includes the header and footer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6f48db5e70fe775dc335a0c83d263b2/href">https://medium.com/media/d6f48db5e70fe775dc335a0c83d263b2/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*Zo58gSYiS4pREjXz76X7bw.png" /><figcaption>Blocks generated by Tesseract — notice there are a total 8 blocks. This can be checked by looking at the block_num column.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VJMwUXP9AIc5k_m9Mk6cVg.jpeg" /><figcaption>Blocks highlighted by green lines</figcaption></figure><p>The image and data frame above show that 8 blocks were generated from OCR, and fortunately the header and footer are included in the first and the last blocks. If I want to remove both of them, it is easy to achieve by removing these two blocks.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd2b68e3576c2f3935366e43627fe2d0/href">https://medium.com/media/cd2b68e3576c2f3935366e43627fe2d0/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*k3FKzNwWxWKmGPxNyo7t1A.png" /></figure><p>Now the extracted text does not include the header or footer. However, for different PDFs, this code may need to be modified or headers and footers may not be so easily excluded.</p><h4>2. OCRmyPDF</h4><p>It is more simple to use OCRmyPDF when compared to Pytesseract because OCRmyPDF doesn’t require image processing steps. The output result of OCRmyPDF will be a PDF file, though, so additional steps are required if one wants to extract its text data. Here I use PyMuPDF to do that, which provides multiple output format options like xml, html or json. Choose whichever type works best for your purposes. The steps of the process are:</p><ol><li>Run the OCRmyPDF function to create new, searchable PDF files.</li><li>Use PyMuPDF to extract text from the PDF.</li></ol><p>The code for using OCRmyPDF will look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1342dcdf7512fa94be9d3bfae9dd3b38/href">https://medium.com/media/1342dcdf7512fa94be9d3bfae9dd3b38/href</a></iframe><p>To show the result of the first PDF file:</p><pre>extraction_pdfs[ocr_file_list[0]]</pre><h4>Conclusion</h4><p>In this article, I’ve shared code for how to use two popular Tesseract python APIs to conduct OCR on PDF files. My suggestions for which API should be used are:</p><ol><li>For simple OCR tasks where text extraction is a minor part of the whole project, you should use OCRmyPDF. It is faster and easier to conduct the OCR process without the extra image processing steps, and you can leave meta-data extraction to PyMuPDF once the PDF files are transferred into searchable PDF.</li><li>If the goal is to do customized text extraction such as getting the date/time from a group of receipts or removing headers and footers as I did in this article, then using Pytesseract will be more appropriate. Pytesseract prevents you from having to read the file twice, and filter conditions can be written during the OCR.</li></ol><h4>Reference</h4><p>https://tesseract-ocr.github.io/</p><p>https://pypi.org/project/pytesseract/</p><p>https://ocrmypdf.readthedocs.io/en/latest/index.html</p><p>https://www.pyimagesearch.com/2017/02/20/text-skew-correction-opencv-python/</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6a2ca0866dd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/social-impact-analytics/extract-text-from-unsearchable-pdfs-for-data-analysis-using-python-a6a2ca0866dd">Extract Text From Unsearchable PDFs For Data Analysis Using Python</a> was originally published in <a href="https://medium.com/social-impact-analytics">Social Impact Analytics</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>