<?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 Ronghui Zhou, Ph.D. on Medium]]></title>
        <description><![CDATA[Stories by Ronghui Zhou, Ph.D. on Medium]]></description>
        <link>https://medium.com/@ronghui-zhou?source=rss-cd5a61234de5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*3fbhHqkG296FayMWl_6DCQ.jpeg</url>
            <title>Stories by Ronghui Zhou, Ph.D. on Medium</title>
            <link>https://medium.com/@ronghui-zhou?source=rss-cd5a61234de5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 20:41:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ronghui-zhou/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[Why some proteins are allergenic?]]></title>
            <link>https://ronghui-zhou.medium.com/protein-exploratory-data-analysis-in-python-ff4c53aa3df7?source=rss-cd5a61234de5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff4c53aa3df7</guid>
            <category><![CDATA[pharmaceutical]]></category>
            <category><![CDATA[sequence]]></category>
            <category><![CDATA[protein]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[biopython]]></category>
            <dc:creator><![CDATA[Ronghui Zhou, Ph.D.]]></dc:creator>
            <pubDate>Thu, 05 Oct 2023 02:25:26 GMT</pubDate>
            <atom:updated>2023-10-05T03:11:49.986Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why some proteins are allergenic? Part I. Exploratory data analysis of protein sequences and properties</h3><p>In this post, I am scraping protein sequence data in FASTA format from the website, parsing it into python and do some statistical analysis and visualization.</p><p>GitHub:</p><p><a href="https://github.com/RonghuiZhou/protein_analysis/blob/main/1.%20Exploratory%20Data%20Analysis.ipynb">protein_analysis/1. Exploratory Data Analysis.ipynb at main · RonghuiZhou/protein_analysis</a></p><p>I am interested in analyzing allergenic proteins, trying to understand why some proteins are allergenic while others are not. From the protein sequence and physical chemical properties, can we distill any meaningful information, so as to predict which protein has allergenic potential?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*E3sIOkJrLuXfPBLq25W8RQ.jpeg" /><figcaption><a href="https://www.nutraingredients.com/Article/2017/12/04/Dietary-protection-Proteins-in-mum-s-milk-could-protect-against-food-allergy">https://www.nutraingredients.com/Article/2017/12/04/Dietary-protection-Proteins-in-mum-s-milk-could-protect-against-food-allergy</a></figcaption></figure><p>I will be using data for this paper:</p><p>Sharma et al. (2021) AlgPred 2.0: an improved method for predicting allergenic proteins and mapping of IgE epitopes, <a href="https://academic.oup.com/bib/advance-article-abstract/doi/10.1093/bib/bbaa294/5985292?fbclid=IwAR1Q-60U7U7Kkzhmb7e-J4_641Y7KiH2fSaOq4bdnaRLxmyoe-rr8J1htjA">Briefings in Bioinformatics,22(4): bbaa294.</a></p><h3>Data Loading</h3><p>Data is loaded into python with these libraries: requests and biopython</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HQ5aqsFXLqFcpYmdBFw1KQ.png" /></figure><h3>Encoding</h3><p>Amino acids can be encoded based on their properties, here we encode based on <em>Hydrophobicity index. Reference: </em><a href="https://www.genome.jp/entry/aaindex:ARGP820101"><em>https://www.genome.jp/entry/aaindex:ARGP820101</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6MbIHAagAOMDnLhP1ZmRng.png" /></figure><p>Before that, we standardize the encoding scheme.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*2XvxWDC_Rv8V2lcAL5gYYw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*36a1sPY0R6EU83f-J4OK4A.png" /></figure><h3>Protein Properties</h3><p>We calculate seqeunce length, composition and several properties by using the <strong>ProteinAnalysis </strong>module from the Biopython library.</p><pre>https://biopython.org/docs/1.75/api/Bio.SeqUtils.ProtParam.html</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KDDJ2VyIWUKRnwgj4gbMDA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*SvyBHp3ztQymW9bkfqZ7cQ.png" /></figure><h3>Exploratory Data Analysis</h3><ol><li>Protein sequence length distribution</li></ol><p>There are quite some variations in terms of the length of protein sequences, but the majority is in the hundreds range. 90 percentiles is marked with the solid purple line. Blue charts are the histograms and dashed red lines represent the cumulative distribution function.</p><p>For the purpose of building machine learning/deep learning models, we often need to make a uniform set in terms of sequence length.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*5kBgk3JeGgFeh7P30EMT5g.png" /></figure><p>2. Gravy (a measure of its hydrophobicity or hydrophilicity)</p><p>The GRAVY value is calculated by adding the hydropathy value for each residue and dividing by the length of the sequence (<a href="https://www.ncbi.nlm.nih.gov/entrez/query.fcgi?cmd=Retrieve&amp;db=PubMed&amp;list_uids=7108955&amp;dopt=Abstract">Kyte and Doolittle; 1982</a>).</p><p><a href="https://www.bioinformatics.org/sms2/protein_gravy.html#:~:text=Protein%20GRAVY&amp;text=Protein%20GRAVY%20returns%20the%20GRAVY,Kyte%20and%20Doolittle%3B%201982">https://www.bioinformatics.org/sms2/protein_gravy.html#:~:text=Protein%20GRAVY&amp;text=Protein%20GRAVY%20returns%20the%20GRAVY,Kyte%20and%20Doolittle%3B%201982</a>).</p><p>It’s hard to say where gravy is important for a protein to be allergenic or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*u54dL-qbzZfDDXvuunlPVQ.png" /></figure><p>3. Aromaticity</p><p>These electrons give rise to what is known as a π-electron cloud over the ring. Aromaticity is a chemical property associated with such cyclic and planar compounds and is attributed to these π-electrons which are free to cycle around the circular arrangements of atoms found in the aromatic moieties. (<a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3530875/#:~:text=These%20electrons%20give%20rise%20to,found%20in%20the%20aromatic%20moieties">https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3530875/#:~:text=These%20electrons%20give%20rise%20to,found%20in%20the%20aromatic%20moieties</a>.)</p><p>Again there is no clear evidence of correlation between aromaticity and allergenicity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*jOQHCEYbuzxLHuf-1N5sYg.png" /></figure><p>4. Instability</p><p>Proteins and peptides are only stable in a limited range of concentration, temperature, ionic strength and acidity conditions (marginal stability) and are very prone to physical and chemical destabilizations. Many recombinant proteins are also under conditions that become unstable and lose their correct folding. (<a href="https://www.ncbi.nlm.nih.gov/pmc/articles/PMC9699111/#:~:text=Proteins%20and%20peptides%20are%20only,and%20lose%20their%20correct%20folding">https://www.ncbi.nlm.nih.gov/pmc/articles/PMC9699111/#:~:text=Proteins%20and%20peptides%20are%20only,and%20lose%20their%20correct%20folding</a>.)</p><p>Again there is no clear evidence of correlation between instability and allergenicity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*8t2IZBZOiOR7-G0g2MU9HQ.png" /></figure><p>5. Isoelectric Point</p><p>The isoelectric point (pI) of a protein is defined as the pH at which the net charge of a protein molecule is zero. Accordingly, proteins are positively charged at a pH below their pI and negatively charged at a pH above their pI. (<a href="https://www.frontiersin.org/articles/10.3389/fmolb.2021.775736/full#:~:text=specific%20pI%20profiles.-,Introduction,a%20pH%20above%20their%20pI">https://www.frontiersin.org/articles/10.3389/fmolb.2021.775736/full#:~:text=specific%20pI%20profiles.-,Introduction,a%20pH%20above%20their%20pI</a>.)</p><p>From the figure below, positive cases seem to have a slightly lower isoelectric point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*TZ4HXQ6wsJlvs53R6jFVBw.png" /></figure><p>6. Flexibility</p><p>Protein flexibility correlates with a variety of physical properties, such as solvent exposure, distance from center-of-mass, and secondary structure. The most frequently invoked correlation is that with solvent-accessible surface area (SASA). (<a href="https://www.pnas.org/doi/10.1073/pnas.032522499#:~:text=Protein%20flexibility%20correlates%20with%20a,5%2C%2012%2C%2029">https://www.pnas.org/doi/10.1073/pnas.032522499#:~:text=Protein%20flexibility%20correlates%20with%20a,5%2C%2012%2C%2029</a>).)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*f_JMlxp4TFOv0ntHiMqmQA.png" /></figure><p>7. Extinction Coefficient</p><p>Most protein extinction coefficients range from 4.0 to 24.0. Therefore, although any given protein can vary significantly from εpercent = 10, the average for a mixture of many different proteins likely will be approximately 10. (<a href="https://assets.thermofisher.com/TFS-Assets/LSG/Application-Notes/TR0006-Extinction-coefficients.pdf">https://assets.thermofisher.com/TFS-Assets/LSG/Application-Notes/TR0006-Extinction-coefficients.pdf</a>)</p><p>Extinction coefficients for proteins are determined at absorbance maxima near 280 nm. Protein analysis is needed to determine if a sample solution contains the desired protein. For example, measuring the absorbance of a protein sample at 280 nm with a spectrophotometer is a rapid and straightforward method. (<a href="https://www.biosyn.com/tew/How-is-Extinction-Coefficient-Determined-for-Proteins.aspx#:~:text=Extinction%20coefficients%20for%20proteins%20are,a%20rapid%20and%20straightforward%20method">https://www.biosyn.com/tew/How-is-Extinction-Coefficient-Determined-for-Proteins.aspx#:~:text=Extinction%20coefficients%20for%20proteins%20are,a%20rapid%20and%20straightforward%20method</a>.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*OEHps6Cx693fHnByylN8Gw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*t-pOXZCqdI7Xovz4PlagSA.png" /></figure><p>9. Secondary Structure</p><p><strong>Protein secondary structure</strong> is the local spatial conformation of the <a href="https://en.wikipedia.org/wiki/Polypeptide">polypeptide</a> backbone excluding the side chains. The two most common <a href="https://en.wikipedia.org/wiki/Protein_structure#Secondary_structure">secondary structural elements</a> are <a href="https://en.wikipedia.org/wiki/Alpha_helix">alpha helices</a> and <a href="https://en.wikipedia.org/wiki/Beta_sheet">beta sheets</a>, though <a href="https://en.wikipedia.org/wiki/Beta_turn">beta turns</a> and <a href="https://en.wikipedia.org/wiki/Omega_loop">omega loops</a> occur as well. Secondary structure elements typically spontaneously form as an intermediate before the protein <a href="https://en.wikipedia.org/wiki/Protein_folding">folds</a> into its three dimensional <a href="https://en.wikipedia.org/wiki/Protein_tertiary_structure">tertiary structure</a>.</p><p>Secondary structure is formally defined by the pattern of <a href="https://en.wikipedia.org/wiki/Hydrogen_bond">hydrogen bonds</a> between the <a href="https://en.wikipedia.org/wiki/Amine">amino</a> hydrogen and <a href="https://en.wikipedia.org/wiki/Carboxyl">carboxyl</a> oxygen atoms in the peptide <a href="https://en.wikipedia.org/wiki/Backbone_chain">backbone</a>. Secondary structure may alternatively be defined based on the regular pattern of backbone <a href="https://en.wikipedia.org/wiki/Dihedral_angle#Dihedral_angles_of_proteins">dihedral angles</a> in a particular region of the <a href="https://en.wikipedia.org/wiki/Ramachandran_plot">Ramachandran plot</a> regardless of whether it has the correct hydrogen bonds.</p><p>The concept of secondary structure was first introduced by <a href="https://en.wikipedia.org/wiki/Kaj_Ulrik_Linderstr%C3%B8m-Lang">Kaj Ulrik Linderstrøm-Lang</a> at <a href="https://en.wikipedia.org/wiki/Stanford">Stanford</a> in 1952. Other types of <a href="https://en.wikipedia.org/wiki/Biopolymer">biopolymers</a> such as <a href="https://en.wikipedia.org/wiki/Nucleic_acid">nucleic acids</a> also possess characteristic <a href="https://en.wikipedia.org/wiki/Nucleic_acid_secondary_structure">secondary structures</a>.</p><p>(<a href="https://en.wikipedia.org/wiki/Protein_secondary_structure">https://en.wikipedia.org/wiki/Protein_secondary_structure</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*tPYr_1W-HJmSj8Au1B-k0w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*2vByNdR2Z8Ir_LBwwT6L5Q.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff4c53aa3df7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LC/MS data processing and plotting with Python (editing)]]></title>
            <link>https://ronghui-zhou.medium.com/lc-ms-data-processing-and-plotting-with-python-editing-48bf0f72bd15?source=rss-cd5a61234de5------2</link>
            <guid isPermaLink="false">https://medium.com/p/48bf0f72bd15</guid>
            <category><![CDATA[analytical-chemistry]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[chromatography]]></category>
            <category><![CDATA[lcms]]></category>
            <category><![CDATA[agilent]]></category>
            <dc:creator><![CDATA[Ronghui Zhou, Ph.D.]]></dc:creator>
            <pubDate>Sun, 15 Aug 2021 01:41:15 GMT</pubDate>
            <atom:updated>2021-08-17T16:47:42.741Z</atom:updated>
            <content:encoded><![CDATA[<p>In this work, I am developing python scripts to process and plot LC/MS data acquired from Agilent 1260 HPLC — G6120B MSD.</p><p>Here is the figure generated in Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Mv1KYF9FQdRsfMPQvCse5Q.png" /><figcaption>LCMS of Sulfa Drug Standard</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Tcd59fb0Q9FwjlYnksbg2g.png" /><figcaption>1st derivative of LCMS</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*FBje8veokSxzzoJZUpSjzQ.png" /><figcaption>2nd derivative of LCMS</figcaption></figure><p>Sulfa Drug Standard Kit is used.</p><p><a href="https://www.agilent.com/store/en_US/Prod-5188-6523/5188-6523">5188-6523 | Agilent</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xoh9L4jOob3w7PJkSL_REw.png" /><figcaption>Sulfa Drug LCMS Standard</figcaption></figure><p>MassHunter Analytical Studio Reviwer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L3EXD6U67O6MJl8v4c57mw.png" /></figure><p>Below is part of the PDF report generated by the instrument:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*Mld585_yg14aDCaLdHb8FA.png" /></figure><p>Work in progress.</p><p><a href="https://github.com/RonghuiZhou/LCMS/tree/main/plotLCMS">GitHub</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48bf0f72bd15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NMR Data Processing and Plotting with Python]]></title>
            <link>https://python.plainenglish.io/nmr-data-processing-and-plotting-with-python-645e6b859628?source=rss-cd5a61234de5------2</link>
            <guid isPermaLink="false">https://medium.com/p/645e6b859628</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Ronghui Zhou, Ph.D.]]></dc:creator>
            <pubDate>Sun, 08 Aug 2021 03:09:03 GMT</pubDate>
            <atom:updated>2021-08-10T06:17:56.685Z</atom:updated>
            <content:encoded><![CDATA[<p>In this work, I am plotting 1D NMR spectrum with Python and also extracting the chemical shift information about the highest peak (water peak in this case).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*hdpRr5xT6nOEHuFSLraLcA.png" /><figcaption>NMR spectrum in Python</figcaption></figure><p>This is a proton NMR spectrum of <a href="https://en.wikipedia.org/wiki/Ibuprofen">Ibuprofen</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*hcV9bhBulF8L3df6.png" /><figcaption>Ibuprofen</figcaption></figure><p>Below is a sample report generated with ACD/Labs <a href="https://www.acdlabs.com/products/adh/spectrusprocessor/?gclid=CjwKCAjw3riIBhAwEiwAzD3TidSpzjU4XTrZ0HqhDLqbSe-Kb5SZtdQ7h7nlzcSSxZTmlMo7msxnrRoCgEUQAvD_BwE">Spectrus Processor</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*fwnr-A1McJJu8JIx3SuN5A.png" /></figure><p>As you can see, there is a huge water peak from the NMR solvent (DMSO-d6). This is not too bad here but for many other samples with limited quantity, water peak is overwhelming the spectrum. A typical approach is to use a water suppression pulse sequence (Bruker: zgpr) to reduce water signal, so the peaks of interest will be stronger as the receiver gain is automatically adjusted during data acquisition.</p><p>For water suppression experiment (zgpr) to work well, we need to specify the exact position of water peak in terms of ppm, the Bruker parameter as o1p. For that purpose, we need to extract the chemical shift of water peak. It is okay to look at a few samples manually, but for a large set of samples and higher work efficiency, it’s desirable to automate this workflow with Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*Jaj4L_j0Vgy-f9YKplO0kA.png" /><figcaption>zgpr pulse sequence</figcaption></figure><p>The main tool used in this work is the nmrglue package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/99/0*rvSpNjYcf8GeZAp5.jpg" /><figcaption>nmrglue</figcaption></figure><p>Here, processed NMR data is read into Python with nmrglue’s bruker module.</p><p>dic, data = ng.bruker.read_pdata(pfile)</p><p>NMR data is processed and converted to a different format to generate chemical shift scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*u7NXR13Rk168foFAuL2nUA.png" /></figure><p>Water peak chemical shift is extracted using numpy and labelled on the spectrum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*3AnbtHWAmm2nyV0Nt11_6Q.png" /></figure><p>X axis is reversed to match with NMR convention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*SGFdSxx8RuvpgkfcWmyljg.png" /></figure><p>With this, it is straightforward to automate water peak extraction for any amount of samples. This will greatly improve the work efficiency and release NMR spectroscopists from tedious work of looking into each individual spectrum, zooming into a certain region, reading the chemical shift of water peak and writing it down in a table. It’s a trivial task to automate all these for a data scientist.</p><p>All Python code and raw NMR data can be found in my GitHub <a href="https://github.com/RonghuiZhou/NMR/tree/main/plotNMR">here</a>.</p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=645e6b859628" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/nmr-data-processing-and-plotting-with-python-645e6b859628">NMR Data Processing and Plotting with Python</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Content-aware image resizing, seam carving]]></title>
            <link>https://ronghui-zhou.medium.com/content-aware-image-resizing-seam-carving-79e14dfe303b?source=rss-cd5a61234de5------2</link>
            <guid isPermaLink="false">https://medium.com/p/79e14dfe303b</guid>
            <category><![CDATA[computational-photography]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Ronghui Zhou, Ph.D.]]></dc:creator>
            <pubDate>Thu, 15 Oct 2020 01:30:34 GMT</pubDate>
            <atom:updated>2020-10-15T01:30:34.522Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gzVZLmQpL1z0mHKc4DIVfQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79e14dfe303b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Edge Detection with Sobel filter]]></title>
            <link>https://ronghui-zhou.medium.com/edge-detection-with-sobel-filter-f4a69348d46b?source=rss-cd5a61234de5------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4a69348d46b</guid>
            <category><![CDATA[sobel-filter]]></category>
            <category><![CDATA[edge-detection]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Ronghui Zhou, Ph.D.]]></dc:creator>
            <pubDate>Tue, 13 Oct 2020 12:48:30 GMT</pubDate>
            <atom:updated>2020-10-13T13:13:38.410Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6NU-NaDUwfHeiaOaJ4F4cg.png" /><figcaption>Kids Mountain Playground: <a href="https://www.lionspridepark.org/">https://www.lionspridepark.org/</a></figcaption></figure><p>Here is the original image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G8pN9A_fdnyXx0YoKYhZkw.jpeg" /><figcaption>Kids Mountain Playground: <a href="https://www.lionspridepark.org/">https://www.lionspridepark.org/</a></figcaption></figure><p>This was achieved with the Sobel filter in OpenCV:</p><p><a href="https://en.wikipedia.org/wiki/Sobel_operator">https://en.wikipedia.org/wiki/Sobel_operator</a></p><p><a href="https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_gradients/py_gradients.html">Image Gradients - OpenCV-Python Tutorials 1 documentation</a></p><p>Contact me for Python code on <a href="https://www.linkedin.com/in/ronghuizhou/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4a69348d46b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Python or Organic/Medicinal Chemistry] How You Can Play with Molecular Structure in Python I.]]></title>
            <link>https://ronghui-zhou.medium.com/python-or-organic-medicinal-chemistry-how-you-can-play-with-molecular-structure-in-python-i-fad10532fa06?source=rss-cd5a61234de5------2</link>
            <guid isPermaLink="false">https://medium.com/p/fad10532fa06</guid>
            <category><![CDATA[molecule]]></category>
            <category><![CDATA[organic]]></category>
            <category><![CDATA[drawing]]></category>
            <category><![CDATA[drugs]]></category>
            <category><![CDATA[structure]]></category>
            <dc:creator><![CDATA[Ronghui Zhou, Ph.D.]]></dc:creator>
            <pubDate>Sun, 12 Jul 2020 11:09:05 GMT</pubDate>
            <atom:updated>2020-07-12T14:08:19.789Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*CY3oNocFU9t4QZm0iVeGjg.png" /><figcaption>Drugs Made in Python</figcaption></figure><h3>[Python for Organic/Medicinal Chemistry] How You Can Play with Molecular Structures of Drugs in Python I. Drawing &amp; Converting File Format</h3><p>In this post, I will show you how to convert drug names into molecular structure, save into Excel, read into Python, display the structure, and convert file format.</p><p>The motivation was really to batch process a large number of organic molecules in a specific way to support drug discovery. In an effort to build high-throughput NMR (Nuclear Magnetic Resonance) capability, we are going to use either one of the two leading analytical data processing software programs from <a href="https://mestrelab.com/">MestReNova</a> or <a href="https://www.acdlabs.com/">ACD/Labs</a> for automated structure verification of small molecules using NMR &amp; LC/MS data. This, of course, requires the input of molecular structure information, preferably in the <a href="https://en.wikipedia.org/wiki/Chemical_table_file">MDL Molfile (.mol)</a> format by vendors.</p><p>Notably, there is another format for molecular structure information, namely <a href="https://en.wikipedia.org/wiki/Simplified_molecular-input_line-entry_system"><strong>Simplified Molecular-Input Line-Entry System</strong> (<strong>SMILES</strong>)</a>. Different from the MDL Molfile format which is two-dimensional, SMILES is a one-dimensional string. Thus it is much more convenient to store and communicate for a large number of molecules in the SMILES format.</p><p>Let’s see <a href="https://en.wikipedia.org/wiki/Aspirin">Aspirin </a>as an example (you can easily understand why SMILES format is preferred for database storage, a single line!):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S9_C2zayHhFQfXxLYe0u0A.png" /></figure><p>As mentioned earlier, we need a .mol file to go with analytical data for automated structure verification. In the high-throughput mode, we are processing hundreds of samples every day. It will get very tedious quickly to prepare hundreds of .mol files. Luckily, we have an internal database (Oracle-based) where we may query structural information for a batch of compounds and download as SMILES strings into a CSV file via Python &amp; SQL. I wish data processing vendors can take SMILES files as the input but it is not currently supported for every vendor. Instead, MDL Molfiles are preferred. As such, I need to convert the file format.</p><p>Of course, you may read in SMILES strings into ChemDraw and convert into Molfiles one-by-one. But that’s definitely not the approach for a data scientist. Luckily the <a href="http://www.rdkit.org/">RDKit </a>package (RDKit: Open-Source Cheminformatics Software) turns out to be extremely handy!</p><p>I have two posts on LinkedIn: <a href="https://www.linkedin.com/pulse/molecular-structure-drugs-python-ronghui-zhou/">1st edition</a> &amp; <a href="https://www.linkedin.com/posts/ronghuizhou_manipulating-molecular-structures-of-drugs-activity-6687830908734631936-W4pm">2nd edition</a>.</p><p>Let me show you how I did.</p><h3>Step 1. Convert Name to Structure in ChemDraw; or Draw the Structure in the Preferred Software</h3><h4>[<a href="https://www.perkinelmer.com/category/chemdraw">ChemDraw</a>] Menu -&gt; Structure → Convert Name to Structure (Shift + Ctrl + N)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/0*R9fdq_0Bn-dtTOnv" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/0*huffsSN4x36Y_ZDZ" /></figure><h3>Step 2. Copy Structure as SMILES to Excel or CSV file</h3><h4>A. Select the molecule and go to Menu → Edit → Copy As → SMILES (Alt + Ctrl + C)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*d5tAgiRGBNGy-h3E" /></figure><h4>B. Paste into CSV or Excel file</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/0*1WaCOQ84lq49-Whh" /></figure><h3>Step 3. Read into Jupyter Notebook using Pandas</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*ff4C7JYPiYU_ovAsGQ-33w.png" /><figcaption>Import drug names &amp; SMILES strings</figcaption></figure><h3>Step 4. Display Chemical Structure with the Chem Module from RDKit</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*ML-YMxGH5gZmzgRhd7lpWw.png" /><figcaption>Aspirin in Python</figcaption></figure><h3>Step 5. Set up Directory, Convert Format, and Output Files</h3><h4>A. Set up directories</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*7KhlsYX5eVLpDJhYIrC92A.png" /><figcaption>Set up directories for different file formats</figcaption></figure><h4>B. Convert format and export files</h4><pre># initiate an empty list to accept all drug structure<br>structure_lst = []</pre><pre># iterate through the whole csv file<br>for i in range(drugs.shape[0]):<br>    <br>    ###################################################<br>    # get the drug name<br>    drug = drugs.loc[i, &#39;Drug Name&#39;]<br>    print(f&#39;\n\033[1m{drug}\033[0m:&#39;)</pre><pre># get the SMILES string<br>    smiles = drugs.loc[i, &#39;SMILES&#39;]<br>    <br>    # convert SMILES string to structure<br>    structure = Chem.MolFromSmiles(smiles)<br>    <br>    # append the structure to the list<br>    structure_lst.append(structure)<br>    <br>    ###################################################<br>    # configure the filename and path for .smi files<br>    smi_file = drug + &#39;.smi&#39;<br>    smi_path = os.path.join(smi_dir, smi_file)   <br>    <br>    ###################################################<br>    # configure the filename and path for .mol files<br>    mol_file = drug + &#39;.mol&#39;<br>    mol_path = os.path.join(mol_dir, mol_file)       <br>   <br>    ###################################################<br>    # configure the filename and path for .sdf files<br>    sdf_file = drug + &#39;.sdf&#39;<br>    sdf_path = os.path.join(sdf_dir, sdf_file)           <br>    <br>    ###################################################<br>    # configure the filename and path for .png files<br>    img_file = drug + &#39;.png&#39;<br>    img_path = os.path.join(img_dir, img_file)    <br>    <br>    <br>    ###################################################<br>    # iterate through .smi, .mol and .sdf files<br>    for item in [smi_path, mol_path, sdf_path]:<br>        try:<br>            if item == smi_path:<br>                f = open(item, &quot;w+&quot;)<br>                f.write(smiles)<br>                f.close()<br>            else:<br>                w = Chem.SDWriter(item)<br>                w.write(structure)<br>                w.close()<br>            print(f&quot;\t.{item.rsplit(&#39;.&#39;,1)[1]} file saved&quot;)<br>        except:<br>            print(f&quot;\t{item.rsplit(&#39;.&#39;,1)[1]} file failed&quot;)<br>            pass</pre><pre># export individual png file<br>    try:<br>        Chem.Draw.MolToFile(structure, img_path, size = (200,200), legend = drug) <br>        print(&#39;\t.png file saved&#39;)<br>    except:<br>        print(&#39;\tImage failed&#39;)<br>        pass</pre><pre>###################################################<br># configure the filename and path for drug_all.sdf file<br>sdf_all_file = &#39;Drugs.sdf&#39;<br>sdf_all_path = os.path.join(sdf_dir, sdf_all_file)</pre><pre>try:<br>    w = Chem.SDWriter(sdf_all_path)<br>    for structure in structure_lst:<br>        w.write(structure)<br>    w.close()    <br>    print(&#39;\nA big sdf file saved for all drugs as &quot;drug_all.sdf&quot;.&#39;)</pre><pre>except:<br>    print(&#39;\tBig sdf for all drugs failed&#39;)<br>    pass<br>    <br>######################################################################################################    <br>img_all_path = os.path.join(img_dir, &#39;drug_all.png&#39;)<br># export a big png file for all drugs <br>try:<br>    img_all = Chem.Draw.MolsToGridImage(structure_lst, molsPerRow=4, subImgSize=(200,200),legends = drugs[&#39;Drug Name&#39;].tolist())    <br>    img_all.save(img_all_path) <br>    print(&#39;\nA big image saved for all drugs as &quot;drug_all.png&quot;.&#39;)<br>except:<br>    print(&#39;\tBig image for all drugs failed&#39;)<br>    pass</pre><pre>print(&#39;\n\x1b[6;30;42m&#39; + &#39;All DONE!&#39; + &#39;\x1b[0m&#39;)</pre><p><strong>Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*CY3oNocFU9t4QZm0iVeGjg.png" /><figcaption>Drugs Made in Python</figcaption></figure><p>This Jupyter Notebook is available on <a href="https://github.com/RonghuiZhou/Chem_Drugs/blob/master/2nd%20edition/Manipulating%20Molecular%20Structures%20of%20Drugs%20in%20Python.ipynb">GitHub</a>. Contact me on <a href="https://www.linkedin.com/in/ronghuizhou/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fad10532fa06" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ICU Survival Rate within 30 days Leveraging Natural Language Processing]]></title>
            <link>https://ronghui-zhou.medium.com/icu-survival-rate-within-30-days-leveraging-natural-language-processing-a0d8fcaeecde?source=rss-cd5a61234de5------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0d8fcaeecde</guid>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[healthcare]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[notes]]></category>
            <dc:creator><![CDATA[Ronghui Zhou, Ph.D.]]></dc:creator>
            <pubDate>Sun, 29 Mar 2020 12:40:02 GMT</pubDate>
            <atom:updated>2020-04-07T13:04:20.718Z</atom:updated>
            <content:encoded><![CDATA[<h3>[Statistical Analysis &amp; Healthcare NLP] Predicting ICU Survival Rate within 30 Days Leveraging Natural Language Processing Based Machine Learning Pipelines</h3><p><a href="https://www.udacity.com/course/data-scientist-nanodegree--nd025">Udacity Data Scientist Nanodegree</a> Capstone Project, March 2020</p><p>Author: <a href="https://www.linkedin.com/in/ronghuizhou">Ronghui Zhou, Ph.D.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hms7y4m5RQAfSZdK.jpg" /><figcaption><a href="https://www.infectioncontroltoday.com/intensive-care-unit/test-can-identify-icu-patients-risk-life-threatening-infections">https://www.infectioncontroltoday.com/intensive-care-unit/test-can-identify-icu-patients-risk-life-threatening-infections</a></figcaption></figure><h3>Note</h3><p>This dataset is obtained from <a href="https://mimic.physionet.org/">MIMIC</a>. All codes are available on <a href="https://github.com/RonghuiZhou/Predicting-ICU-Survival-Rate-Leveraging-NLP-based-Machine-Learning-Pipelines">GitHub</a>.</p><p>— — — — — — — — — — — — — — — — — — — — — — — —</p><h3>Acknowledgements</h3><blockquote><em>MIMIC-III, a freely accessible critical care database. Johnson AEW, Pollard TJ, Shen L, Lehman L, Feng M, Ghassemi M, Moody B, Szolovits P, Celi LA, and Mark RG. Scientific Data (2016). DOI: </em><a href="http://dx.doi.org/10.1038/sdata.2016.35"><em>10.1038/sdata.2016.35</em></a><em>. Available at: </em><a href="http://www.nature.com/articles/sdata201635"><em>http://www.nature.com/articles/sdata201635</em></a></blockquote><p><a href="https://towardsdatascience.com/introduction-to-clinical-natural-language-processing-predicting-hospital-readmission-with-1736d52bc709">Introduction to Clinical Natural Language Processing: Predicting Hospital Readmission with…</a></p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — -</p><h3>1. Introduction</h3><h4>Project Overview</h4><p>This project will outline how to select a patient cohort, clean the data for exploratory visualization and building a classification model to predict the mortality within 30 days after ICU admission, utilizing initial caregivers’ notes.</p><h4>Problem Statement</h4><p>The goal is to identify potential high risk patients and try to predict the possibility of survival within 30 days after the ICU admission. If the chance is low, actions should be taken to intervene.</p><h4>Data Set</h4><p><a href="https://mimic.physionet.org/">https://mimic.physionet.org/</a></p><p>MIMIC-III (Medical Information Mart for Intensive Care III) is a large, freely-available database comprising deidentified health-related data associated with over forty thousand patients who stayed in critical care units of the Beth Israel Deaconess Medical Center between 2001 and 2012.</p><p>The database includes information such as demographics, vital sign measurements made at the bedside (~1 data point per hour), laboratory test results, procedures, medications, caregiver notes, imaging reports, and mortality (both in and out of hospital).</p><p>MIMIC is made available largely through the work of researchers at the MIT Laboratory for Computational Physiology and collaborating research groups.</p><p>MIMIC-III, a freely accessible critical care database. Johnson AEW, Pollard TJ, Shen L, Lehman L, Feng M, Ghassemi M, Moody B, Szolovits P, Celi LA, and Mark RG. Scientific Data (2016). DOI: 10.1038/sdata.2016.35.</p><p>Available at: <a href="http://www.nature.com/articles/sdata201635">http://www.nature.com/articles/sdata201635</a></p><p>To gain access to the data, you will need to complete the CITI “Data or Specimens Only Research” course</p><p><a href="https://mimic.physionet.org/gettingstarted/access/">https://mimic.physionet.org/gettingstarted/access/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZTqM2f6pxmmwLZR1GtAmAg.png" /></figure><h4>Metrics</h4><p>We will evaluate the performance of machine learning models based on accuracy and confusion matrix.</p><p>Classification report shows the metrics: precision, recall, f1-score, and support.</p><h4>Brief Summary</h4><p>a. Age distribution</p><pre>The average age of patients died is significantly higher than patients survived (more than 10 years older). It makes sense as older people have weaker health condition and harder to recover from serious diseases.</pre><p>b. Insurance distribution</p><pre>It is found that significantly higher portion of patients died had Medicare insurance, in comparison to private insurance for patients survived.</pre><p>c. Top 10 diagnoses for different patient groups</p><pre>What are the top reasons for patients to go to ICU and die? In this data set, the top 10 reasons for going to ICU are: pneumonia, sepsis, intracranial hemorrhage, coronary artery disease, congestive heart failure, chest pain, altered mental status, gastrointestinal bleed, subarachnoid hemorrhage, and abdominal pain. Five out of these have less than 50% survival rate within 30 days, with the least one being sepsis with less than 30% patients survived.</pre><p>d. Machine learning algorithm predicting mortality:</p><pre>Clearly, logistic regression is the winner in all different metrics. More importantly, the metrics for patients died improved significantly after balancing the data with under-sampling. The scores are comparable for both survived patients and died patients.</pre><h3>2. Patient Cohort &amp; Data Preparation</h3><h4>Patient Cohort</h4><p>In this project, ICU patients in the age range 18 to 100 will be selected.</p><h4>Database Setup: PostgreSQL</h4><p><a href="https://mimic.physionet.org/tutorials/install-mimic-locally-windows/">https://mimic.physionet.org/tutorials/install-mimic-locally-windows/</a></p><p>Installing MIMIC-III in a local Postgres database on Windows</p><p>Note that before proceeding with this guide you will need to:</p><p>a. Download the MIMIC-III Clinical Database<br>b. Extract the MIMIC-III Clinical Database as .csv files somewhere on your local computer<br>c. Download the PostgreSQL scripts — only the files which end in .sql are required</p><p>Note: I tried to install gzip and 7-zip and added to the path, but didn’t work. So I installed cygwin which worked for me.<br><a href="https://cygwin.com/install.html">https://cygwin.com/install.html</a></p><h4>PostgreSQL tables</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*5cuTvXSdgviITr_RU4_T-g.png" /><figcaption>postgresql database</figcaption></figure><h4>Import libraries</h4><pre># Import libraries<br>import numpy as np<br>import pandas as pd<br>import seaborn as sns<br>import matplotlib.pyplot as plt<br>import psycopg2<br>import getpass</pre><pre>%matplotlib inline<br>plt.style.use(&#39;ggplot&#39;)</pre><h4>Set up database connnection</h4><pre># information used to create a database connection<br>sqluser = &#39;postgres&#39;<br>host = &#39;localhost&#39;<br>dbname = &#39;mimic&#39;<br>schema_name = &#39;mimiciii&#39;</pre><pre># Connect to postgres with a copy of the MIMIC-III database (pwd: whatever you specified when setting up the database)<br>con = psycopg2.connect(dbname=dbname, user=sqluser, host=host, <br>                      password=getpass.getpass(prompt=&#39;Password:&#39;.format(sqluser)))</pre><pre># the below statement is prepended to queries to ensure they select from the right schema<br>cur = con.cursor()<br>cur.execute(&#39;SET search_path to {}&#39;.format(schema_name))</pre><h4>Get data from noteevents table</h4><pre># check noteevents table<br># partition by subject_id &amp; hadm_id<br># then order by chartdate and storetime to select only the first note upon entering the hospital<br># exlude notes in the categories of ECG, Echo, Radiology and Discharge summary, as there is no date</pre><pre>query = \<br>&quot;&quot;&quot;<br>with nts as<br>(<br>SELECT subject_id, hadm_id, chartdate, storetime, category, text</pre><pre>, RANK() OVER (PARTITION BY subject_id, hadm_id ORDER BY chartdate, storetime) AS storetime_order</pre><pre>FROM noteevents<br>WHERE category NOT IN (&#39;ECG&#39;, &#39;Echo&#39;, &#39;Radiology&#39;, &#39;Discharge summary&#39;)</pre><pre>)</pre><pre>SELECT *</pre><pre>, CASE<br>    WHEN storetime_order &gt;1 THEN 1<br>    ELSE 0 END AS exclusion_storetime_order</pre><pre>from nts</pre><pre>WHERE storetime_order=1</pre><pre>ORDER BY subject_id, hadm_id, chartdate, storetime</pre><pre>&quot;&quot;&quot;<br>df_nts = pd.read_sql_query(query, con)</pre><h4>Noteevents table</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ffYHf2Cs_0u5Fu7RML2gcg.png" /><figcaption>a peak at the noteevents table</figcaption></figure><h4>Category of notes</h4><p>There are notes from different caregivers. Notes from these four categories (‘ECG’, ‘Echo’, ‘Radiology’, ‘Discharge summary’) are note selected as there is no related timestamp in the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*aFjrigSq-XG1W42zx4MRJQ.png" /><figcaption>note category</figcaption></figure><h4>Get data from other three tables</h4><pre># join multiple tables together to get the age<br># get patients 18-100 years old<br># first select icustays table and then inner join with patients and admissions<br># get the age of admission based on the icu.intime and date of birth<br># get the days patient died after icu admission by subtracting icu.intime from date of death<br># set some criteria to slice the database: exlucision_age: &lt;18 or &gt;100<br># los_death: &gt;30; survived or died more than 30 days later or survived within 30 days<br># exclude &#39;Elective&#39; and &#39;Newborn&#39;</pre><pre>query = \<br>&quot;&quot;&quot;<br>WITH co AS<br>(<br>SELECT icu.subject_id, icu.hadm_id, icu.icustay_id, icu.intime, icu.los<br>, EXTRACT(&#39;epoch&#39; from icu.intime - pat.dob) / 60.0 / 60.0 / 24.0 / 365.242 as age<br>, EXTRACT(&#39;epoch&#39; from pat.dod - pat.dob) / 60.0 / 60.0 / 24.0 / 365.242 as death_age<br>, EXTRACT(&#39;epoch&#39; from pat.dod - icu.intime) / 60.0 / 60.0 / 24.0 as los_death<br>, pat.gender, pat.dob, pat.dod, pat.dod_hosp, pat.expire_flag<br>, adm.admission_type, adm.admission_location, adm.insurance, adm.language<br>, adm.religion, adm.marital_status, adm.ethnicity, adm.diagnosis</pre><pre>, RANK() OVER (PARTITION BY icu.subject_id ORDER BY icu.intime) AS icustay_id_order</pre><pre>FROM icustays icu</pre><pre>INNER JOIN patients pat ON icu.subject_id=pat.subject_id</pre><pre>INNER JOIN admissions adm ON icu.hadm_id=adm.hadm_id</pre><pre>)</pre><pre>SELECT *</pre><pre>,CASE<br>    WHEN icustay_id_order &gt; 1 THEN 1<br>    ELSE 0 END AS exclusion_icustay_id_order</pre><pre>, CASE<br>    WHEN age &lt; 18 or age &gt;100 then 1<br>    ELSE 0 END as exclusion_age<br>, CASE<br>    WHEN los_death &gt;30 then 1<br>    ELSE 0 END as exclusion_los_death</pre><pre>FROM co<br>WHERE admission_type !=&#39;ELECTIVE&#39;<br>AND admission_type !=&#39;NEWBORN&#39;<br>&quot;&quot;&quot;<br>df_icu = pd.read_sql_query(query, con)</pre><h4>Join these two tables together to get the final table of interest</h4><pre># inner join the two dataframes together on subjet_id and hadm_id<br>df=df_nts.merge(df_icu, on=[&#39;subject_id&#39;,&#39;hadm_id&#39;], how=&#39;inner&#39;)</pre><pre># check the shape of the merged dataframe<br>print(f&#39;Shape of the merged dataframe: {df.shape}.&#39;)</pre><h3>3. Natural Language Processing based Machine Learning Pipelines: imbalanced data set</h3><h4>3.1 Prepare train-test data sets</h4><p>For natural language processing based machine learning pipelines, all patient information including age, gender, admission_type, admission_location, insurance, ethnicity, diagnosis and physicians or nurses’ notes are combined together as features to go through NLP. The target for the prediction is whether patient dies or not as specified by expire_flag, where 0 meaning survived, 1 meaning died.</p><pre># split the data into training and test sets<br># join the columns together as a single string<br>X = df[&#39;age&#39;].astype(str) + &#39; &#39; + df[&#39;gender&#39;] + &#39; &#39; + df[&#39;admission_type&#39;] + &#39; &#39; + df[&#39;admission_location&#39;] + &#39; &#39; + df[&#39;insurance&#39;] + &#39; &#39;  + df[&#39;ethnicity&#39;] + &#39; &#39; + df[&#39;diagnosis&#39;] + &#39; &#39; +  df[&#39;text&#39;]</pre><pre># target is the death in hospital within 30 days<br>y = df[&#39;expire_flag&#39;]</pre><pre># split the dataset<br>X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)</pre><pre># print the shape<br>print(f&#39;X_train shape: {X_train.shape}, X_test shape: {X_test.shape}, y_train shape: {y_train.shape}, y_test shape: {y_test.shape}.&#39;)</pre><h4>3.2 Define an NLP tokenize function</h4><p>This is a simple model based on the common NLTK workflow. There is potential room for improvement and optimization.</p><pre># define a function to interpret the text, splitting to tokens</pre><pre>def tokenize(text):<br>    <br>    # extrac text based on the pattern<br>    text = re.sub(r&quot;[^a-zA-Z0-9]&quot;, &quot; &quot;, text)<br>    <br>    # get tokens and remove stopwords<br>    tokens = word_tokenize(text)<br>    <br>    tokens = [w for w in tokens if w not in stopwords.words(&quot;english&quot;)]<br>    <br>    lemmatizer = WordNetLemmatizer()</pre><pre>clean_tokens = []<br>    <br>    for tok in tokens:<br>        clean_tok = lemmatizer.lemmatize(tok).lower().strip()<br>        clean_tokens.append(clean_tok)</pre><pre>return clean_tokens</pre><h4>3.3 Build a logistic regression pipeline</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*Sbyx5qzmqy6DyoX77gnrwA.png" /><figcaption>Logistic regression pipeline</figcaption></figure><h4>3.4 Low classification metrics due to imbalanced data set</h4><p>From the results shown above, we can see that the metrics is pretty good for patients survived but quite bad for patients died. This is due to the imbalanced data set. Survived patients account for more than 75% of the data set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*js7f_vQijMxlNfmhGoR6Dw.png" /><figcaption>imbalanced data set</figcaption></figure><p>There are different ways to handle imbalanced data, but here we use a simple under-sampling technique to randomly select the same amount of patients from survived group to match the died group, as we have quite substantial amount of patients in each group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*O_7ZOy6X63Zc6it6_tHLJw.png" /><figcaption>balanced data set</figcaption></figure><h3>4. <strong>Exploratory Data Analysis: balanced data set</strong></h3><h4>4.1 Age distributions for patients survived or died within 30 days after balancing</h4><p>I was wondering if there is any difference in age between the two different groups. Is it possible that older people have lower chance of survival? This is indeed the case as show below. The average age of patients died is significantly higher than patients survived (more than 10 years older). It makes sense as older people have weaker health condition and harder to recover from serious diseases.</p><h4>Statistical Analysis</h4><p>Box plot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*jG0h6UQGhDC3tmkBgsbgew.png" /><figcaption>box plot for age</figcaption></figure><p>Histogram of age distribution for patients died versus survived</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*YPno0r0vLQ1x6qADjqwxug.png" /><figcaption>histogram</figcaption></figure><p>Empirical cumulative distribution function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*8iR8dz49x2_9PG6IekoKFA.png" /><figcaption>Empirical cumulative distribution function</figcaption></figure><h4>Bootstrap &amp; null hypothesis: no difference in average age</h4><p>Shift the data for patients survived and patients died so that the two groups have the same average age. The null hypothesis is that they have the same average age.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*hnw8IFRDLC7vAQMwVjUr7w.png" /><figcaption>shifted age</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*SE9JqCZVpZJlJ9SxYt3_Xw.png" /><figcaption>Null hypothesis</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v7i9eC8m_WdXCt5ijRFVHA.png" /><figcaption>p-value</figcaption></figure><p>As p value is zero, this means that the probability of observing this actual age difference is zero if the average ages of the two groups (patients died and patients survived) are the same.</p><p>As a consequnce, this null hypothesis is rejected. In other words, the average ages of patients survived and patients died are not equal.</p><h4>4.2 Insurance distributions for patients all, survived or died within 30 days after balancing</h4><p>Then, what about insurance? Based on the graph below, significantly higher portion of patients died had Medicare insurance, in comparison to private insurance for patients survived. It is possible that as patients who died are significantly older, they are retired and carry medicare insurance. While younger patients are still in the workforce and have private insurance. I hope hospital doesn’t treat patients differently based on the financial background as low-income families tend to have medicare insurance. On the other hand, high-income families may have more nutrition support and higher life quality which help to reduce the mortality rate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*FJUak_SqMtDBEBmLzQtn2A.png" /><figcaption>insurance situation</figcaption></figure><h4>4.3 Gender distributions for patients all, survived or died within 30 days after balancing</h4><p>We have seen a lot of high-age (over 100 years old) female around the world. Does female live longer? Does male tend to have lower survival rate? Based on this data, there is no clear evidence to support that. In contrast, female patients have slightly lower survival rate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*Z4mu11PYAODE7H4dWerCDg.png" /><figcaption>gender situation</figcaption></figure><h4>Statistical Analysis for gender difference</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*srq-sbtTB0cjdtBYqFjb7Q.png" /><figcaption>death rate for male versus female</figcaption></figure><p>From this figure above, the death rate for female is higher than that for male. Is it statistically significant? Let’s do some bootstrapping and find the 95% confidence interval.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*UHm3_O2rbcCYmoNs1r51zg.png" /><figcaption>death rate difference between male and female</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2R8lolcAkj0TdD2wUn_flQ.png" /></figure><p>This means that the probability of observing death rate difference at least or larger than the actual observed difference is 49.54%. This death difference is real.</p><h4>4.4 Top 10 diagnoses for different patient groups</h4><p>What are the top reasons for patients to go to ICU and die? In this data set, the top 10 reasons for going to ICU are: pneumonia, sepsis, intracranial hemorrhage, coronary artery disease, congestive heart failure, chest pain, altered mental status, gastrointestinal bleed, subarachnoid hemorrhage, and abdominal pain. Five out of these have less than 50% survival rate within 30 days, with the least one being sepsis with less than 30% patients survived. This is a piece of useful information for self-protection or taking care of the family. If you or someone in your family has these health issues, do not overlook!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u89g45Yjh0iDRUNJ-A7Z4A.png" /><figcaption>Top 10 list</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*10k3SgwcAH3eHnZ-GrX7Tw.png" /><figcaption>most vulnerable diagnoses</figcaption></figure><h3>5. Natural Language Processing based Machine Learning Pipelines: balanced data sets</h3><p>In this project, I am trying to predict the mortality within 30 days using various classification algorithms, including logistic regression, k-nearest neighbors, decision trees, random forest, adaboost and xgboost. Prediction accuracy is compared against each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*rZLME2pQZiBjV3AN51YqXQ.png" /><figcaption>classification algorithms used in this project</figcaption></figure><p>These follow the same machine learning pipeline starting from nltk’s tokenization, followed by sklearn’s CountVectorizer and TfidfTransformer feature extraction, and then the classification algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*pLiXEpqc6nSnsJUTKraNCg.png" /><figcaption>a typical machine learning pipeline</figcaption></figure><p>Here are the results. Different algorithms have quite different performance in this project, with logistic regression and support vector machine being the winning algorithms in terms of accuracy score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*bEzBpGWqNf6FVWWMSUmD4w.png" /><figcaption>machine learning algorithms</figcaption></figure><p>Accuracy, precision, recall and f1-score are all compared for these different algorithms. Precision refers to the percentage of reported true positive over reported positive (true positive + false positive). Recall, also referred as sensitivity, is the percentage of reported true positive over actual positive (true positive + false negative).</p><figure><img alt="What&#39;s the deal with Accuracy, Precision, Recall and F1?" src="https://cdn-images-1.medium.com/proxy/1*Ub0nZTXYT8MxLzrz0P7jPA.png" /><figcaption><a href="https://towardsdatascience.com/whats-the-deal-with-accuracy-precision-recall-and-f1-f5d8b4db1021">https://towardsdatascience.com/whats-the-deal-with-accuracy-precision-recall-and-f1-f5d8b4db1021</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/0*1HA5JG0Sd_jfbmLd.jpeg" /><figcaption><a href="https://towardsdatascience.com/accuracy-precision-recall-or-f1-331fb37c5cb9">confusion matrix</a></figcaption></figure><p>Clearly, support vector machine and logistic regression are the top performers in all different metrics. More importantly, the metrics for patients died improved significantly after balancing the data with under-sampling. The scores are comparable for both survived patients and died patients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A44vwJwJI1abM3qQNNeaKw.png" /><figcaption>classification report using various algorithms: balanced data sets</figcaption></figure><h3>6. Model Evaluation &amp; Optimization</h3><p>Models can be improved with hyperparameter optimization to find the optimal parameters. This is commonly done with GridSearch and cross-validation in sklearn. This process can take a lot of time depending on the number of parameters and the size of the data set, and of course the power of the computer.</p><p>In this project, a lenovo desktop with Intel(R) Xeon(R) CPU Et-1630 v4 @ 3.70 GHz with 8 concurrent workers was used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*a7pcCdFWeVJnEp18uo3CxQ.png" /><figcaption>lenovo desktop used for this project</figcaption></figure><h4>a. NLP using spaCy</h4><p>A different NLP pipleline was tried using the spaCy-en_core_sci_lg library. The performance is not as good as the original one using NLTK.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ULu-lI36WnG_B5xj8SYzhQ.png" /><figcaption>spaCy</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*nQt80PaWI7wFSfNMl09Spw.png" /><figcaption>classification report for logistic regression with spaCy library</figcaption></figure><h4>b. Hyper-parameter optimization for logistic regression</h4><p>Parameters were searched for c and penalty and narrowed down to a few values after a couple of trials. The optimized parameter for c is 1 and penalty is l2.</p><pre># optimize a logistic regression pipeline<br>logreg=LogisticRegression()</pre><pre>pipeline = Pipeline([(&quot;vect&quot;,CountVectorizer(tokenizer=tokenize)),<br>                     (&quot;tfidf&quot;,TfidfTransformer()),<br>                     (&quot;clf&quot;, logreg)])</pre><pre>parameters = {<br>    &quot;clf__penalty&quot;: [&#39;l1&#39;,&#39;l2&#39;],<br>    &quot;clf__C&quot; : [0.1,1,10]    <br>    }</pre><pre>cv = GridSearchCV(pipeline, param_grid=parameters, n_jobs=-1, cv=5, verbose=2)</pre><pre>time_begin = time.time()</pre><pre>cv.fit(X_train, y_train)</pre><pre>print(f&#39;It took {round((time.time() - time_begin)/60,2)} minutes.&#39;)</pre><pre>cv.best_params_</pre><p>Best parameters:</p><pre>{&#39;clf__C&#39;: 1, &#39;clf__penalty&#39;: &#39;l2&#39;}</pre><p>Comparing the classification metrics between and after the optimization, there is no significant improvement for this case. The default parameters are already optimal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*vK81c1stSk67Txl3OImDsg.png" /><figcaption>classification report after hyperparameter tuning: logistic regression</figcaption></figure><p>We also tried to optimize the second performing algorithm, XGBoost, with four parameters. This is going to take overnight calculation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S2YSxhJLYP6z3Y2aA2IvyQ.png" /></figure><p>It’s completed finally after near 9 hours. But the metrics is still not as good as that from logistic regression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*aj8vvZ7_t_jmdnC9DfaVNw.png" /><figcaption>optimized XGBoost</figcaption></figure><h3>7. Conclusion &amp; Perspective</h3><p>This project demonstrated that it is possible to identify high risky patients and predict mortality with pretty good accuracy, with Support Vector Machine and Logistic Regression being the best classification algorithms. Further improvement is possible to utilize biomedical natural language processing packages such as SciSpaCy, to understand medical notes more accurately and extract relevant information. Other technique such as topic modelling and Latent Dirichlet Allocation (LDA) are to be exploited as well.</p><p>For the imbalanced data, other techniques such as over-sampling and synthetic minority oversampling technique (SMOTE) will also be exploited in the follow-up work.</p><p>In this project, we haven’t used any lab results and radiology reports. More work needs to be done to incorporate these data to extract meaningful information. Advanced imaging processing techniques and deep learning algorithms might be helpful as well.</p><p>Healthcare is directly related with everyone. No matter how healthy you are today, you may interact with the healthcare system in one way or another as you get older or unexpected things can happen to you or your family. With growing digitized healthcare records and data and evolving natural language processing techniques and machine learning algorithms, data science can have a tremendous impact on the human life.</p><p>We wish the world without diseases!</p><h3>8. Graduation certificate</h3><p>It has been a great journey to become a data scientist! Thank you Udacity, thank you my mentor, <a href="https://www.linkedin.com/in/ACoAACcIgPQBiiN7wr2DwQ3xaYYuYTAlfDG085Y/">Mrudula Vulpala</a>! Thank you all friends and colleagues for comments and suggestions!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*80RfFOcQTBvf4bKo3CfMdA.png" /><figcaption>Data Scientist_Ronghui Zhou</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0d8fcaeecde" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How You Can Avoid Car Accident in 2020]]></title>
            <link>https://ronghui-zhou.medium.com/how-you-can-avoid-car-accident-in-2020-c9626c9b6f68?source=rss-cd5a61234de5------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9626c9b6f68</guid>
            <category><![CDATA[drive-safe]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[roadtrip-tips]]></category>
            <category><![CDATA[car-accidents]]></category>
            <dc:creator><![CDATA[Ronghui Zhou, Ph.D.]]></dc:creator>
            <pubDate>Mon, 23 Dec 2019 12:30:59 GMT</pubDate>
            <atom:updated>2019-12-23T21:35:00.885Z</atom:updated>
            <content:encoded><![CDATA[<h4>Insights from exploratory data analysis and applying machine learning algorithms to predict accident severity</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/0*rHE7Y9J2_H14nnOH.jpg" /><figcaption><a href="https://www.talentedladiesclub.com/articles/drive-safely-five-tips-to-keep-your-kids-entertained-so-you-can-focus-on-the-road/">https://www.talentedladiesclub.com/articles/drive-safely-five-tips-to-keep-your-kids-entertained-so-you-can-focus-on-the-road/</a></figcaption></figure><p>Part I. Exploratory Data Analysis of Car Accidents in the States of <a href="https://github.com/RonghuiZhou/us-accidents/blob/master/Exploratory%20Data%20Analysis%20for%20the%20NJ%2C%20PA%20%26%20NY%20data.ipynb">NJ, PA &amp; NY</a> OR <a href="https://github.com/RonghuiZhou/us-accidents/blob/master/Exploratory%20Data%20Analysis%20for%20the%20DE%2C%20FL%20%26%20CA%20data.ipynb">DE, FL &amp; CA</a>;</p><p>Part II. Applying Machine Learning Algorithms to Predict Accident Severity: PA-<a href="https://github.com/RonghuiZhou/us-accidents/blob/master/Machine%20Learning%20for%20US%20Accidents_PA_Mont_RZhou.ipynb">Montgomery County</a> OR the state of <a href="https://github.com/RonghuiZhou/us-accidents/blob/master/Machine%20Learning%20for%20US%20Accidents_NJ_RZhou.ipynb">NJ</a>, <a href="https://github.com/RonghuiZhou/us-accidents/blob/master/Machine%20Learning%20for%20US%20Accidents_PA_RZhou.ipynb">PA</a>, <a href="https://github.com/RonghuiZhou/us-accidents/blob/master/Machine%20Learning%20for%20US%20Accidents_NY_RZhou.ipynb">NY</a>, <a href="https://github.com/RonghuiZhou/us-accidents/blob/master/Machine%20Learning%20for%20US%20Accidents_DE_RZhou.ipynb">DE</a>, <a href="https://github.com/RonghuiZhou/us-accidents/blob/master/Machine%20Learning%20for%20US%20Accidents_FL_RZhou.ipynb">FL</a> OR <a href="https://github.com/RonghuiZhou/us-accidents/blob/master/Machine%20Learning%20for%20US%20Accidents_CA_RZhou.ipynb">CA</a></p><p><strong>Motivation: </strong>As a nation on wheels, driving around is part of the life. Imagine you just dressed yourself up and on the way to your first date, what’s the last thing you want to happen? Or you just took off a family road trip to a long-dreamed national park, what’s absolutely the thing you want to avoid? The answer is quite obvious: car accident (Figure 1)!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eZUngp0Oy68EQjVgLZdmcA.png" /><figcaption><strong>Fig 1.</strong> Accidents in the United States and selected states</figcaption></figure><p>The good thing is that, although it varies state by state, most accidents are light accidents with severity level 2, with the most severe one (level 4) the least (Figure 2). It takes 30–50 minutes to clear a level 2 accident but 6 hours for a level 4 accident (Figure 3). The time impact is not the mere thing, the emotional impact can last much longer, or even ruin your whole day or entire vacation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oc_1oie-fTN5z1fAtMTLJg.png" /><figcaption><strong>Fig 2. </strong>Accident severity for the states of NJ, PA, NY, DE, FL, &amp; CA</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*qWttUAtCU5si0d0oTGlsUQ.png" /><figcaption><strong>Fig 3. </strong>How long does it take to clear the accident?</figcaption></figure><p>To keep the good mood and happiness, it’s highly desirable to take actions to avoid car accidents if possible. Are there any tricks or tips? Sure thing!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*azT0jeIDKkOqZY0g" /><figcaption><a href="https://unsplash.com/photos/poG5Tq5Hw7M">https://unsplash.com/photos/poG5Tq5Hw7M</a></figcaption></figure><p>By analyzing accident records data set collected for the past three years, insights on how to drive safely and keep accident free are highlighted here. This should provide a reference guide you may use to drive safely and avoid car accident in 2020!</p><p><strong>Exploratory Data Analysis: (WWW) When</strong>, <strong>Where</strong>, &amp; <strong>Weather</strong></p><p>To avoid car accidents, it is meaningful to see when, where and under what weather conditions did most accidents happen.</p><ul><li><strong>When</strong></li></ul><p>According to the results, most accidents happened during the daytime (Figure 4). There are more accidents on weekdays than weekends (Figure 5). On weekdays, rush hours are most dangerous times while on weekends, early afternoon is more dangerous than other time (Figure 6). Based on this information, you may plan your travel better if possible, or pay extra attention while driving during highly risky time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ytu3ZytXlNfvb_lwUHhevw.png" /><figcaption><strong>Fig 4.</strong> Percentage of accidents during daytime versus nighttime</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*ttTggot5TjxHP06dxKIXiw.png" /><figcaption><strong>Fig 5. </strong>Average number of accidents per day for each weekday/weekend</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kJT5gjpDTflpOkdEuqNj5Q.png" /><figcaption><strong>Fig 6. </strong>Average number of accidents per severity level per day for each hour on weekday/weekend</figcaption></figure><ul><li><strong>Where</strong></li></ul><p>While most accidents happened on the right side of the street, still quite a significant portion (~ 30%) of accidents occurred on the left side, especially in the states of PA and DE (Figure 7). While New Castle county in DE, Montgomery county in PA, and Los Angles county in CA have the most accidents (Figure 8), Wilmington and Los Angles are the most dangerous cities in DE and CA respectively (Figure 9).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*3ITEPJdd-DdY40mvoO3niA.png" /><figcaption><strong>Fig 7. </strong>Street sides for accidents</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*81pcMYJbRJltbWjpNhPm5w.png" /><figcaption><strong>Fig 8. </strong>Most dangerous counties</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*sLKQ9-QkzggYeNcUGc7HEg.png" /><figcaption><strong>Fig 9. </strong>Most dangerous cities</figcaption></figure><p>Take a closer look at each accident, most accidents happened at traffic signals, followed by Junctions and Crossings (Figure 10). In each of theses locations, most accidents are still light accidents with severity level 2 (Figure 11).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*i0PdLPuJeVaNQ2LnacwFAw.png" /><figcaption><strong>Fig 10.</strong> Where did most accidents occur</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ntwG1Q8g5VmmrrBX7UvHCA.png" /><figcaption><strong>Fig. 11</strong> Accident severity levels for each location</figcaption></figure><p>Based on this information, you know where you need to avoid if possible, otherwise, stop texting or messaging but rather focusing on the road!</p><ul><li><strong>Weather</strong></li></ul><p>Based on this data set, most accidents occurred under clear weather condition. It may be due to the fact that percentage of clear days being the highest, or drivers tend to pay less attention to the road under good weather conditions (Figure 12). While under bad weather conditions, people may be more cautious while driving, thus less accidents. While for each weather condition, most accidents have severity level 2 (Figure 13), for each severity category, most accidents occurred under clear weather condition (Figure 14).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cKbTykiXibqf-Oo5T9_gRw.png" /><figcaption><strong>Fig 12. </strong>Percentage of accidents under various weather conditions</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k4uf5YpOCjMBq4Of4rZVOw.png" /><figcaption><strong>Fig 13. </strong>Accident severity under top three weather conditions</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CCD9NOKWiqMxpE75F3ZsSg.png" /><figcaption><strong>Fig 14. </strong>Weather conditions for accidents with each severity</figcaption></figure><p>Now you know you should not relax and diverge your attention to other unrelated affairs while driving under the sun.</p><p>Accidents are everywhere, we should do everything we can to avoid it. It is just for your own, but also for your families and loved ones. Especially for those deadly accidents, there is no regret.</p><p>Nevertheless, if you already did your best but still cannot avoid it. Can we try to reduce the severity, thus impact, of the accident? Can we predict the severity with machine learning algorithms?</p><p><strong>Severity Prediction: </strong>Applying Machine Learning Algorithms to Predict the Severity of Car Accidents</p><ul><li><strong>Feature Engineering</strong></li></ul><p>Although there is more information available, it is desirable to select a few relevant features which have higher impact on accident and its severity. This can reduce the demand on computation and improve the accuracy of predictions. Mainly the time, location and weather conditions were selected.</p><pre>feature_lst=[&#39;Source&#39;,&#39;TMC&#39;,&#39;Severity&#39;,&#39;Start_Lng&#39;,&#39;Start_Lat&#39;,&#39;Distance(mi)&#39;,&#39;Side&#39;,&#39;City&#39;,&#39;County&#39;,&#39;State&#39;,&#39;Timezone&#39;,&#39;Temperature(F)&#39;,&#39;Humidity(%)&#39;,&#39;Pressure(in)&#39;, &#39;Visibility(mi)&#39;, &#39;Wind_Direction&#39;,&#39;Weather_Condition&#39;,&#39;Amenity&#39;,&#39;Bump&#39;,&#39;Crossing&#39;,&#39;Give_Way&#39;,&#39;Junction&#39;,&#39;No_Exit&#39;,&#39;Railway&#39;,&#39;Roundabout&#39;,&#39;Station&#39;,&#39;Stop&#39;,&#39;Traffic_Calming&#39;,&#39;Traffic_Signal&#39;,&#39;Turning_Loop&#39;,&#39;Sunrise_Sunset&#39;,&#39;Hour&#39;,&#39;Weekday&#39;, &#39;Time_Duration(min)&#39;]</pre><p>Due to the limit of personal computer, it is impossible to use the whole dataset. Predictions were made for individual state or county.</p><ul><li><strong>Data Preprocessing</strong></li></ul><p>Besides no missing value is allowed, most machine learning algorithms work only with numerical data. For that, records with missing values were dropped from the calculation. Some outliers, especially with extremely short or long time to clear the accident, were processed and replaced with median values. As it doesn’t make sense to take 0 minute or many years to clear an accident.</p><ul><li><strong>Predicting Accident Severity with various Machine Learning Algorithms</strong></li></ul><p>In this study, four classification machine learning algorithms were evaluated. These are Logistic Regression, K-Nearest Neighbors (KNN), Decision Trees and Random Forest. As you can see in Figure 15, Random Forest algorithm is always the winner and KNN is the last on the list in terms of accuracy. The accuracy is quite high for Montgomery county in PA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lyU0euyCNfYXpVrgMvD8Ng.png" /><figcaption><strong>Fig 15. </strong>Accuracy of predicting accident severity with various machine learning algorithms for each state</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*F_ecVnnl5cDBzCPHsElQlw.png" /><figcaption><strong>Fig 16. </strong>Accuracy of predicting accident severity with various machine learning algorithms for Montgomery county in PA</figcaption></figure><ul><li><strong>Most important features</strong></li></ul><p>Shown below are the top 10 features affecting the accuracy of predicting accident severity for the data from Montgomery county in PA. Prediction accuracy can be further improved by removing less important or irrelevant features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*l_cayCem-6WdoNejBdrMIA.png" /><figcaption><strong>Fig 17. </strong>Top 10 features affecting the prediction accuracy for Random Forest algorithm for Montgomery county in PA</figcaption></figure><h3><strong>Summary</strong></h3><p>This study indicates that there are patterns of when, where and under what weather conditions did most accidents occurred. The severity of each accident can be predicted quite accurately with various classification machine learning algorithms.</p><p>Although many accidents are just merely out of luck. For instance, I was once waiting for the red signal to turn green and the car in front of me started to back up and bumped into mine. Still it is desirable to understand what are possible to control and reduce in terms of chance of accident or its severity.</p><p>Now you know all this information, will you still be distracted at rush hours, at signals or driving under the sun? Always keep your families and loved ones in mind and practice caution!</p><p>May the world be accident free in 2020!</p><h3>Note</h3><p>This dataset is obtained from <a href="https://www.kaggle.com/sobhanmoosavi/us-accidents">kaggle</a>. All codes are available on <a href="https://github.com/RonghuiZhou/us-accidents">GitHub</a>.</p><h3>Acknowledgements</h3><ul><li>Moosavi, Sobhan, Mohammad Hossein Samavatian, Srinivasan Parthasarathy, and Rajiv Ramnath. “<a href="https://arxiv.org/abs/1906.05409">A Countrywide Traffic Accident Dataset</a>.”, 2019.</li><li>Moosavi, Sobhan, Mohammad Hossein Samavatian, Srinivasan Parthasarathy, Radu Teodorescu, and Rajiv Ramnath. <a href="https://arxiv.org/abs/1909.09638">“Accident Risk Prediction based on Heterogeneous Sparse Data: New Dataset and Insights.”</a> In proceedings of the 27th ACM SIGSPATIAL International Conference on Advances in Geographic Information Systems, ACM, 2019.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9626c9b6f68" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>