<?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 Kinder Sham on Medium]]></title>
        <description><![CDATA[Stories by Kinder Sham on Medium]]></description>
        <link>https://medium.com/@kindersham?source=rss-2ed1b024159d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*N5Lw6LLkXoTYUDOl</url>
            <title>Stories by Kinder Sham on Medium</title>
            <link>https://medium.com/@kindersham?source=rss-2ed1b024159d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 04:29:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kindersham/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[Detecting Parkinson’s Disease with Machine Learning]]></title>
            <link>https://medium.com/analytics-vidhya/detecting-parkinsons-disease-with-machine-learning-44c17208afce?source=rss-2ed1b024159d------2</link>
            <guid isPermaLink="false">https://medium.com/p/44c17208afce</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[svm]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[decision-tree]]></category>
            <dc:creator><![CDATA[Kinder Sham]]></dc:creator>
            <pubDate>Wed, 02 Sep 2020 07:22:16 GMT</pubDate>
            <atom:updated>2020-09-02T12:55:24.038Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Keep On Moving</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gi3KkVDg_6-A557E" /><figcaption>Photo by <a href="https://unsplash.com/@brunus?utm_source=medium&amp;utm_medium=referral">Bruno Martins</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this article, I will build a model that can accurately detect the presence of Parkinson’s disease in humans. Before starting, we will walk through the data science life cycle to understand what should happen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/0*xzzLq1sN70fSIUdu.png" /><figcaption>Photo by Srinivas Rao on Quora</figcaption></figure><p><strong>Steps of solving Business Problem with Data Science Life Cycle:</strong><br>1. Business Understand<br>2. Data Collection<br>3. Data Preparation<br>4. Exploratory Data Analysis<br>5. Modelling<br>6. Model Evaluation<br>7. Model Deployment</p><h3>#1 ~ Business Understanding</h3><p>Any project, regardless of its size, requires an understanding of the business, which is the basis for effectively solving business problems.</p><p><strong>What is problem I trying to solve?</strong></p><p>At this stage, I need to define problems, project goals and solutions from a business perspective. This is the first step in solving problems with data science methods. In this article, I need to accurately detect the presence of Parkinson’s disease based on the voice measurement data set.</p><p><strong>What is Parkinson’s Disease?</strong></p><p>Parkinson’s disease is an age-related neurodegenerative disease of the central nervous system. It is the second most common disease after Alzheimer’s disease that affects neurons in the brain that produce dopamine.​​​ It affects movement and induces tremor and stiffness. An estimated 70–10 million people worldwide suffer from Parkinson’s disease.</p><p>Therefore, it is a Supervisor Learning ~ I will use Classification method.</p><h3>#2 ~ Data Collection</h3><p>Data is the most critical part of the entire machine learning. So I need to consider the following:</p><ul><li>Do I have the data?</li><li>Where does the data come from?</li><li>Do we trust the data source?</li><li>Do I have the domain knowledge?</li></ul><p>The data is coming from the UCI Donald Bren School of Information &amp; Computer Sciences, you can download it <a href="https://archive.ics.uci.edu/ml/machine-learning-databases/parkinsons/">here</a>. The dataset has 24 columns and 195 records.</p><h3>#3 ~ Data Preparation &amp; #4 ~ Exploratory Data Analysis</h3><p>Now we will make necessary imports and try to load the Parkinson’s disease dataset to jupyter notebook.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/766b369427c2d76093b5a1a25020d197/href">https://medium.com/media/766b369427c2d76093b5a1a25020d197/href</a></iframe><p>Now, let’s take a look at the dataset. The dataset contain 195 rows and 24 columns. The dependent variable is <strong>status </strong>and MDVP:Fo(Hz) to PPE are independent variables. In the picture below, we can see that there are no missing values ​​in dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4inX2c44xrfJ0JjYqjmsjQ.png" /></figure><p>We can see that all our numeric variables are listed at the top, and we have values ​​such as count, mean, standard deviation, minimum, maximum, 25% and 50%, and 75%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DnebAwY-M-x7K_XjAy17zA.png" /></figure><h3>#5 ~ Modelling</h3><p>It is important to standardization the training data and test data because most machine learning models converge much faster if the proportions of the elements are the same. Doing standardization will centralize the feature’s mean between 0 to 1. The data will be distributed on normal distribution. To calculate the mean and standard deviation of those feature and apply the above formula to each observation/value, it will use sklearn’s StandardScaler:</p><p>The last thing to do before training our models is to split the dataset. I split this data randomly with 80/20 for training versus test examples to training set and testing set. We need to do this so we could estimate the predictive result of our model by predicting the testing set data (unseen data).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d8c76455d6145877ae688daf9bad08d/href">https://medium.com/media/5d8c76455d6145877ae688daf9bad08d/href</a></iframe><p>LogisticRegression</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/153f467556323586b5ce5c6c270089a0/href">https://medium.com/media/153f467556323586b5ce5c6c270089a0/href</a></iframe><p>DecisionTreeClassifier</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de17c84b745a6f4f04c7dad445f89802/href">https://medium.com/media/de17c84b745a6f4f04c7dad445f89802/href</a></iframe><p>SVC</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d36910b5d9e66cd96be37be4955a5ffd/href">https://medium.com/media/d36910b5d9e66cd96be37be4955a5ffd/href</a></iframe><h3>#6 ~ Model Evaluation</h3><p>In this step, we will evaluate the performance and accuracy of the machine learning model. Based on the prediction, we can see that the model can accurately predict from Logistic Regression is 0.79, Decision Tree is 0.87 and SVC is 0.92.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zPs0CLbta9d_8hCgGelKrw.png" /></figure><h3>#7 ~ Model Deployment</h3><p>This is a relatively simple project, usually we also need iteration and function selection or compare with other algorithm. By collecting the results of the implementation model, you also need to receive feedback about the performance of the model and its impact on the implementation environment. By analyzing this information, data scientists can improve the model and improve its accuracy, thereby improving its practicality. Once a satisfactory model is developed, it will be implemented in the production environment.</p><p>Thanks for reading! If you enjoyed the post, please appreciate your support by applauding via the clap (👏🏼) button below or by sharing this article so others can find it.</p><p>I hope you have a basic understanding of the Data Science Life Cycle. How to think at each stage to help guide you through the methodology of a successful data science project. At the end, I hope that you can learn the how to use the logistic regression techniques. You can also find the full project on the <a href="https://github.com/kindersham/100DaysDS/tree/master/Detecting_Parkinson&#39;s_Disease">GitHub</a> repository.</p><p>[1]: <em>‘Exploiting Nonlinear Recurrence and Fractal Scaling Properties for Voice Disorder Detection’, <br>Little MA, McSharry PE, Roberts SJ, Costello DAE, Moroz IM. <br>BioMedical Engineering OnLine 2007, 6:23 (26 June 2007)</em></p><p>[2]: <em>Max A. Little, Patrick E. McSharry, Eric J. Hunter, Lorraine O. Ramig (2008), <br>‘Suitability of dysphonia measurements for telemonitoring of Parkinson’s disease’, <br>IEEE Transactions on Biomedical Engineering (to appear).</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44c17208afce" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/detecting-parkinsons-disease-with-machine-learning-44c17208afce">Detecting Parkinson’s Disease with Machine Learning</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linear Regression in Python with Scikit-Learn]]></title>
            <link>https://medium.com/analytics-vidhya/linear-regression-in-python-with-scikit-learn-e1bb8a059cd2?source=rss-2ed1b024159d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1bb8a059cd2</guid>
            <category><![CDATA[simple-linear-regression]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Kinder Sham]]></dc:creator>
            <pubDate>Mon, 15 Jun 2020 15:10:38 GMT</pubDate>
            <atom:updated>2020-06-16T01:00:15.000Z</atom:updated>
            <content:encoded><![CDATA[<h4>Predict the housing price by Linear Regression</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x_YCnjw2XvYxfXUO" /><figcaption>Photo by <a href="https://unsplash.com/@xavi_cabrera?utm_source=medium&amp;utm_medium=referral">Xavi Cabrera</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>In supervised machine learning, there are two algorithms: regression algorithm and classification algorithm. For example, predicting house prices is a regression problem, and predicting whether houses can be sold is a classification problem.</p><blockquote>The term “linearity” in algebra refers to a linear relationship between two or more variables.</blockquote><p>In the simple linear regression discussed in this article, if you draw this relationship in a two-dimensional space, you will get a straight line.</p><p>Let’s consider a scenario where we want to determine the linear relationship between the house square feet and the house selling price. when we given the square feet of a house, can we estimate how much money can be sold?</p><p>We know that the formula of a regression line is basically: <strong><em>y = mx + b</em></strong></p><p>where <strong><em>y</em></strong> is the predicted target label, <strong><em>m</em></strong> is the slope of the line, and <strong><em>b</em></strong> is the <strong><em>y</em></strong> intercept.</p><p>If we plot the independent variable (Square Feet) on the x-axis and dependent variable (Sale Price) on the y-axis, linear regression gives us a straight line that best fits the data points, as shown in the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*a6wu4TSq8Hp1gzx2n5BgLA.png" /></figure><h3>Linear Regression in Python with Scikit-Learn</h3><p>In this section, we will learn how to use the Python Scikit-Learn library for machine learning to implement regression functions. We will start with a simple linear regression involving two variables. In this regression task we will predict the Sales Price based upon the Square Feet of the house. This is a simple linear regression task as it involves just two variables.</p><h3>Code</h3><ol><li><strong>Importing Libraries</strong></li></ol><p>To import necessary libraries for this task, execute the following import statements:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yk3FS3U7gxljzGbtwCfzGg.png" /></figure><p><strong>2. Import the dataset</strong></p><p>The following command imports the CSV dataset via pandas:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e78Zv8UeZ5B7NqMmpIog-g.png" /></figure><p><strong>3. Understand the data</strong></p><p>Now let’s explore the dataset. Execute the following script: df.shape.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KmcPCvqS07SjktFdTQ2WOw.png" /></figure><p>After that, you should see the following output. The dataset contain 1,460 rows and 2 columns. Let’s take a look at what our dataset actually looks like. enter the df.head()which will retrieves the first 5 records from our dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_okERVeGjRAE9ymDqYs6gA.png" /></figure><p>To see statistical details of the dataset, we can use df.describe():</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F4jMKpKrQ6c6iHMZf62LUQ.png" /></figure><p>Finally, we can draw data points on the two-dimensional graph to focus on the dataset and see if we can manually find any relationship between the data. We use df.plot() function of the pandas dataframe and pass it the column names for x coordinate and y coordinate, which are “SquareFeet” and “SalesPrice” respectively. We can use the below script to create the graph:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_gTk4-psYNHU-NtQ2bkffQ.png" /></figure><p>From the graph above, we can clearly see that there is a positive linear relation between the house square feet and the house sales price.</p><p><strong>4. Preparing the Data</strong></p><p>Now we have ideas about the details of data statistics. The next step is to divide the data into “attributes” and “target labels”. Attributes are independent variables, and target labels are dependent variables whose values ​​are to be predicted. In our dataset we only have two columns. We want to predict the Sales Price based upon the Square Feet of the house. Therefore our attribute set will consist of the “SquareFeet” column, and the label will be the “SalesPrice” column. To extract the attributes and labels, execute the following script:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YkMCAm-2Ffxplh-6xb-wVg.png" /></figure><p>The attributes are stored in the X variable. We specified “-1” as the range for columns since we wanted our attribute set to contain all the columns except the last one, which is “SalesPrice”. Similarly the y variable contains the labels. We specified 1 for the label column since the index for “SalesPrice” column is 1. Remember, the column indexes start with 0, with 1 being the second column.</p><p>Now that we have our attributes and labels, the next step is to split this data into training and test sets. We’ll do this by using Scikit-Learn built-in train_test_split() method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hfkHxlJmj246TiUn3z5y-g.png" /></figure><p>The above script splits 80% of the data to training set while 20% of the data to test set. The test_size variable is where we actually specify the proportion of test set.</p><p><strong>5. Modelling</strong></p><p>We have split our data into training and testing sets, and now is finally the time to train our model. Execute following script:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7tmWwQQqlkwD3AIJs2yMeA.png" /></figure><p>With Scikit-Learn it is extremely straight forward to implement linear regression models, as all you really need to do is import the LinearRegression class, instantiate it, and call the fit() method along with our training data. This is about as simple as it gets when using a machine learning library to train on your data.</p><p>In the theory section we said that linear regression model basically finds the best value for the intercept and slope, which results in a line that best fits the data. To see the value of the intercept and slop calculated by the linear regression algorithm for our dataset, execute the following script to retrieve the intercept:.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j-T3UAK9JpWcv-N2h7zbCQ.png" /></figure><p>The resulting value you see should be approximately: 13330.26. And the then execute the following script to retrieving the slope (coefficient of x):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ITHmXbON6YXDvtxrL3f7eQ.png" /></figure><p>The result should be approximately: 110.26.</p><p>This means that for every one unit of change in Square Feet, the change in the SalesPrice is about 110.26.</p><p><strong>6. Predictions</strong></p><p>Now that we have trained our algorithm, it’s time to make some predictions. To do so, we will use our test data and see how accurately our algorithm predicts the percentage score. To make pre-dictions on the test data, execute the following script:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iCy0ify_A9OeEwwXuamQQA.png" /></figure><p>The y_pred is a numpy array that contains all the predicted values for the input values in the X_test series.</p><p>To compare the actual output values for X_test with the predicted values, execute the following script and the output looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tbilY8VNq6rOUV_8ASMbxg.png" /></figure><p>Although our model is not very accurate, the predicted value is close to the actual value.</p><p><strong>7. Evaluation</strong></p><p>The final step is to evaluate the performance of the algorithm. This step is particularly important for comparing the performance of different algorithms on specific data sets. For regression algorithms, three evaluation indicators are usually used:</p><ol><li>Mean Absolute Error (MAE) is the mean of the absolute value of the errors.</li><li>Mean Squared Error (MSE) is the mean of the squared errors.</li><li>Root Mean Squared Error (RMSE) is the square root of the mean of the squared errors</li></ol><p>The Scikit-Learn library pre-built the functions that can be used to find out these values for us. Let’s find the values for these metrics using our test data. Execute the following script:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vNdzi2qOE7roKezIfpdaQg.png" /></figure><p>You can see that the value of root mean squared error is 62560.28, which is large than 10% of the mean value of the Sales Price i.e. 180921.2. This means that our algorithm is just average.</p><p>There are many factors that contribute to this inaccuracy, some of which are listed here:</p><ol><li>The features we used may not have had a high enough correlation to the values we were trying to predict.</li><li>We assume that this data has a linear relationship, but this is not the case. visual data can help you determine.</li></ol><h3>Next</h3><p>To improve the model, we need to use more independent variable and try difference model, such as SVR, Lasso and ElasticNet.</p><p>Thanks for reading! If you enjoyed the post, please appreciate your support by applauding via the clap (👏🏼) button below or by sharing this article so others can find it.</p><p>At the end, I hope that you can learn the how to use the simple linear regression techniques. You can also find the full project on the <a href="https://github.com/kindersham/100DaysDS/tree/master/Housing%20Prices%20-%20Linear%20Regression">GitHub</a> repository.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1bb8a059cd2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/linear-regression-in-python-with-scikit-learn-e1bb8a059cd2">Linear Regression in Python with Scikit-Learn</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to send email via python]]></title>
            <link>https://medium.com/analytics-vidhya/how-to-send-email-via-python-95302a7f06de?source=rss-2ed1b024159d------2</link>
            <guid isPermaLink="false">https://medium.com/p/95302a7f06de</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[business-report]]></category>
            <category><![CDATA[send-email]]></category>
            <category><![CDATA[crontab]]></category>
            <dc:creator><![CDATA[Kinder Sham]]></dc:creator>
            <pubDate>Mon, 15 Jun 2020 03:46:47 GMT</pubDate>
            <atom:updated>2020-06-15T13:59:35.656Z</atom:updated>
            <content:encoded><![CDATA[<h4>Send sales reports automatically every day</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Hw_DUXRPK0pNt-25" /><figcaption>Photo by <a href="https://unsplash.com/@muukii?utm_source=medium&amp;utm_medium=referral">Muukii</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Recently, my company has tasked me with looking into reporting solutions for our sales department. I need to send sales report to the sales manager every day. The sales report will be prepared after end of the day, and the report needs to be sent at 08:00 am. Therefore, I am trying to automate a flow using a custom scenario script written in Python.</p><h3>How to send email via python</h3><p>Python includes several modules in the standard library for working with emails and email servers. Basically we will use the built-in <strong>smtplib</strong> module, which can send email using Simple Mail Transfer Protocol (SMTP). <strong>smtplib</strong> uses RFC 821 protocol for SMTP. The examples in this tutorial will use the own SMTP server to send emails with attachments and HTML content, but the same principles apply to other email services.</p><p>To send the email, you need to make use of SMTP (Simple Mail Transfer Protocol). As mentioned earlier, Python provides libraries to handle this task you don’t need to extra installations or tricks are required. You can import the module using the following statement:</p><p>line 4–5: Import the smtplib related module. It should be included in Python by default.</p><p>line 6–8: We will deal with the MIME message type, which is able to combine HTML and plain text. In Python, it is handled by the<em> email.mime</em> module.</p><p>line 11: Attachments are still the MIME objects but we need to encode them with the base64 module.</p><p>line 13: Import the datetime module.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5858ca90436651f56e69417773c2e300/href">https://medium.com/media/5858ca90436651f56e69417773c2e300/href</a></iframe><p><strong>Let’ create the sendemail function:</strong></p><p>line 2–6: Create the MIMEMultipart message object and load it with appropriate headers for From, To, and Subject fields.</p><p>line 9: Add your message body.</p><p>line 11–24: Add your attachment.</p><p>line 29–34: Login to the mail server and send the email out.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25f54508381dc328af9d0807f50a927c/href">https://medium.com/media/25f54508381dc328af9d0807f50a927c/href</a></iframe><p>I recommend defining the email addresses and message content at the top of your script, then you can change it easily:</p><p>line 2: Define the sending date.</p><p>line 4–8: Define the sender name, sender email, sender passwd, recipient and subject.</p><p>line 10: Create a HTML messages.</p><p>line 14: call the sendemail function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d6414de55c372c81eb216cff240ebe1/href">https://medium.com/media/1d6414de55c372c81eb216cff240ebe1/href</a></iframe><p>Cheers!!! I got the email with the sales report now!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YT82GBjekgV4Wbnj-ZxJ1Q.png" /></figure><p>Now we need to configure automatic report sending.</p><p>Create a run.sh</p><pre>#!/bin/bash<br>source /home/user/.bashrc<br>python /home/user/sales_report_email.py</pre><p>Setup the cron job at linux.</p><pre>user@reportsrv$ crontab -e</pre><pre>00 8 * * * /usr/bin/bash /home/user/run.sh &gt; /home/user/logs/run_report_`date +\%Y\%m\%d`.log</pre><p>These are just basic options for sending email using Python. You can also use for…loop to send more than one recipient. For get the better results, please check the Python documentation!</p><p>Thanks for reading! If you enjoyed the post, please appreciate your support by applauding via the clap (👏🏼) button below or by sharing this article so others can find it.</p><p>In the end, I hope that you can learn how to using python to send an email. You can also find the full project on the <a href="https://github.com/kindersham/100DaysDS/tree/master/SendEmail">GitHub</a> repository.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95302a7f06de" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/how-to-send-email-via-python-95302a7f06de">How to send email via python</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Find the best customer service centre location by using K-means clustering]]></title>
            <link>https://medium.com/analytics-vidhya/find-the-best-customer-service-centre-location-by-using-k-means-clustering-fcc05eb7ab0f?source=rss-2ed1b024159d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcc05eb7ab0f</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[k-means-clustering]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[k-means]]></category>
            <category><![CDATA[insurance]]></category>
            <dc:creator><![CDATA[Kinder Sham]]></dc:creator>
            <pubDate>Sat, 13 Jun 2020 15:28:28 GMT</pubDate>
            <atom:updated>2020-06-13T16:08:24.354Z</atom:updated>
            <content:encoded><![CDATA[<h4>K-Means cluster and how it benefits to the business</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SktlMevR-wXlGo8d" /><figcaption>Photo by <a href="https://unsplash.com/@officestock?utm_source=medium&amp;utm_medium=referral">Sebastian Herrmann</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>A large Hong Kong insurance company wants to open a series of customer service centres. But how to choose the location has become the biggest problem. After i finish a machine learning course, I decided to use data to solve problems and use unsupervised learning k-means clustering to find the location of customer service centres.</p><p><strong>What is k-means clustering?</strong></p><p>K-means clustering is an unsupervised algorithm that find a rule to group similar data together. It can be used to organize large amounts of unlabelled data to generate competitive insights about your business. There are many use cases that can help you implement this practice in your business, such as the following video, the pizza parlors wants to open branch in the city. How to find the best location to provide services to customers?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FQXOkPvFM6NU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DQXOkPvFM6NU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FQXOkPvFM6NU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8bc43bdda0fd100559fd847d2376f71/href">https://medium.com/media/d8bc43bdda0fd100559fd847d2376f71/href</a></iframe><h3>About the Data</h3><p>The data we will use is come with a large insurance company. The data lists the customer ID, latitude and longitude of the customer address. Let’s import the data using pandas and check the first 5 entries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-gEZgaaY5b-Zm6AAotjYow.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xLPXRg7PwzSK-Hkp5KlidA.png" /></figure><h3>Data Preparation</h3><p>Now, we will check whether the values ​​of these variables are what we want. Missing values ​​and variables with outliers represent values ​​that do not follow the variable pattern, which will greatly affect the accuracy of the model. By see the describe information, we see that there is an outliner on the columns of <strong>GOO_LATITUDE</strong> and <strong>GOO_LONGITUDE</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ax6Njbz6ZMFnGRhTDeNTxw.png" /></figure><p>We need to find out the problematic data and correct it. The latitude of Hong Kong is 22.302711, and the longitude is 114.177216. So, we apply a filter to <strong>GOO_LATITUDE </strong>and found out that has 3 rows had an abnormal value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1uoN-8fAkVmwHVXEa0AtlQ.png" /></figure><p>Refer to the internal CRM system, and query the addresses of these three customers on Google Map, and correct their addresses latitude and longitude.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cEbp1LFDkoqoToBRzriyqg.png" /></figure><p>We try to plot a scatter plot. <strong>Amazing!</strong> The green dots draw a picture similar to the map of Hong Kong. it’s time to find out the number of customer service centre locations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*vKMK78wosZBHsgagVt6Rtg.png" /></figure><h3>How to find out the optimal number of clusters?</h3><p>The important step to be performed before starting k-means analysis is to determine the number of clusters. But how many clusters do we need to setup? Therefore, we need to use the elbow method which provide a recommended optimal number of clusters in the data set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rgsb1JFJAjWOqAvXYPblZQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*6DxrzZkEUCqJpROfEYDbmw.png" /></figure><p>In the plot above the elbow is at k=4 indicating the optimal k for this dataset is 4. As we can see that with an increase in the number of clusters the WCSS value decreases. We can choose the value of K according to the decreases rate of WCSS. For example, from the clusters 1–2–3–4 in the above figure, we can see that WCSS drops suddenly and dramatically. After 4, the decrease is very small, so we choose 4 as the best value of K.</p><h3>Modeling</h3><p>We will show how the K-means algorithm works with the latitude and longitude data set of the customer’s address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0DKVnjHzR-B5eMo7iQJtHg.png" /></figure><p>The chart below shows the results. Visually, you can see that the <em>K</em>-means algorithm splits the two groups based on the distance feature. Each cluster centroid is marked with a star.</p><ul><li>Group 1 Centroid = (22.43797896, 114.18428292)</li><li>Group 2 Centroid = (22.30146589, 114.21442467)</li><li>Group 3 Centroid = (22.4148498 , 113.99272852)</li><li>Group 4 Centroid = (22.33590727, 114.14365898)</li></ul><p>Using domain knowledge of the dataset, we can infer that Group 1 is near Tai Po drivers, Group 2 is near North Point, Group 3 is near Tuen Mun and Group 4 is near Lai Chi Kok.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T-yfjNnF2tOaHxdw2SQfRw.png" /></figure><p>The chart below shows the resulting clusters. We see that four distinct groups have been identified by the algorithm;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*mTlCoupprmIOk7Yxxxkpjg.png" /></figure><p>Thanks for reading! If you enjoyed the post, please appreciate your support by applauding via the clap (👏🏼) button below or by sharing this article so others can find it.</p><p>I hope that you can learn how to use the k-means clustering techniques. Because data privacy policy, the dataset cannot provide at this time, but you can also find the source code in the <a href="https://github.com/kindersham/100DaysDS/tree/master/Customer_Service_Centre">GitHub</a> repository.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcc05eb7ab0f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/find-the-best-customer-service-centre-location-by-using-k-means-clustering-fcc05eb7ab0f">Find the best customer service centre location by using K-means clustering</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using logistic regression to predict whether a property can be sold]]></title>
            <link>https://medium.com/analytics-vidhya/using-logistic-regression-to-predict-whether-a-property-can-be-sold-b06c43154930?source=rss-2ed1b024159d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b06c43154930</guid>
            <category><![CDATA[data-science-life-cycle]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[data-preprocessing]]></category>
            <category><![CDATA[data-transformation]]></category>
            <dc:creator><![CDATA[Kinder Sham]]></dc:creator>
            <pubDate>Fri, 12 Jun 2020 08:48:10 GMT</pubDate>
            <atom:updated>2020-06-12T18:02:54.874Z</atom:updated>
            <content:encoded><![CDATA[<h4>Can my house be sold?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xLKi7r8nb6ciGAD-" /><figcaption>Photo by <a href="https://unsplash.com/@peterlaster?utm_source=medium&amp;utm_medium=referral">Pedro Lastra</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Logistic Regression</strong> is the earliest subject I learned in Data Science. When we encounter a category variable whose dependent variable (Y) is binary, logistic regression is a suitable method for regression analysis. Logistic regression is a predictive analysis which is used to describe data and explain the relationship between a dependent variable binary variable and one or more independent variables.</p><p><strong>When can logistic regression be used? <br></strong>For example: Do drugs, alcohol, unemployment, broken marriages, long-term health problems and physical disabilities increase suicide rates? (yes vs. no)?</p><p>In this article, I will explain how to use logistic regression to predict whether a house can be sold. Before starting, we will walk through the data science life cycle to understand what should happen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*KZZK9xvJzWM5h4pBMZK7HQ.png" /><figcaption>Photo by Srinivas Rao on Quora</figcaption></figure><p><strong>Steps of solving Business Problem with Data Science Life Cycle:</strong><br>1. Business Understand<br>2. Data Collection<br>3. Data Preparation<br>4. Exploratory Data Analysis<br>5. Modelling<br>6. Model Evaluation<br>7. Model Deployment</p><h3><strong>#1 ~ Business Understanding</strong></h3><p>Any project, regardless of its size, requires an understanding of the business, which is the basis for effectively solving business problems.</p><p>What is problem I trying to solve?</p><p>At this stage, I need to define problems, project goals and solutions from a business perspective. This is the first step in solving problems with data science methods. In this article, I am a manager of a real estate company. I need to find out the sales potential of these real estates, and these sales potentials are basically the data of past real estate transactions. So, I want to predict whether the property will be sold or not.</p><p>Therefore, it is a <strong>Supervisor Learning</strong> ~ I will use <strong>Classification</strong> method.</p><h3><strong>#2 ~ Data Collection</strong></h3><p>Data is the most critical part of the entire machine learning. So I need to consider the following:</p><ul><li>Do I have the data?</li><li>Where does the data come from?</li><li>Do we trust the data source?</li><li>Do I have the domain knowledge?</li></ul><p>The data is coming from the <a href="https://www.udemy.com/course/machine-learning-basics-classification-models-in-python/learn/lecture/14519188?start=0#overview">udemy online course</a></p><h3>#3 ~ Data Preparation &amp; #4 ~ Exploratory Data Analysis</h3><p>Now we will try to load the house dataset to jupyter notebook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*L5WfKbanknsIW6oFw9HMHQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L-rjrPEeTg6CUCMaNGhbhA.png" /></figure><p>Now, let’s take a look at the dataset. The dataset contain 506 rows and 19 columns. The dependent variable is <strong>Sold </strong>and price to Parks are independent variables. There are three categorical variables, namely airport, water body and bus, the others are numerical variables. In the picture below, we can see that there are missing values ​​in <strong>n_hos_beds</strong>. Before running logistic regression or any other type of machine, we need to deal with these missing values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*5WP4IjX8C0JzBmZCvUk90g.png" /></figure><p>We can see that all our numeric variables are listed at the top, and we have values ​​such as count, mean, standard deviation, minimum, maximum, 25% and 50%, and 75%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*OBKB0QRyWRnSRqcPaF0hFA.png" /></figure><p>Now, we will check whether the values ​​of these variables are what we want. Missing values ​​and variables with outliers represent values ​​that do not follow the variable pattern, which will greatly affect the accuracy of the model. By using the box-plot and joint-plot, we see that there is an outliner on the columns of <strong>n_hot_rooms</strong> and <strong>rainfall</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*Dm8PJQMw-CNwQRAcF4xmYA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*ORr19BhIHBITk08YT8yv_g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*GC_jMIr_2c0kUte-JaWvbg.png" /></figure><p>Now we have three observations from our numerical data. First there are missing values in the <strong>n_hos_beds </strong>variable The second problem is an outliers on the higher end of the <strong>n_hot_room </strong>variable<strong>. </strong>The third problem is an outliers on the lower end of <strong>rainfall</strong> variable. Now let’s look at the categorical variables. We will plot the count bar to all categorical variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*p9BabDS48tr4DbEW5fYLBw.png" /></figure><p>In the categorical variable, you can see that the <strong>bus_ter</strong> variable only had a value, yes. So in a sense this is not a variable. This is a constant. Therefore, we can delete this variable from our data because it does not provide any additional information or have any impact on the results.</p><p>Now we can start processing the problematic data. The first one is the missing value at <strong>n_hos_beds </strong>variable. The treatment of missing values ​​is generally divided into deleting missing values ​​or filling in missing values. Due to the small number of missing values, we will fill the missing value by <strong>Mean</strong> value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*QgjhyX-nm5aa9JueJJWYxw.png" /></figure><p>The next thing to deal with is the abnormal value of the upper limit of the <strong>n_hot_room</strong> variable and the abnormal value of the lower limit of the <strong>rainfall</strong> variable. We will use capping and flooring method to impute the abnormal values with 3* P99 and 0.3*P1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*XJMCdDOA2EWySMa7qWBtow.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*Uyf0gBlC-0XLeJ2Rip-fyg.png" /></figure><p>Finally, we will perform a data transformation, we will first drop out the <strong>bus_ter</strong> variable, beacuse all the <strong>bus_ter</strong> variable is YES, it does not provide any additional information or have any impact on the results. Then we will create the <strong>avg-dist</strong> variable, using the <strong>dist1</strong>, <strong>dist2</strong>, <strong>dist3</strong> and <strong>dist4</strong> variable the get the average distance to the employment hub. After that, we will use Scikit-learn LabelEncoder to transform the <strong>airport</strong> variable and use One-Hot Encoder the transform the <strong>waterbody</strong> variable. Lastly, we will drop the waterbody variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*Y2Hh_r-I3YcXJtDx1e-KEA.png" /></figure><h3>#5 ~ Modelling</h3><p>It is important to standardization the training data and test data because most machine learning models converge much faster if the proportions of the elements are the same. Doing standardization will centralize the feature’s mean between 0 to 1. The data will be distributed on normal distribution. To calculate the mean and standard deviation of those feature and apply the above formula to each observation/value, it will use sklearn’s StandardScaler:</p><p>The last thing to do before training our models is to split the dataset. I split this data randomly with 80/20 for training versus test examples to training set and testing set. We need to do this so we could estimate the predictive result of our model by predicting the testing set data (unseen data).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*mzb1Us6bzXKtIxo1Ona7RQ.png" /></figure><p>We have trained a model and to check the coefficient and intercept.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*5oHlcFNUOrP0zn_sA6fggA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*WXi_2geowfcIYh1izPCg0A.png" /></figure><h3>#6 ~ Model Evaluation</h3><p>In this step, we will evaluate the performance and accuracy of the machine learning model. The commonly used indicator for classification problems is called Confusion Matrix. Confusion Matrix is ​​a commonly used indicator for classification problems. It derives many different indicators and marks some more important derived indicators .Based on the prediction, we can conclude that predict whether a property can be sold or not accurately for 66.6% of the test data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*0bGUWFK0fnUshtdwWFTC-A.png" /></figure><h3>#7 ~ Model Deployment</h3><p>This is a relatively simple project, usually we also need iteration and function selection or compare with other algorithm. By collecting the results of the implementation model, you also need to receive feedback about the performance of the model and its impact on the implementation environment. By analyzing this information, data scientists can improve the model and improve its accuracy, thereby improving its practicality. Once a satisfactory model is developed, it will be implemented in the production environment.</p><p>Thanks for reading! If you enjoyed the post, please appreciate your support by applauding via the clap (👏🏼) button below or by sharing this article so others can find it.</p><p>I hope you have a basic understanding of the Data Science Life Cycle. How to think at each stage to help guide you through the methodology of a successful data science project. At the end, I hope that you can learn the how to use the logistic regression techniques. You can also find the full project on the <a href="https://github.com/kindersham/100DaysDS/tree/master/House_Prediction">GitHub</a> repository.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b06c43154930" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/using-logistic-regression-to-predict-whether-a-property-can-be-sold-b06c43154930">Using logistic regression to predict whether a property can be sold</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create a rule-based chatbot by using RiveScript]]></title>
            <link>https://medium.com/analytics-vidhya/how-to-create-a-rule-based-chatbot-by-using-rivescript-b3ca326b264d?source=rss-2ed1b024159d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3ca326b264d</guid>
            <category><![CDATA[dialogflow]]></category>
            <category><![CDATA[qna-maker]]></category>
            <category><![CDATA[rivescript]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Kinder Sham]]></dc:creator>
            <pubDate>Wed, 10 Jun 2020 15:38:07 GMT</pubDate>
            <atom:updated>2020-08-12T06:52:37.573Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6WXQZ2nDvlbejt5c" /><figcaption>Photo by <a href="https://unsplash.com/@agkdesign?utm_source=medium&amp;utm_medium=referral">Alex Knight</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>What is a chatbot? It is a service that allows users to interact with it through AI (Artificial Intelligence) or custom automatic rules through the chat communication interface. The user interacts with chatbots through the chat interface. The chatbot can provide various types of services. For example, in the application of the insurance industry, it can provide policy inquiry, premium inquiry, payment inquiry, premium change application, claims inquiry, etc.</p><p>With the development of instant messaging (IM) technology, many companies have begun to use the IM platform as an important channel for providing services. The chatbot is a new-generation user interface, companies can build a chatbot on the company’s website or on social software, such as Telegram, Line, and Facebook Messenger, to provide quality customer service.</p><p>Is it difficult to build a Chatbot? If I don’t understand the program at all, can I still create my own chatbot? In simple terms, it is not difficult to build a basic operation Chatbot. To create a “smart” Chatbot, it needs to be achieved through artificial intelligence or machine learning technology. And there are many tools on the market that can help you build a chatbot with artificial intelligence.</p><p>RiveScript is a scripting language for chatterbots which is very similar to AIML, but matching Mode and condition control are more complete than AIML. RiveScript is a rule-based engine, where rules are created by humans writers in program scripts through a process called dialog flow scripting. These use a scripting metalanguage (simply called a “script”) as their source code. I will show you how to create a chatbot using Python and RiveScript.</p><p>In this tutorial, we will be using one Python libraries that require installation. You can easily do this via the pip install command as follows to install RiveScript:</p><pre>$ pip install rivescript<br># --or--<br>$ easy_install rivescript</pre><p><a href="https://www.rivescript.com/">Artificial Intelligence Scripting Language - RiveScript.com</a></p><p>RiveScript works well in python 2 and 3, after installation, create a chatbot.py and import the following library. Let’s take a look at the code of the chatbot app that we are building today. You will see that there are less than 20 lines of code:</p><pre>import re<br>from rivescript import RiveScript</pre><pre>bot = RiveScript(utf8=True, debug=False)<br>bot.unicode_punctuation = re.compile(r&#39;[.,!?;:]&#39;)<br>bot.load_directory(&quot;eg/brain&quot;)<br>bot.sort_replies()</pre><pre>msg = sys.argv[1]</pre><pre>def response(text):<br>    text = text.encode(&quot;utf-8&quot;)<br>    reply = bot.reply(&quot;localuser&quot;, text)<br>    reply_text = reply.encode(&quot;utf-8&quot;).strip()<br>    <br>    return reply_text</pre><pre>def main():        <br>    input_text = msg<br>    input_text = input_text.encode(&quot;utf8&quot;)</pre><pre>    reply_text = response(input_text)<br>    print (&quot;Bot: &quot; + str(reply_text)) </pre><pre>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>Let’s take some time to make some understanding of the above code.</p><p><strong><em>Lines 1 and 2<br></em></strong>Imports re and rivescript libraries.</p><p><strong><em>Lines 3 to 6<br></em></strong>Setup the bot dictionary.</p><p><strong><em>Lines 7 to 11<br></em></strong>Create a function call response, which is the information returned by the chatbot to humans.</p><p><strong><em>Lines 12 and 16<br></em></strong>Create a function call main, which is the main structure of the program.</p><p><strong><em>Line 17 and 18<br></em></strong>call the main function.</p><p>The standalone mode makes for an excellent RiveScript development environment. It allows you to run interactive conversations, then interacts with them using<strong>: commands</strong>. This is a special set of interactive command tools for testing and debugging your dialogs during the development and debug phase.</p><p>You can define the bot’s dialog flows with a script stored as a normal text file. This is much simpler than the methods used by other chatbot tools. Other chatbot tools usually use a browser-based user interface, JSON, or XML. Writing scripts as text files gives you complete control over the conversation flow and makes it easier to process and upgrade session code using back-end scripts and tools.</p><p>To create a chat script, you need to create the file under ./eg/brain, and I will create a file called chat.rive.</p><p>Here what a RiveScript script file looks like:</p><pre>+ (Hi)<br>- Hello!<br>- Hi, how are you?</pre><pre>+ (What is your name?)<br>- (I am Pepper)</pre><pre>+ (Good Morning)<br>- Morning</pre><p>In fact, there are many complex functions that can be put into SuperScript scripts, like the following example: create a script to answer what time is it.</p><pre>&gt; object askTime python<br>    import time <br> <br>    now_hour = int(time.strftime(&quot;%H&quot;))<br>    now_min = (time.strftime(&quot;%M&quot;))</pre><pre>if (now_hour &gt; 12):<br>        ampm = &quot;pm&quot;<br>        now_hour = now_hour - 12<br>    else:<br>        ampm = &quot;am&quot;</pre><pre>output = str(ampm) + str(now_hour) + str(now_min) <br> <br>    return output<br>&lt; object</pre><pre>+ (|*)(What time is it now?)(|*)(what time now?)(|*)<br>- &lt;call&gt;askTime&lt;/call&gt;</pre><p>After saving all the code into a files fire up the command prompt and run the following command:</p><pre>&gt;python chatbot.py &quot;What is your name?&quot;<br>&gt;Bot:My name is Pepper</pre><p>In addition to using RiveScript to create rule-based chatbots, it can also be combined with Microsoft’s Q&amp;AMaker or Google’s Dialogflow to create a chatbot suitable for itself</p><p>Thanks for reading! If you enjoyed the post, please appreciate your support by applauding via the clap (👏🏼) button below or by sharing this article so others can find it.</p><p>In the end, I hope that you can learn how to create a basic rule-based chatbot. You can also find the full project on the <a href="https://github.com/kindersham/100DaysDS/tree/master/chatbot-python-rivescripts-msqna">GitHub</a> repository.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3ca326b264d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/how-to-create-a-rule-based-chatbot-by-using-rivescript-b3ca326b264d">How to create a rule-based chatbot by using RiveScript</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to scrape a news website using Python, BeautyfulSoup, and Selenium to build the Word Cloud]]></title>
            <link>https://medium.com/analytics-vidhya/how-to-scrape-a-news-website-using-python-beautyfulsoup-and-selenium-to-build-the-word-cloud-3355066b72dc?source=rss-2ed1b024159d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3355066b72dc</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[word-cloud]]></category>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[beautifulsoup]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Kinder Sham]]></dc:creator>
            <pubDate>Mon, 25 May 2020 15:59:41 GMT</pubDate>
            <atom:updated>2020-06-16T01:30:02.992Z</atom:updated>
            <content:encoded><![CDATA[<h4>Better visualization by using word cloud</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oFjaReilo0xBbXt766hKwA.png" /></figure><p>From early 2020 to the present, what is the most frequent news in Hong Kong newspapers? Hong Kong social movement, 2019 Coronavirus or China–United States trade war? I scraped a well-known newspaper in Hong Kong, hope to use a good visualization method ~ <strong>Word Cloud</strong> to get the answer I want.</p><p><strong>What is web scraping?</strong></p><p>Web scraping tools are specifically used to extract information from websites. They are also known as network collection tools or Web data extraction tools.</p><p><strong>Why doing web scraping?</strong></p><p>The web scraping tool can be used for unlimited purposes in various scenarios. For examples:</p><ol><li>Collect market research data</li><li>Collect stock markets information</li><li>Collect contact information</li><li>Collect data to download for offline reading or storage</li><li>Track prices in multiple markets, etc.</li></ol><p><strong>How to scraping in Python?</strong></p><p>Scrape a website in Python is very easy, especially with the help of the BeautifulSoup and Selenium library. Beautiful Soup is a Python library module that allows developers to quickly parse web page HTML code and extract useful data from it by writing a small amount of code, reducing development time, and accelerating the programming speed of the web scraping. Selenium is a tool for automated testing of web pages, which can automatically operate the browser through some of the methods it provides, and can completely simulate the operation of real people.</p><p>Before scraping a website, some preparations must be made, enter the command in Jupiter notebook, it will install the following libraries.</p><pre>!pip install BeautifulSoup4<br>!pip install selenium</pre><p><strong>What is Word Cloud and why we need it?</strong></p><p>Word Cloud is a very good third-party word cloud visualization library in Python. The word cloud is a visual display of keywords that appear more frequently in the text. WordCloud will filter out a lot of low-frequency and low-quality text information so that the audience can understand the main purpose of the text at a glance.</p><p><strong>What is word segmentation?</strong></p><p>Word segmentation is the process of recombining consecutive word sequences into word sequences according to certain specifications. Jieba is one of the better Chinese word segmentation library, because Chinese usually contains the entire sentence, so we need to use Jieba to assist in the work of word segmentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*26qQCmYtmhLhPLjmy2kY4g.png" /></figure><p>Before generating a word cloud image, some preparations must be made, enter the command in Jupiter notebook, it will install the following libraries.</p><pre>!pip install wordcloud<br>!pip install jieba</pre><p><strong># Load the libraries</strong></p><pre>#! /usr/bin/env python<br># -*- encoding UTF-8 -*-</pre><pre>import os<br>import sys<br>from importlib import reload<br>reload(sys)</pre><pre>if sys.version[0] == &#39;2&#39;:<br>    sys.setdefaultencoding(&quot;utf-8&quot;)<br>    <br>    import parse<br>    import urllib2<br>else:<br>    import urllib.parse<br>    from urllib.request import urlopen</pre><pre>import re<br>import jieba</pre><pre>import pandas as pd<br>import numpy as np</pre><pre>#from bs4 import BeautifulSoup<br>from selenium import webdriver<br>from selenium.webdriver import ChromeOptions</pre><pre>from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator</pre><pre>from PIL import Image</pre><pre>import matplotlib.pyplot as plt<br>%matplotlib inline</pre><pre>jieba.enable_paddle()</pre><p><strong># Clean the CSS, JavaScript and HTML tag</strong></p><pre>def cleanHTML(html):<br>    for script in html([&quot;script&quot;, &quot;style&quot;]): # remove all javascript and stylesheet code<br>        script.extract()<br>    # get text<br>    text = html.get_text()<br>    # break into lines and remove leading and trailing space on each<br>    lines = (line.strip() for line in text.splitlines())<br>    # break multi-headlines into a line each<br>    chunks = (phrase.strip() for line in lines for phrase in line.split(&quot;  &quot;))<br>    # drop blank lines<br>    text = &#39;\n&#39;.join(chunk for chunk in chunks if chunk)<br>    <br>    return text</pre><p><strong># Find the main focus news link of the day</strong></p><pre>def getNewsLink(news_date):<br>    try:<br>        options = ChromeOptions()<br>        options.add_argument(&#39;headless&#39;)<br>        driver = webdriver.Chrome(options=options)</pre><pre>        url = &#39;<a href="https://orientaldaily.on.cc/cnt/news/&#39;">https://orientaldaily.on.cc/cnt/news/&#39;</a> + str(news_date) + &#39;/mobile/index.html&#39;</pre><pre>        driver.get(url)<br>        driver.implicitly_wait(30)</pre><pre>        html_source = (driver.page_source.encode(&#39;utf-8&#39;))</pre><pre>        driver.quit()</pre><pre>        soup = BeautifulSoup(html_source, &#39;html.parser&#39;)<br>        news = soup.find(&#39;div&#39;, attrs={&#39;id&#39;:&#39;swipe&#39;})<br>        main_focus = soup.find(&#39;div&#39;, attrs={&#39;class&#39;:&#39;main-focus-container&#39;})<br>        main_focus_link = &#39;<a href="https://orientaldaily.on.cc&/#39;">https://orientaldaily.on.cc&#39;</a> + main_focus.find(&#39;a&#39;, href = re.compile(r&#39;[/]([a-z]|[A-Z])\w+&#39;)).attrs[&#39;href&#39;]</pre><pre>        return (main_focus_link)<br>    except:<br>        return 0</pre><p><strong># Data Collection</strong></p><pre>def getNews(news_url):<br>    options = ChromeOptions()<br>    options.add_argument(&#39;headless&#39;)<br>    driver = webdriver.Chrome(options=options)<br>    <br>    driver.get(news_url)<br>    driver.implicitly_wait(30)<br>        <br>    html_source = (driver.page_source.encode(&#39;utf-8&#39;))<br>        <br>    driver.quit()<br>    <br>    soup = BeautifulSoup(html_source, &#39;html.parser&#39;)<br>    paragraph = soup.find_all(&#39;div&#39;, attrs={&#39;class&#39;:&#39;paragraph&#39;})<br>    paragraph_list = []<br>    <br>    for sub_paragraph in paragraph:<br>        clean_sub_paragraph = cleanHTML(sub_paragraph)<br>        paragraph_list.append(clean_sub_paragraph)<br>        <br>    full_paragraph_list = [e for e in paragraph_list if e]<br>    <br>    if (len(full_paragraph_list) &gt; 0):<br>        f=open(&quot;news.txt&quot;, &quot;a+&quot;)<br>        <br>        for i in range(len(full_paragraph_list)):<br>            <br>            <br>            for line in full_paragraph_list[i].splitlines():<br>                clean_paragraph = cleanText(line)<br>                <br>                f.write(clean_paragraph)<br>                <br>        f.write(&#39;\n\n&#39;)<br>        f.close()</pre><p><strong># Draw the word cloud</strong></p><pre>def draw_word_cloud(text, images_name, plt_title):<br>    images_path = images_name<br>    images = Image.open(images_path)<br>    <br>    #create a write mask <br>    images_mask = Image.new(&quot;RGB&quot;, images.size, (255,255,255))<br>    images_mask.paste(images, images)<br>    images_mask = np.array(images_mask)<br>    <br>    color = ImageColorGenerator(images_mask)<br>    <br>    #Chinese need to use another font, download it from <a href="https://www.freechinesefont.com/">https://www.freechinesefont.com/</a><br>    font_path = &#39;HanyiSentyCandy.ttf&#39;<br>    <br>    #create wordcloud ~ <br>    wc = WordCloud(font_path=font_path, max_font_size=250, max_words=1000, mask=images_mask, \<br>                   margin=5, background_color=&quot;black&quot;).generate_from_text(text)<br>    wc.recolor(color_func = color, random_state = 7)<br>    <br>    #Save the image<br>    wc.to_file(&quot;news.png&quot;)<br>    <br>    plt.rcParams[&quot;figure.figsize&quot;] = (16, 12)<br>    <br>    plt.title(plt_title)<br>    plt.imshow(wc, interpolation=&quot;bilinear&quot;)<br>    plt.axis(&quot;off&quot;)<br>    plt.show()</pre><p><strong># Main logic:</strong></p><pre>if __name__ == &quot;__main__&quot;:<br>    start_date = input(&quot;Enter the start date (yyyymmdd): &quot;)<br>    end_date = input(&quot;Enter the end date (yyyymmdd): &quot;)<br>    <br>    if ((start_date != &quot;&quot;) and (end_date != &quot;&quot;)):<br>        daterange = pd.date_range(start_date, end_date)<br>        <br>        #Download the main focus news<br>        for news_date in daterange:<br>            print (&#39;Downloading &#39; + str(news_date) + &#39; news...&#39;)<br>            single_news_date = dateConvert(news_date)<br>            getNews(getNewsLink(single_news_date))<br>            <br>        source_text = open(&#39;news.txt&#39;, &#39;r&#39;,encoding= &#39;UTF-8&#39;).read()<br>        tokens = &#39; &#39;.join(jieba.cut_for_search(source_text))<br>        <br>        title = str(start_date) + &#39; - &#39; + str(end_date) + &#39; Main Focus News on on.cc&#39;<br>        <br>        draw_word_cloud(tokens, &#39;hongkongpng.png&#39;, title)</pre><p><strong># Future Improvement</strong></p><ol><li>Add the processing of STOPWORDS</li><li>Use a different word segmentation library, such as thulac, FoolNLTK, HanLP, nlpir and ltp.</li></ol><p>Thanks for reading! If you enjoyed the post, please appreciate your support by applauding via the clap (👏🏼) button below or by sharing this article so others can find it.</p><p>In the end, I hope that you can learn the scraping techniques. You can also find the full project on the <a href="https://github.com/kindersham/100DaysDS/tree/master/NewsWordCloud">GitHub</a> repository.</p><p><strong>References</strong></p><ul><li><a href="https://medium.com/the-artificial-impostor/nlp-four-ways-to-tokenize-chinese-documents-f349eb6ba3c3">[NLP] Four Ways to Tokenize Chinese Documents</a></li><li><a href="https://amueller.github.io/word_cloud/index.html">WordCloud for Python documentation - wordcloud 1.8.1 documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3355066b72dc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/how-to-scrape-a-news-website-using-python-beautyfulsoup-and-selenium-to-build-the-word-cloud-3355066b72dc">How to scrape a news website using Python, BeautyfulSoup, and Selenium to build the Word Cloud</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to generate a Chinese text-to-speech via iFLYTEK API?]]></title>
            <link>https://medium.com/analytics-vidhya/how-to-generate-a-chinese-text-to-speech-via-iflytek-api-db469b31f4a2?source=rss-2ed1b024159d------2</link>
            <guid isPermaLink="false">https://medium.com/p/db469b31f4a2</guid>
            <category><![CDATA[merge-audio]]></category>
            <category><![CDATA[mp3]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[iflytek]]></category>
            <category><![CDATA[text-to-speech]]></category>
            <dc:creator><![CDATA[Kinder Sham]]></dc:creator>
            <pubDate>Sat, 23 May 2020 11:16:09 GMT</pubDate>
            <atom:updated>2020-06-16T01:26:50.869Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to generate a Chinese text-to-speech via iFLYTEK API</h3><h4>Add voice to your websites and apps to make your content available to a wider audience.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xnA0J7rqH9WQQuLG" /><figcaption>Photo by <a href="https://unsplash.com/@eprouzet?utm_source=medium&amp;utm_medium=referral">Eric Prouzet</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Introduction</strong></p><p>Last year, I carried out a project requesting the conversion of ancient Chinese poetry from text to audio. Therefore, I conducted some research on the Internet and found that not many companies can provide Chinese text-to-speech services. Finally, I found that using iFLYTEK source code on github can provide speech recognition functions, and improved it to meet the requirements of the project.</p><p>Original source code link on github:</p><p><a href="https://github.com/ssky87/iflytek_sdk_python">ssky87/iflytek_sdk_python</a></p><p><strong>What is Text-To-Speech?</strong></p><p>The abbreviation of Text-To-Speech is (TTS), that is, “from text to speech”, which is a part of the human-machine dialogue, so that the machine can speak. Text-to-speech (TTS) is a natural language modeling process that requires changing text units to speech units for audio presentation. This is the opposite of speech and text. In this technique, a technique absorbs spoken words and attempts to record them accurately as text.</p><p>Now that we know what Text-To-Speech is, I will explain the preliminary preparation and requirements of the project.</p><p><strong>Preparation</strong>：</p><p>I will use ubuntu 16.04 for this project, because I found that the version above ubuntu 18.04 is not working. The second is the need to use Python 2.7 version. After install, we download the original github package first.</p><pre>sysadmin@tts:~$ git clone <a href="https://github.com/ssky87/iflytek_sdk_python.git">https://github.com/ssky87/iflytek_sdk_python.git</a><br>Cloning into &#39;iflytek_sdk_python&#39;...<br>remote: Enumerating objects: 16, done.<br>remote: Total 16 (delta 0), reused 0 (delta 0), pack-reused 16<br>Unpacking objects: 100% (16/16), done.<br>Checking connectivity... done.</pre><p>Then, we need to test the package is it running correct.</p><pre>sysadmin@tts:~$ cd iflytek_sdk_python/<br>sysadmin@tts:~/iflytek_sdk_python$ python tts.py<br>INFO:root:正在合成 [科大讯飞还是不错的]...<br>DEBUG:root:.<br>DEBUG:root:.<br>DEBUG:root:.<br>DEBUG:root:.<br>DEBUG:root:.<br>INFO:root:合成完成！<br>sysadmin@tts:~/iflytek_sdk_python$ ls<br>README.md  <strong>msc</strong>  stt.py  tts.py  <strong>x64</strong>  <strong>x86</strong>  xx.wav</pre><p>We will see a xx.wav, try to download and listen to it, this is the voice file we just generated. But there are some requirements on this project, for example:</p><ol><li>Need to input from a text file</li><li>Each paragraph needs to add a pause time</li><li>Since the output wav file size is too large, it needs to be converted to mp3</li></ol><p>After confirming the requirements, we need to install ffmpeg package to converted the wav to mp3.</p><pre>sysadmin@tts:~$ sudo add-apt-repository ppa:mc3man/trusty-media<br>sysadmin@tts:~$ sudo apt-get update<br>sysadmin@tts:~$ sudo apt-get install ffmpeg</pre><p><strong>Modify the source code</strong></p><p>Import the required library</p><pre>#!/usr/bin/env python<br># -*- coding: utf-8 -*-<br>import os<br>import sys<br>reload(sys)<br>sys.setdefaultencoding(&#39;utf-8&#39;)<br><br>import time<br>from ctypes import *<br>from io import BytesIO<br>import wave<br>import platform<br>import logging<br>from pydub import AudioSegment<br>import shutil</pre><p>Encapsulate the source code in class</p><pre>class convertTTS(object):<br>    logging.basicConfig(level=logging.DEBUG)<br>    BASEPATH=os.path.split(os.path.realpath(__file__))[0]<br>    plat = platform.architecture()</pre><pre>    if plat[0] == &#39;32bit&#39;:<br>        cur = cdll.LoadLibrary(BASEPATH + &#39;/x86/libmsc.so&#39;)<br>    else:<br>        cur = cdll.LoadLibrary(BASEPATH + &#39;/x64/libmsc.so&#39;)</pre><pre>    def login(self,str_txt=&#39;appid = 539feff8, work_dir = .&#39;):<br>        MSPLogin = self.cur.MSPLogin<br>        ret = 0<br>        ret = MSPLogin(None,None,str_txt) <br>  <br>        if ret != 0:<br>            logging.error(&quot;MSPLogin failed, error code: &quot; + str(ret))<br>        else:<br>            logging.info(&quot;MSPLogin&quot;)<br><br>        return ret</pre><pre>    def logout(self):<br>        MSPLogout = self.cur.MSPLogout<br>        MSPLogout()<br>        logging.info(&quot;MSPLogout&quot;)</pre><pre>    def saveWave(self, raw_data, _tmpFile = &#39;test.wav&#39;):<br>        f = wave.open(_tmpFile,&#39;w&#39;)<br>        f.setparams((1, 2, 16000, 262720, &#39;NONE&#39;, &#39;not compressed&#39;))<br>        f.writeframesraw(raw_data)<br>        f.close()</pre><pre>        return _tmpFile</pre><pre>    def text_to_speech(self,src_text,voicename,speed,volumn,pitch,mp3,file_name=None):</pre><pre>        logging.info (str(voicename) + &quot; &quot; + str(speed) + &quot; &quot; + str(volumn) + &quot; &quot; + str(pitch))<br>        encoding = &#39;utf8&#39;<br>        sample_rate = 16000<br>        rdn = 2<br><br>        QTTSSessionBegin = self.cur.QTTSSessionBegin<br>        QTTSTextPut = self.cur.QTTSTextPut<br>        QTTSAudioGet = self.cur.QTTSAudioGet<br>        QTTSAudioGet.restype = c_void_p<br>        QTTSSessionEnd = self.cur.QTTSSessionEnd<br><br>        ret_c = c_int(0)</pre><pre>session_begin_params=&quot;voice_name=&quot; + str(voicename) + &quot;,text_encoding=&quot; + str(encoding) + &quot;,sample_rate=&quot; + str(sample_rate) +&quot;,speed=&quot; + str(speed) + &quot;,volume=&quot; + str(volumn) + &quot;,pitch=&quot; + str(pitch) + &quot;,rdn=&quot; + str(rdn)<br><br>        sessionID = QTTSSessionBegin(session_begin_params, byref(ret_c))<br><br>	if ret_c.value != 0 :<br>            logging.error(&quot;QTTSSessionBegin failed, error code: &quot; + ret_c.value)<br>            return</pre><pre>        ret = QTTSTextPut(sessionID, src_text, len(src_text),None)</pre><pre>        if ret != 0:<br>            logging.error(&quot;QTTSTextPut failed, error code: &quot; + str(ret))<br>            QTTSSessionEnd(sessionID, &quot;TextPutError&quot;)<br>            return</pre><pre>        logging.info(&quot;Synthesizing : &quot; + (src_text))</pre><pre>        audio_len = c_uint(0)<br>	synth_status = c_int(0)<br>        f = BytesIO()</pre><pre>        while True:<br>            p = QTTSAudioGet(sessionID, byref(audio_len), byref(synth_status), byref(ret_c))</pre><pre>        if ret_c.value != 0:<br>	    logging.error(&quot;QTTSAudioGet failed, error code: &quot; + str(ret_c))<br>	    QTTSSessionEnd(sessionID, &quot;AudioGetError&quot;)<br>	    break</pre><pre>        if p != None:<br>	    buf = (c_char * audio_len.value).from_address(p)<br>	    f.write(buf)</pre><pre>        if synth_status.value == 2 :<br>	    self.saveWave(f.getvalue(),file_name)<br>	    break</pre><pre>        time.sleep(1)</pre><pre>        logging.info(&#39;Convert Completed！【&#39; + file_name  + &#39;】\n&#39;)</pre><pre>        ret = QTTSSessionEnd(sessionID, &quot;Normal&quot;)</pre><pre>        if ret != 0:<br>            logging.error(&quot;QTTSTextPut failed, error code: &quot; + str(ret))</pre><p>Since we are converting by paragraph, multiple files will be generated, so we need to merge the files together.</p><pre>def joinwav(fn, num_of_file):<br>    infiles =[]<br>    outfile = fn + &quot;.wav&quot;<br><br>    for num in range(1,num_of_file):<br>	filename = fn + &quot;-&quot; + str(num) + &quot;.wav&quot;<br>	logging.info(filename)<br>	infiles.append (AudioSegment.from_wav(filename))<br>	infiles.append (AudioSegment.from_wav(&quot;silentFix.wav&quot;))<br>	<br>    combined = infiles[0]<br>	<br>    for wavcombined in infiles[1:]:<br>	combined = combined.append(wavcombined)<br><br>    combined.export(outfile, format=&quot;wav&quot;)<br>    logging.info(&#39; Merge Complete！【&#39; + outfile  + &#39;】&#39;)</pre><p>In addition, we also need to convert the output wav file to mp3 file</p><pre>def wav2mp3(filename):<br>    fn = os.path.splitext(filename)[0]<br><br>    AudioSegment.from_wav(filename).export(fn + &quot;.mp3&quot;, format=&quot;mp3&quot;<br>    logging.info(&#39; MP3 Output Complete！【&#39; + fn + &quot;.mp3&quot;  + &#39;】&#39;)</pre><p>Clean up special symbols of text file</p><pre>def clear(text):<br>    text = text.replace(&#39;《&#39;, &#39;&#39;)<br>    text = text.replace(&#39;》&#39;,&#39;&#39;)<br><br>    return text</pre><p>Program logic: you can change the voice name, speed, volume, tone, mp3, joinfile in the function.</p><p>voicename: Through this parameter, different speakers are set to achieve different languages, dialects, genders, etc. The default speaker is xiaoyan</p><p>speed: Through this parameter, set the speech rate of the audio returned by the synthesis, value range: [0, 100], default: 50</p><p>volumn: Through this parameter, set the volume of the audio returned by the synthesis, value range: [0, 100], default: 50</p><p>pitch: Through this parameter, set the tone of the synthesized return audio, value range: [0, 100], default: 50</p><p>mp3: Through this parameter, set output mp3 file or not</p><p>joinfile: Through this parameter, set whether to link multiple wav files into one file</p><pre>def main(filename, voicename, speed, volumn, pitch, mp3, joinfile):<br>    lineno = 0<br><br>    fh = open(filename)<br>    fn = os.path.splitext(filename)[0]<br><br>    tts = convertTTS()<br>    tts.login()<br><br>    while True:	<br>        content = fh.readline()<br><br>	if (content &lt;&gt; &#39;&#39;):<br>	    if not content.strip(): continue<br>		content = clear(content)<br><br>		lineno = lineno + 1<br>			<br>		targetfilename = fn + &quot;-&quot; + str(lineno) + &quot;.wav&quot;<br>						    tts.text_to_speech(content,voicename,speed,volumn,pitch,mp3,targetfilename)<br><br><br>	if not content:<br>	    break</pre><pre>    fh.close()<br>	<br>    tts.logout()<br>	<br>    if (1 == joinfile):<br>	joinwav(fn, lineno+1)<br><br>	if (1 == mp3):<br>            wav2mp3(fn + &quot;.wav&quot;)</pre><pre>if __name__ == &quot;__main__&quot;:<br>    nfn = sys.argv[1]</pre><pre>    main(nfn, &#39;xiaoyan&#39;, 50, 50, 50, 1, 1)</pre><p>Now you can run the program in console!!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*EK51s4fLJuKURdA5iZtuow.png" /></figure><p>Thanks for reading! If you enjoyed the post, please appreciate your support by applauding via the clap (👏🏼) button below or by sharing this article so others can find it.</p><p>You can also download the source code in my <a href="https://github.com/kindersham/100DaysDS/tree/master/iFLYTEK_TTS">github</a> repository. Thank you for your reading time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db469b31f4a2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/how-to-generate-a-chinese-text-to-speech-via-iflytek-api-db469b31f4a2">How to generate a Chinese text-to-speech via iFLYTEK API?</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to run a data science project with GPU on an old computer]]></title>
            <link>https://medium.com/analytics-vidhya/how-to-run-a-data-science-project-with-gpu-on-an-old-computer-330805898d08?source=rss-2ed1b024159d------2</link>
            <guid isPermaLink="false">https://medium.com/p/330805898d08</guid>
            <category><![CDATA[cuda-10]]></category>
            <category><![CDATA[anaconda]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[jupyter-notebook]]></category>
            <dc:creator><![CDATA[Kinder Sham]]></dc:creator>
            <pubDate>Fri, 22 May 2020 05:32:52 GMT</pubDate>
            <atom:updated>2020-06-12T18:05:03.218Z</atom:updated>
            <content:encoded><![CDATA[<h4>Use it when you can, don’t waste it!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eWraNnXv8xFIxbeO" /><figcaption>Photo by <a href="https://unsplash.com/@hishahadat?utm_source=medium&amp;utm_medium=referral">Shahadat Rahman</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Introduction</h4><p>I had bought this PC in 2014, but usually, I only work on my MacBook, the PC only for simple web browsing and backup the photo. Since I enrolled MSc Data Science course in 2018, Macbooks without GPU processors were too slow to process image data, so I purchased an NVIDIA GeForce GTX 1050 Ti graphics card (it only HKD 550, very cheap) and installed it on my PC.</p><p>OS：Ubuntu 18.04 LTS<br>CPU: Intel Core I5–4570 @3.2GHz x 4<br>RAM: 16GB<br>HDD: 500GB SSD<br>Display Card：NVIDIA GeForce GTX 1050 Ti</p><h4>Procedure:</h4><p>1. Install Ubuntu 18.04 LTS Server<br>2. Install CUDA Toolkit 10 &amp; CuDNN 7 &amp; NCCL 2<br>3. Install Anaconda &amp; configuration to remote use</p><h4><strong>#Install Ubuntu 18.04 LTS Server</strong></h4><p>Since I only use this PC via remotely by SSH and Juypter Notebook, so I will install the Ubuntu 18.04 LTS Server. The difference between Ubuntu Desktop and Ubuntu Server is the GUI interfaces for installation and usage. Basically, installing Ubuntu Desktop is the same as installing any other software. But Ubuntu Server uses a process-driven menu instead.</p><p>The Ubuntu 18.04 LTS Desktop or Server ISO can download here:</p><p>Desktop: <a href="http://ftp.cuhk.edu.hk/pub/Linux/ubuntu-releases/18.04/ubuntu-18.04.4-desktop-amd64.iso">http://ftp.cuhk.edu.hk/pub/Linux/ubuntu-releases/18.04/ubuntu-18.04.4-desktop-amd64.iso</a></p><p>Server: <a href="http://ftp.cuhk.edu.hk/pub/Linux/ubuntu-releases/18.04/ubuntu-18.04.4-live-server-amd64.iso">http://ftp.cuhk.edu.hk/pub/Linux/ubuntu-releases/18.04/ubuntu-18.04.4-live-server-amd64.iso</a></p><p>The installation method can refer to the following Jack Wallen article on techrepublic.com</p><p><a href="https://www.techrepublic.com/article/how-to-install-ubuntu-server-18-04/">How to install Ubuntu Server 18.04</a></p><p>Remember, no matter installing the Desktop or Server version, you need to run an update after restarting.</p><pre># System update &amp; upgrade<em><br></em><strong>users@ds</strong>:<strong>~/</strong>$<em>sudo apt-get update</em></pre><pre><strong>users@ds</strong>:<strong>~/</strong>$<em>sudo apt-get upgrade</em></pre><p><strong># Install CUDA Toolkit 10</strong></p><p>Because need to use Tensorflow with GPU for calculation, so we need to install CUDA, CuDNN7, NCCL 2, and other packages.</p><pre># Install other importance packages<br><strong>sysadmin@ds</strong>:<strong>~/</strong>$sudo apt-get install build-essential dkms freeglut3 freeglut3-dev libxi-dev libxmu-dev</pre><pre><strong>sysadmin@ds</strong>:<strong>~/</strong>$<em>wget </em><a href="https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/cuda-repo-ubuntu1804_10.0.130-1_amd64.deb"><em>https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/cuda-repo-ubuntu1804_10.0.130-1_amd64.deb</em></a></pre><pre><strong>sysadmin@ds</strong>:<strong>~/</strong>$sudo apt-key adv — fetch-keys <a href="https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/7fa2af80.pub">https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/7fa2af80.pub</a></pre><pre><strong>sysadmin@ds</strong>:<strong>~/</strong>$sudo apt-get update</pre><pre><strong>sysadmin@ds</strong>:<strong>~/</strong>$sudo dpkg -i cuda-repo-ubuntu1804_10.0.130–1_amd64.deb</pre><p>## Install CuDNN 7 and NCCL 2</p><pre><strong>sysadmin@ds</strong>:<strong>~/</strong>$wget <a href="http://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64/nvidia-machine-learning-repo-ubuntu1804_1.0.0-1_amd64.deb">http://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64/nvidia-machine-learning-repo-ubuntu1804_1.0.0-1_amd64.deb</a></pre><pre><strong>sysadmin@ds</strong>:<strong>~/</strong>$sudo apt install ./nvidia-machine-learning-repo-ubuntu1804_1.0.0–1_amd64.deb</pre><pre><strong>sysadmin@ds</strong>:<strong>~/</strong>$sudo apt-get update</pre><pre><strong>sysadmin@ds</strong>:<strong>~/</strong>$apt-get install — no-install-recommends nvidia-driver-418</pre><pre><strong>sysadmin@ds</strong>:<strong>~/</strong>$reboot</pre><p>## Reboot the computer</p><p>After reboot, type: nvidia-smi, the installation is normal, it seems that there is no problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3nW82_QsPnlauV8p5Cm_Rw.png" /></figure><p><strong>#Install Anaconda &amp; configuration to remote use</strong></p><p>Designed specifically for data science and machine learning workflows, Anaconda is an open-source package manager, environment manager, and distribution of Python and R programming languages.</p><pre># Download Anaconda Python 3.7:<br><strong>sysadmin@ds</strong>:<strong>~/</strong>$wget <a href="https://repo.anaconda.com/archive/Anaconda3-2020.02-Linux-x86_64.sh">https://repo.anaconda.com/archive/Anaconda3-2020.02-Linux-x86_64.sh</a></pre><p>The installation method can refer to the following Lisa Tagliaferri article on digitalocean.com</p><p><a href="https://www.digitalocean.com/community/tutorials/how-to-install-anaconda-on-ubuntu-18-04-quickstart">How To Install Anaconda on Ubuntu 18.04 [Quickstart] | DigitalOcean</a></p><p>To create a jupyter_notebook_config.py file, with all the defaults commented out, you can use the following command line:</p><pre><strong>sysadmin@ds</strong>:<strong>~/</strong>$jupyter notebook --generate-config</pre><p>For remote access, we need to set the password to the Jupyter Notebook, you can use the following command line::</p><pre><strong>sysadmin@ds</strong>:<strong>~/</strong>$jupyter notebook password</pre><p>After setting the password, we need to modify the Jupyter Notebook configuration file, you can find the file in $home/.jupyter/jupyter_notebook_config.py:</p><pre><strong>sysadmin@ds</strong>:<strong>~/</strong>$cd .jupyter<br><strong>sysadmin@ds</strong>:<strong>~/.jupyter</strong>$nano jupyter_notebook_config.py</pre><pre>change the following item:</pre><pre>c.NotebookApp.ip = <strong>&#39;0.0.0.0&#39;<br></strong>c.NotebookApp.open_browser = <strong>False</strong></pre><p>Create the jupyter.services</p><pre><strong>sysadmin@ds</strong>:<strong>~/</strong>$nano /etc/systemd/system/jupyter.services</pre><pre>[Unit]<br>Description=Jupyter Notebook</pre><pre>[Service]<br>Type=simple<br>PIDFile=/run/jupyter.pid<br>ExecStart=/bin/bash -c &quot;. /home/sysadmin/anaconda3/bin/activate;jupyter-notebook&quot;<br>User=sysadmin<br>Group=sysadmin<br>WorkingDirectory=/home/sysadmin/data<br>Restart=always<br>RestartSec=10</pre><pre>[Install]<br>WantedBy=multi-user.target</pre><p>Now enabled the service as below:</p><pre><strong>sysadmin@ds</strong>:<strong>~/</strong>$sudo systemctl enable jupyter.services</pre><pre><strong>sysadmin@ds</strong>:<strong>~/</strong>$sudo systemctl daemon-reload</pre><pre><strong>sysadmin@ds</strong>:<strong>~/</strong>$sudo systemctl restart jupyter.services</pre><p>The service is started now. You can test it as below:</p><pre><strong>sysadmin@ds</strong>:<strong>~/</strong>$systemctl -a | grep jupyter<br> jupyter.services      loaded active running Jupyter Notebook</pre><p>Now, Jupyter Notebook can be accessed via the Internet! ! !</p><p>Thanks for reading! If you enjoyed the post, please appreciate your support by applauding via the clap (👏🏼) button below or by sharing this article so others can find it.</p><p>Reference:</p><ul><li><a href="https://medium.com/@joelzhang/setting-up-jupyter-notebook-server-as-service-in-ubuntu-16-04-116cf8e84781">Setting up jupyter notebook server as service in Ubuntu 16.04</a></li><li><a href="https://medium.com/@maniac.tw/ubuntu-18-04-%E5%AE%89%E8%A3%9D-nvidia-driver-418-cuda-10-tensorflow-1-13-a4f1c71dd8e5">Ubuntu 18.04 安裝 NVIDIA Driver 418 &amp; CUDA 10 &amp; TensorFlow 1.13</a></li><li><a href="https://www.tensorflow.org/install/gpu#software_requirements">GPU support | TensorFlow</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=330805898d08" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/how-to-run-a-data-science-project-with-gpu-on-an-old-computer-330805898d08">How to run a data science project with GPU on an old computer</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>