<?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 Karan Choudhary on Medium]]></title>
        <description><![CDATA[Stories by Karan Choudhary on Medium]]></description>
        <link>https://medium.com/@karan18csu103?source=rss-c6b7aa233755------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GyaDDh6DZhB8lZOVMF0eJw.jpeg</url>
            <title>Stories by Karan Choudhary on Medium</title>
            <link>https://medium.com/@karan18csu103?source=rss-c6b7aa233755------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 03:23:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@karan18csu103/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[Spring Boot Tutorial With Project |Part 1]]></title>
            <link>https://medium.com/analytics-vidhya/spring-boot-tutorial-with-project-part-1-35a9d29bd0ae?source=rss-c6b7aa233755------2</link>
            <guid isPermaLink="false">https://medium.com/p/35a9d29bd0ae</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[swagger]]></category>
            <category><![CDATA[spring-training]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Karan Choudhary]]></dc:creator>
            <pubDate>Sat, 03 Dec 2022 18:22:21 GMT</pubDate>
            <atom:updated>2022-12-03T18:25:18.893Z</atom:updated>
            <content:encoded><![CDATA[<p>We’ll learn everything there is to know about the Spring Boot framework for Java developers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*DfG8LhiBw1v8ZePLj0b2uQ.jpeg" /></figure><p>We’ll build a spring boot project in this tutorial that has CRUD (Create, Read/Retrieve, Update, Delete) APIs. We’re going to connect to a real database and use three layers in this system, and we’ll see how it works.</p><p>For those who want to use Java to create back-end or full-stack apps, Spring Boot is an excellent framework.</p><p>Now we are ready to create an application which consists of various Entity , various variable and inter-relation between them.</p><h3>Project <strong><em>Architecture</em></strong></h3><p><strong>Controller -&gt; Service -&gt; Repository -&gt;Database</strong></p><p>Our REST APIs will be in the controller. Business logic will be present in the Service Layer. Repository(DAO) layer will have logic to communicate with the database.</p><p>Now that we have a project structure, let’s construct a package. We’ll develop layers for the controller , entity, services, and repositories.</p><p>In this tutorial we are learning an <strong>Blog Application</strong> which based on web and for that we are using java language ,Springboot as a framework and for database connectivity we have Mysql. Now lets with the basic creating Architectureof application for that we start with entites for application <strong>User,Post,Role,Category,Comment</strong> will be our 5 entity for our project. Which have there own variables in it and they connected with each other with help of some relation.</p><p>Our first entity will be User which consists of id , name , e-mail, password and about user .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*kcCP-1-EPGErVuZIw0F9mg.png" /></figure><p>Our second entity will be <strong>Category</strong> which consists of <strong>CategoryId</strong> and <strong>category description</strong> .This entity will help us to know about the blog category which help user to distinguish what category user is in interseted to read articles/blogs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T2NZZt0qS8HsC72WXExRHw.png" /></figure><p>Next entity is <strong>Post </strong>which help user to upload any post related to his/her content he wants to publish on application. It consists of<strong> title , content, imageName, addedDate </strong>which help us to maintain record of user and its content uploaded by them on application<strong>.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RpwhfRchGZyQswbQs_9o8w.png" /></figure><p>Next entity will be <strong>Role</strong> which is based on role based in application such as <strong>admin, premium user ,non-premium user</strong>. <strong>Role</strong> enitiy consists of <strong>id </strong>and<strong> name.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*CO9mVWvWRlQtxDHSMJNoow.png" /></figure><p>Next enitity will be comment which are based on post an user is posting it can have Multiple comments to maintain that we have created an seperate entity which have unique id based on post and content written in it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*SXNrm23_e2xxTwGC8E8lIg.png" /></figure><p>I have build this in an particular package on our project to avoid any confusion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/186/1*FGM7mGyGKu5nZMeEZEwOgQ.png" /></figure><p>Blog Application ER model .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*MopXDA3tT8EqNAiuDT2umQ.png" /></figure><p>We will start developing project further in next part .If you like to read these kind of tutorial and have common interest in similar projects then we can grow our network and can work for more real time projects.</p><p>For more details connect with me on my <a href="https://www.linkedin.com/in/karan-choudhary-9102b81a0/"><strong>Linkedin account</strong></a><strong><em>!</em></strong></p><p><strong>THANKS!!!!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35a9d29bd0ae" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/spring-boot-tutorial-with-project-part-1-35a9d29bd0ae">Spring Boot Tutorial With Project |Part 1</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[BUILDING RECOMMENDED SYSTEM USING PYSPARK WITH ALS ALGORITHM]]></title>
            <link>https://medium.com/swlh/building-recommended-system-using-pyspark-with-als-algorithm-34fd265fa90c?source=rss-c6b7aa233755------2</link>
            <guid isPermaLink="false">https://medium.com/p/34fd265fa90c</guid>
            <category><![CDATA[recommendations]]></category>
            <category><![CDATA[als]]></category>
            <category><![CDATA[bigdatacourse]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[Karan Choudhary]]></dc:creator>
            <pubDate>Thu, 26 Nov 2020 05:53:04 GMT</pubDate>
            <atom:updated>2020-11-26T05:53:04.774Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/376/0*fHD6tZHXusUUluEz.png" /></figure><p>Recommender System is an information filtering tool that seeks to predict which product a user will like, and based on that, recommends a few products to the users. For example, Amazon can recommend new shopping items to buy, Netflix can recommend new movies to watch, and Google can recommend news that a user might be interested in. The two widely used approaches for building a recommender system are the content-based filtering (CBF) and collaborative filtering (CF).</p><p>Majorly we have 3 types of recommended system : -</p><ul><li>Collaborative Filtering</li><li>Content-Based Filtering</li><li>Hybrid Recommendation Systems</li></ul><p><strong>Collaborative Filtering</strong></p><p>Collaborative filtering methods are based on collecting and analyzing a large amount of information on users’ behaviors, activities or preferences and predicting what users will like based on their similarity to other users. A key advantage of the collaborative filtering approach is that it does not rely on machine analyzable content and therefore it is capable of accurately recommending complex items such as movies without requiring an “understanding” of the item itself. Many algorithms have been used in measuring user similarity or item similarity in recommender systems. For example, the k-nearest neighbor (k-NN) approach and the Pearson Correlation.</p><p><strong>Content Based Filtering</strong></p><p>Content-based filtering methods are based on a description of the item and a profile of the user’s preference. In a content-based recommendation system, keywords are used to describe the items; beside, a user profile is built to indicate the type of item this user likes. In other words, these algorithms try to recommend items that are similar to those that a user liked in the past (or is examining in the present). In particular, various candidate items are compared with items previously rated by the user and the best-matching items are recommended. This approach has its roots in information retrieval and information filtering research.</p><p><strong>Hybrid Recommendation Systems</strong></p><p>Recent research has demonstrated that a hybrid approach, combining collaborative filtering and content-based filtering could be more effective in some cases. Hybrid approaches can be implemented in several ways, by making content-based and collaborative-based predictions separately and then combining them, by adding content-based capabilities to a collaborative-based approach (and vice versa), or by unifying the approaches into one model. Several studies empirically compare the performance of the hybrid with the pure collaborative and content-based methods and demonstrate that the hybrid methods can provide more accurate recommendations than pure approaches. These methods can also be used to overcome some of the common problems in recommendation systems such as cold start and the sparsity problem.</p><p><a href="https://dataconomy.com/netflixs-vision-future-personalising-channels-shows/">Netflix is a good example of a hybrid system.</a> They make recommendations by comparing the watching and searching habits of similar users (i.e. collaborative filtering) as well as by offering movies that share characteristics with films that a user has rated highly (content-based filtering).</p><p>#before starting of the notebook we will familiar with the data.</p><p>MOVIELENS_RATING.CSV</p><p>in this data we have movie_id ,rating and user_id.</p><p>movie_id refers to the id of the spaefic movie user watched.</p><p>rating is from 1.0 to 5.0 given by user.</p><p>user_id refers to the id to the particular user.</p><p>#we will be implementing the code in google colab before starting o f the code let’s go for installation of pyspark library.</p><blockquote>!pip install pyspark</blockquote><p>#then we will start of the new sparksession which helps to make the model in it is one of the basic steps in executing the model.</p><blockquote>from pyspark.sql import SparkSession</blockquote><p># now we will go for making the app builder in the sparksession</p><blockquote>spark = SparkSession.builder.appName(‘rec_sys’).getOrCreate()</blockquote><p>#now we will start the session by importing the dataset</p><blockquote>data=spark.read.csv(‘movielens_ratings.csv’,inferSchema=True,header=True)</blockquote><blockquote>data.show(5)</blockquote><p>#now we will be implementing the printschema to show the deafult schema by spark session.</p><blockquote>data.printSchema()</blockquote><p>root</p><p>| — movieId: integer (nullable = true)</p><p>| — rating: double (nullable = true)</p><p>| — userId: integer (nullable = true)</p><p># now we will showing the describe function to make data undertable</p><blockquote>data.describe().show()</blockquote><p># Build the recommendation model using ALS on the training data</p><p># Smaller dataset so we will use 0.8 / 0.2</p><blockquote>(training, test) = data.randomSplit([0.8, 0.2])</blockquote><blockquote>from pyspark.ml.evaluation import RegressionEvaluator</blockquote><blockquote>from pyspark.ml.recommendation import ALS</blockquote><blockquote>als = ALS(maxIter=2, regParam=0.01, userCol=”userId”, itemCol=”movieId”, ratingCol=”rating”)</blockquote><blockquote>model = als.fit(training)</blockquote><p># these above are the parameters of the ALS model with the userCol,itemCol,ratingCol wih the specific iteration.</p><p>#then we will be implementing them on the test data through transformation</p><blockquote>predictions = model.transform(test)</blockquote><p>#then we will see the prediction about the single user for the testing and the predicition according to the model.</p><p># we will be evaluating the model on the basis of rmse ,r2,mae value’s .</p><blockquote>evaluator = RegressionEvaluator(metricName=”rmse”, labelCol=”rating”,predictionCol=”prediction”)</blockquote><blockquote>rmse = evaluator.evaluate(predictions)</blockquote><blockquote>print(“Root-mean-square error = “ + str(rmse))</blockquote><blockquote>evaluator = RegressionEvaluator(metricName=”r2&quot;, labelCol=”rating”,predictionCol=”prediction”)</blockquote><blockquote>r2 = evaluator.evaluate(predictions)</blockquote><blockquote>print(“r2= “ + str(r2))</blockquote><blockquote>evaluator = RegressionEvaluator(metricName=”mae”, labelCol=”rating”,predictionCol=”prediction”)</blockquote><blockquote>mae = evaluator.evaluate(predictions)</blockquote><blockquote>print(“mean absolute error = “ + str(mae))</blockquote><p># then for single user we will be implementing them on</p><blockquote>single_user=test.filter(test[‘userId’]==20).select([‘movieId’,’userId’,’rating’])</blockquote><blockquote>single_user.show(5)</blockquote><blockquote>reccomendations = model.transform(single_user)</blockquote><blockquote>reccomendations.sort(‘prediction’,ascen=True).show(5)</blockquote><p>HERE ARE THE SCREENSHOTS OF THE CODE</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mPQDRJw_X56xHrPc_bmb0w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bmYOLKVGIWDBvjZTRcxCWA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gOuhpfSalQpwKWo1FbaAmg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sEKW9CEkGmQsnFhORVU08A.png" /></figure><p>If u like to read this article and have common interest in similar projects then we can grow our network and can work for more real time projects.</p><p>For more details connect with me on my <a href="https://www.linkedin.com/in/karan-choudhary-9102b81a0/"><strong>Linkedin account</strong></a><strong><em>!</em></strong></p><p><strong>THANKS!!!!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34fd265fa90c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/building-recommended-system-using-pyspark-with-als-algorithm-34fd265fa90c">BUILDING RECOMMENDED SYSTEM USING PYSPARK WITH ALS ALGORITHM</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Big Data using pyspark in Databricks]]></title>
            <link>https://medium.datadriveninvestor.com/big-data-using-pyspark-in-databricks-7d399a860347?source=rss-c6b7aa233755------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d399a860347</guid>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Karan Choudhary]]></dc:creator>
            <pubDate>Sat, 14 Nov 2020 10:12:46 GMT</pubDate>
            <atom:updated>2020-11-20T03:24:55.414Z</atom:updated>
            <content:encoded><![CDATA[<p>Implementation of linear regression through pyspark library in Databricks. before starting of the implementation we must familiar to the databricks platform.</p><p>This is the homepage of the databricks developed specially for spark to implement on it and its is cost free. Before starting of the session we have to make cluster and then for properties of the cluster in terms of their ram and other requirements based on the workspace you want to do</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u4We4Cdcdae1SVtt6uSBIA.png" /></figure><p>In Databricks we can apply spark RDD’s , SQl , MLIB , graphX . This is one of the best platform to learn spark without any requirements of the local system.</p><p>we will be implementing linear regression here on the dataset before this we will be uploading file here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y_wEMLRtRqIccR6EubMjYg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xhv7rl1N50dEcSk48JXXlw.png" /></figure><p>click data icon and then browse file and select the file you want to upload and by click file gets Uploaded EC.CSV file gets uploaded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DZn_HOt7yOpJCpo7qs2iTA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EuCOW4bvkiaw4v9sRDETuQ.png" /></figure><p>Now we will form cluster to make a file so we will click on cluster icon and then we have option of create cluster click on it and then we will go to name of the cluster we want to set karan_first_cluster and other requirements and then we will go to create cluster button.</p><p>Before implementing code we will go to theory of linear regression and how it works.</p><p>Linear regression is a technique used to model the relationships between observed variables. The idea behind simple linear regression is to “fit” the observations of two variables into a linear relationship between them. Graphically, the task is to draw the line that is “best-fitting” or “closest” to the points (x_i,y_i),(<em>xi</em>​,<em>yi</em>​), where x_i<em>xi</em>​ and y_i<em>yi</em>​ are observations of the two variables which are expected to depend linearly on each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/0*5_fw53Sey9f62BXC" /></figure><p><em>The best-fitting linear relationship between the variables </em>x<em>x and yy.</em></p><p>Regression is a common process used in many applications of statistics in the real world. There are two main types of applications:</p><ul><li>Predictions: After a series of observations of variables, regression analysis gives a statistical model for the relationship between the variables. This model can be used to generate predictions: given two variables x<em>x</em> and y,<em>y</em>, the model can predict values of y<em>y</em> given future observations of x.<em>x</em>. This idea is used to predict variables in countless situations, e.g. the outcome of political elections, the behavior of the stock market, or the performance of a professional athlete.</li><li>Correlation: The model given by a regression analysis will often fit some kinds of data better than others. This can be used to analyze correlations between variables and to refine a statistical model to incorporate further inputs: if the model describes certain subsets of the data points very well, but is a poor predictor for other data points, it can be instructive to examine the differences between the different types of data points for a possible explanation. This type of application is common in scientific tests, e.g. of the effects of a proposed drug on the patients in a controlled study.</li></ul><p>Although many measures of best fit are possible, for most applications the best-fitting line is found using the method of least squares . That is, viewing y<em>y</em> as a linear function of x,<em>x</em>, the method finds the linear function L<em>L</em> which minimizes the sum of the squares of the errors .</p><p>After creating cluster and uploading file we will come back to the home page and then create new notebook .</p><blockquote>we will first import the pyspark libraray.</blockquote><blockquote>import pyspark</blockquote><blockquote>from pyspark.sql import SparkSession</blockquote><blockquote>spark=SparkSession.builder.appName(‘LINEAR_REGRESSION_KARAN_FIRSTFILE’).getOrCreate()</blockquote><p>App builder is for the making an new app for the process to create and then we will go for the new sparksession .</p><p>now we will import the dataset through cmmd.</p><blockquote>from pyspark.ml.regression import LinearRegression<br>data_EC =spark.read.csv(“dbfs:/FileStore/tables/EC.csv”,inferSchema=True,header=True)</blockquote><p>here is the screenshort of the commands which we have applied.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KQ8wf6QakCMGCDAVz3VtlA.png" /></figure><blockquote>#now we will print schema and hen we will be implemntaing the correlation between each independent to dependent features.</blockquote><blockquote>from pyspark.sql.functions import corr<br>print(data_EC.corr(‘Time on App’,’Time on Website’))</blockquote><blockquote>print(data_EC.corr(‘Time on App’,’Yearly Amount Spent’))</blockquote><p>#ouput</p><p>0.0823882731909817</p><p>0.4993277700534503</p><p>#now we will be creating a vector of the independent variables in a vector storing row wise value in it so we then make a better prediction.</p><blockquote>#converting the vectors having value of numericals in to a vector<br>from pyspark.ml.linalg import Vectors<br>from pyspark.ml.feature import VectorAssembler</blockquote><blockquote>#taking the numerical value from the dataset and then come across the last 5 columns<br>assembler=VectorAssembler(inputCols=[ ‘Avg Session Length’,’Time on App’,’Time on Website’,’Length of Membership’],outputCol=’features’)</blockquote><blockquote>assembler</blockquote><p>#converting all these features into a feature [<strong>‘Avg Session Length’,’Time on App’,’Time on Website’,’Length of Membership]</strong></p><p>output=assembler.transform(data_EC)</p><blockquote>#then prediciting the faetures to the depenedent variable</blockquote><blockquote>#we can see the dense vector which will combination of vector of the ‘Avg Session Length’,’Time on App’,’Time on Website’,’Length of Membership’<br>#now we will predict the multilinear regression here and then classify it<br>final_data=output.select(‘features’,’Yearly Amount Spent’)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J5YbTAEIE-j0wc_Mz1m3BA.png" /></figure><blockquote>#splitting the fdata into train and test<br>train_split,test_split=final_data.randomSplit([0.7,0.3])</blockquote><p>70/30 ratio splait data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M9rpupCX3YAh2iWvvumfJA.png" /></figure><p>Making the linear regression model and then predicitng residuals.</p><blockquote>lr=LinearRegression(labelCol=’Yearly Amount Spent’)<br>lr_model=lr.fit(train_split)<br>lr_model</blockquote><p>LinearRegressionModel: uid=LinearRegression_89496b266f8f, numFeatures=4</p><blockquote>#error for the actual -predicted of each row<br>test_results=lr_model.evaluate(test_split)<br>#residuels refer to the actual -predicted <br>test_results.residuals.show()</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P_LhhbyOzp6-WZ34n_eWSg.png" /></figure><p>here is the end of the linear regression and we will be making the files save to format as if cluster died aur data will be erased from it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pAYA93kTY7sGZpQgyCmHYw.png" /></figure><p>In various format we can print it and then we will make a launch to it.</p><p>All the viewers can access the code through drive link and if u find the article intersting do comment on it.</p><p><a href="https://drive.google.com/drive/folders/1mWmvpINd05_n2DKLtPJiyjA94PSNX0Cu?usp=sharing">https://drive.google.com/drive/folders/1mWmvpINd05_n2DKLtPJiyjA94PSNX0Cu?usp=sharing</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d399a860347" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/big-data-using-pyspark-in-databricks-7d399a860347">Big Data using pyspark in Databricks</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FEATURE SELECTION ONE OF THE MOST TIME CONSUMING TOPIC IN DATA SCIENCE PROFESSION]]></title>
            <link>https://medium.com/swlh/feature-selection-one-of-the-most-time-consuming-topic-in-data-science-profession-1f294a4d9b7b?source=rss-c6b7aa233755------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f294a4d9b7b</guid>
            <category><![CDATA[datascience-training]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <dc:creator><![CDATA[Karan Choudhary]]></dc:creator>
            <pubDate>Sun, 25 Oct 2020 18:58:59 GMT</pubDate>
            <atom:updated>2020-10-25T19:04:03.277Z</atom:updated>
            <content:encoded><![CDATA[<p>FEATURE SELECTION TECNIQUES<br>1.variance threshold <br> →constant <br> →quasi constant <br> →duplicate features<br>2.fisher score<br>3.chi-square test<br>4.mutual information</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*qJt7wbAFC3ITB34mhc0g7Q.png" /></figure><p># In[1]:</p><p>#importig the libararies<br>import pandas as pd<br>import numpy as np</p><p># In[2]:</p><p>bc_data=pd.read_csv(‘breast_cancer.csv’)</p><p># In[8]:</p><p>bc_data.head()</p><p># In[10]:</p><p>bc_data.shape</p><p># In[5]:</p><p>bc_data.columns</p><p># In[6]:</p><p>bc_data.info()</p><p># In[7]:</p><p>bc_data.corr()</p><p># In[11]:</p><p>X=bc_data.drop(labels=[‘diagnosis’],axis=1)<br>y=bc_data[‘diagnosis’]</p><p># In[13]:</p><p>X.shape</p><p># In[15]:</p><p>y.shape</p><p># In[16]:</p><p>#splitting the data into graining ad testing <br>from sklearn.model_selection import train_test_split<br>X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.4,random_state=0)</p><p># In[22]:</p><p>#shape of raining and testing will be<br>print(‘Independent variable \nTraining -&gt;’,X_train.shape,”Testing -&gt;”,X_test.shape)<br>print(‘Dependent variable \nTraining -&gt;’,y_train.shape,”Testing -&gt;”,y_test.shape)</p><p># In[24]:</p><p>#1.VARIANCE THRESHOLD METHOD</p><p># In[25]:</p><p>#Removing The constant features<br>from sklearn.feature_selection import VarianceThreshold</p><p># In[28]:</p><p>V_thr = VarianceThreshold(threshold=0)<br>V_thr.fit(X_train)</p><p># In[29]:</p><p>V_thr.get_support()</p><p># In[30]:</p><p>sum(V_thr.get_support())</p><p># In[32]:</p><p>constant_columns=[col for col in X_train.columns<br> if col not in X_train.columns[V_thr.get_support()]]</p><p># In[33]:</p><p>constant_columns</p><p># In[ ]:</p><p># #From this constant coloums variable we come to know about that our dataset doesnt contain any constant features</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CkZt_Xpiedvk6a660lVN6w.png" /></figure><p># 2. Removing Quasi-constant features</p><p># In[115]:</p><p># Quasi-Constant features<br>var_thresh=VarianceThreshold(threshold=0.15)<br>var_thresh.fit(X_train)</p><p># In[116]:</p><p>var_thresh.get_support()</p><p># In[117]:</p><p>sum(var_thresh.get_support())</p><p># In[118]:</p><p>q_constant_cols=[column for column in X_train.columns<br> if column not in X_train.columns[var_thresh.get_support()]]</p><p># In[119]:</p><p>q_constant_cols</p><p># In[120]:</p><p>len(X_train.columns[var_thresh.get_support()])</p><p># In[121]:</p><p>len(q_constant_cols)</p><p># # 3. Remove Duplicated Features</p><p># In[123]:</p><p>dup_data = X_train.T<br>dup_data.head()</p><p># In[ ]:</p><p>dup_data.duplicated().sum()</p><p>#</p><p># In[129]:</p><p>dup_data[dup_data.duplicated()]</p><p># In[131]:</p><p>dup_data.duplicated().sum()</p><p># In[130]:</p><p># checking duplicates in this we find it to be zero</p><p># # ChiAquare</p><p># In[132]:</p><p>from sklearn.feature_selection import SelectKBest<br>from sklearn.feature_selection import chi2</p><p># In[147]:</p><p>features=SelectKBest(score_func=chi2,k=15)</p><p># In[148]:</p><p>features</p><p># In[149]:</p><p>rank=ordered_features.fit(X_train,y_train)</p><p># In[150]:</p><p>rank</p><p># In[151]:</p><p>df_scores=pd.DataFrame(ordered_rank.scores_,columns=[‘Score’])<br>dfcols=pd.DataFrame(X_train.columns)</p><p># In[152]:</p><p>dfcols</p><p># In[153]:</p><p>features_rank=pd.concat([dfcols,df_scores],axis=1)</p><p># In[155]:</p><p>features_rank.columns=[‘Features’,’Score’]<br>features_rank.nlargest(5,’Score’)</p><p># In[163]:</p><p>ranked_features=pd.Series(ordered_rank.scores_,index=X_train.columns)<br>ranked_features.nlargest(5).plot(kind=’bar’,color=”green”,figsize=(10,10))<br>plt.show()</p><p># In[181]:</p><p>#fisher score</p><p># In[183]:</p><p>#importing dataset<br>dataset=pd.read_csv(‘breast_cancer_data.csv’)<br>from sklearn import preprocessing <br> <br># label_encoder object knows how to understand word labels. <br>label_encoder = preprocessing.LabelEncoder() <br> <br># Encode labels in column ‘species’. <br>dataset[‘diagnosis’]= label_encoder.fit_transform(dataset[‘diagnosis’]) <br> <br>dataset[‘diagnosis’].unique()</p><p># In[184]:</p><p># using fisher man algorithm<br>#we will doing an them</p><p>def fisher_man_score(attribute_name):<br> mean_fields=[]<br> variance=[]<br> for k in range(0,2): # 0,2 refers here about the class of diagonisis M or B<br> data=dataset[dataset[‘diagnosis’]== k]<br> mean_fields.append(df[attribute_name].mean())<br> variance.append(df[attribute_name].var())<br> fisher=((mean_fields[0]-mean_fields[1])**2)/(var[0]+var[1])<br> return fisher</p><p># In[191]:</p><p>fisher_1=[]<br>for i in list (dataset.columns):<br> fisher_1[i]=fisher_man_score[i]<br> print(i,” — — →&gt;”,fisher_1[i])</p><p># # MUTUAL INFO</p><p># In[166]:</p><p>from sklearn.feature_selection import mutual_info_classif<br>mutual_data=mutual_info_classif(X,y)</p><p># In[167]:</p><p>mutual_info=pd.Series(mutual_data,index=X.columns)</p><p># In[173]:</p><p>mutual_info[:10]</p><p># In[180]:</p><p>mutual_info.nlargest(5)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f294a4d9b7b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/feature-selection-one-of-the-most-time-consuming-topic-in-data-science-profession-1f294a4d9b7b">FEATURE SELECTION ONE OF THE MOST TIME CONSUMING TOPIC IN DATA SCIENCE PROFESSION</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BIGDATA MRJOB AND PIG LATIN SCRIPTS]]></title>
            <link>https://medium.com/swlh/bigdata-mrjob-and-pig-latin-scripts-43476dca8c60?source=rss-c6b7aa233755------2</link>
            <guid isPermaLink="false">https://medium.com/p/43476dca8c60</guid>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[datascience-training]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Karan Choudhary]]></dc:creator>
            <pubDate>Fri, 09 Oct 2020 10:54:26 GMT</pubDate>
            <atom:updated>2020-10-09T10:54:26.630Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TJaZJoyL5ENSN6naRJuBMA.jpeg" /></figure><p>Create two data files with names and datasets as shown below and then implement the following queries using mrjob package in python for map reduce programming and using pigalso for the same.Compare the two processing types.</p><p>We have dataset of employee and expenses in form of txt</p><p>Employee.txt</p><blockquote>101,Abhay,20000,1</blockquote><blockquote>102,Shiv,10000,2</blockquote><blockquote>103,Aarav,11000,3</blockquote><blockquote>104,Anubhav,5000,4</blockquote><blockquote>105,Palash,2500,5</blockquote><blockquote>106,Aman,25000,1</blockquote><blockquote>107,Sahil,17500,2</blockquote><blockquote>108,Ram,14000,3</blockquote><blockquote>109,Karan,1000,4</blockquote><blockquote>110,Priya,2000,5</blockquote><blockquote>111,Tushar,500,1</blockquote><blockquote>112,Ajay,5000,2</blockquote><blockquote>113,Jay,1000,1</blockquote><blockquote>114,Maddy,2000,2</blockquote><p>Expenses.txt</p><blockquote>101,200</blockquote><blockquote>102,100</blockquote><blockquote>110,400</blockquote><blockquote>114,200</blockquote><blockquote>119,200</blockquote><blockquote>105,100</blockquote><blockquote>101,100</blockquote><blockquote>104,300</blockquote><blockquote>102,300</blockquote><p>Q1 Top 5 employees (employeeid and employee name) with highest rating. (In casetwoemployees have same rating, employee with name coming first in dictionary shouldgetpreference).</p><p>MRJOB COMMANDS</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*gnJqHvPykGfUgU_mmYIg5A.png" /></figure><p>PIG LATIN COMMANDS</p><p>employee_info = LOAD ‘gs://piglatinquery/employee.txt’ USING PigStorage(‘,’) AS (emp_id:int,emp_name:chararray,emp_salary:int,emp_rating:int);</p><p>Emp_desc_sort = ORDER employee_info BY emp_rating DESC; //sort in descending order</p><p>Emp_top_5 = LIMIT Emp_desc_sort 5; //top 5 emp with rating</p><p>employees_id_name = FOREACH top_5_employees GENERATE emp_id, emp_name;</p><p>DUMP employees_id_name;</p><p>OUTPUT</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*s7d101Ez2oSZexolkQzN6A.png" /></figure><p>Q2 Top 3 employees (employee id and employee name) with highest salary, whoseemployee idis an odd number. (In case two employees have same salary, employee with namecoming firstin dictionary should get preference)</p><p>MRJOB</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*bhm0rTs3akmyjYD7zIHD7A.png" /></figure><p>PIG LATIN COMMAND</p><p>employee_info = LOAD ‘gs://piglatinquery/employee.txt’ USING PigStorage(‘,’) AS (emp_id:int,emp_name:chararray,emp_salary:int,emp_rating:int);</p><p>odd_emp_id = FILTER employee_info BY emp_id%2 == 1; //for checking odd condition</p><p>emp_sort_salary = ORDER odd_emp_id BY emp_salary DESC; //sorting descending salary</p><p>Sal_top3_emp = LIMIT emp_sort_salary 3; //printing the salry of first 3 emp</p><p>Dump Sal_top3_emp;</p><p>OUTPUT</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*FRv6Ys_oCIj4SNwRhmFHnQ.png" /></figure><p>Q3</p><p>Employee (employee id and employee name) with maximum expense (In casetwoemployees have same expense, employee with name coming first in dictionaryshould getpreference).</p><p>MRJOB</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*Pn0bvAUjomwClJV6gxNhuw.png" /></figure><p>PIG LATIN COMMANDS</p><p>employee_info = LOAD ‘gs://piglatinquery/employee.txt’ USING PigStorage(‘,’) AS (emp_id:int,emp_name:chararray,emp_salary:int,emp_rating:int);</p><p>emp_expenses = LOAD ‘employee_expenses.txt’ AS (emp_id:int, expense:int);</p><p>Join_emp = JOIN employee_info BY emp_id, emp_expenses BY emp_id;</p><p>grouped_emp_info = GROUP Join_emp ALL;</p><p>max_expense = FOREACH emp_info GENERATE MAX (Join_emp. emp_expenses::emp_expense) AS expense;</p><p>max_expense_emp = FILTER Join_emp BY emp_expenses::expense == max_expense.expense;</p><p>DUMP max_expense_emp;</p><p>OUTPUT</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*vcdELcBiT39w4zHpTT507w.png" /></figure><p>Q4List of employees (employee id and employee name) having entries in expenses.txt.</p><p>MRJOB</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*9hWdYYVqQemtgQP7TZuL_g.png" /></figure><p>PIG ATIN COMMANDS</p><p>employee_info = LOAD ‘gs://piglatinquery/employee.txt’ USING PigStorage(‘,’) AS (emp_id:int,emp_name:chararray,emp_salary:int,emp_rating:int);</p><p>emp_expenses = LOAD ‘employee_expenses.txt’ AS (emp_id:int, expense:int);</p><p>JOIN= JOIN employee_info BY emp_id, emp_expenses BY emp_id;</p><p>emp_information = FOREACH JOIN GENERATE emp_info::emp_id, employee_details::emp_name;</p><p>final_join = DISTINCT emp_information; //UNIQUE</p><p>DUMP final_join;</p><p>OUTPUT</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*uSu59C2lYt2ZrTBqir5V9A.png" /></figure><p>Q 5.List of employees (employee id and employee name) having no entry in expenses.txt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*zBHL1dRtmfNYwR3aW8nV9g.png" /></figure><p>employee_info = LOAD ‘gs://piglatinquery/employee.txt’ USING PigStorage(‘,’) AS (emp_id:int,emp_name:chararray,emp_salary:int,emp_rating:int);</p><p>emp_details_LEFTJOIN = JOIN employee_info BY emp_id LEFT OUTER, emp_expenses BY emp_id;</p><p>JOIN_details = FILTER emp_details_LEFTJOIN BY emp_expenses::emp_id IS NULL;</p><p>emp_details= FOREACH JOIN_ details GENERATE employee_info:: emp_id, employee_info::emp_name;</p><p>DUMP emp_details;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*TiHuv88226ORRL5q39EdVw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43476dca8c60" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/bigdata-mrjob-and-pig-latin-scripts-43476dca8c60">BIGDATA MRJOB AND PIG LATIN SCRIPTS</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[END TO END DEPLOYMENT OF HEART DISEASE PREDICTION USING FLASK (Detailed Explanation)]]></title>
            <link>https://medium.datadriveninvestor.com/end-to-end-deployment-of-heart-disease-prediction-using-flask-detailed-explanation-1b07ac961c3b?source=rss-c6b7aa233755------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b07ac961c3b</guid>
            <category><![CDATA[heart-disease]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[machinelerning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[medical-devices]]></category>
            <dc:creator><![CDATA[Karan Choudhary]]></dc:creator>
            <pubDate>Wed, 07 Oct 2020 19:53:54 GMT</pubDate>
            <atom:updated>2020-10-10T14:10:27.512Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*2hGJJJIxDp882fkD-4PZUg.jpeg" /></figure><p>Importing the libraries.</p><p>import numpy as np</p><p>import pandas as pd</p><p>import matplotlib.pyplot as plt</p><p>Reading the dataset</p><p>df = pd.read_csv(“heart.csv”)</p><p>df.head() #printing the all the columns with first 5 rows</p><p>Dataset with independent and dependent variables.</p><p>age</p><p>age in years</p><p>Independent Variable</p><p>sex</p><p>(1 = male; 0 = female)</p><p>Independent Variable</p><p>cp</p><p>chest pain type</p><p>Independent Variable</p><p>trestbps</p><p>resting blood pressure (in mm Hg on admission to the hospital)</p><p>Independent Variable</p><p>chol</p><p>serum cholestoral in mg/dl</p><p>Independent Variable</p><p>fbs</p><p>(fasting blood sugar &gt; 120 mg/dl) (1 = true; 0 = false)</p><p>Independent Variable</p><p>restecg</p><p>resting electrocardiographic results</p><p>Independent Variable</p><p>thalach</p><p>maximum heart rate achieved</p><p>Independent Variable</p><p>exang</p><p>exercise induced angina (1 = yes; 0 = no)</p><p>Independent Variable</p><p>oldpeak</p><p>ST depression induced by exercise relative to rest</p><p>Independent Variable</p><p>slope</p><p>the slope of the peak exercise ST segment</p><p>Independent Variable</p><p>ca</p><p>number of major vessels (0,3) colored by flourosopy</p><p>Independent Variable</p><p>thal</p><p>3 = normal; 6 = fixed defect; 7 = reversable defect</p><p>Independent Variable</p><p>target</p><p>have disease or not (1=yes, 0=no)</p><p>Dependent Variable</p><p>For Data Analysis we have to go for Explore.</p><p>From this we come to analysis that we have well defined distributed dependent variable(target).</p><p>df.target.value_counts()</p><p>1 165</p><p>0 138</p><p>For further analysis we are checking the age how data is distributed according to the dependent variable.</p><p>#We come to conclusion that our data is well distributed along age’s</p><p>pd.crosstab(df.age,df.target).plot(kind=”bar”)</p><p>plt.title(‘Heart Disease Frequency for Ages’)</p><p>plt.xlabel(‘Age’)</p><p>plt.ylabel(‘Frequency’)</p><p>plt.show()</p><p>Now we have to analysis that the people age’s having heart problem or not according to gender(F/M).</p><pre>pd.crosstab(df.sex,df.target).plot(kind=&quot;bar&quot;,figsize=(15,6))</pre><pre>plt.title(&#39;Heart Disease Frequency for Sex&#39;)</pre><pre>plt.xlabel(&#39;Sex (0 = Female, 1 = Male)&#39;)</pre><pre>plt.xticks(rotation=0)</pre><pre>plt.legend([&quot;Haven&#39;t Disease&quot;, &quot;Have Disease&quot;])</pre><pre>plt.ylabel(&#39;Frequency&#39;)</pre><pre>plt.show()</pre><p>From above analysis we got an rough idea about dataset and then we will have to make relationship between the independent and dependent variables for further analysis.</p><pre>corr = df.corr()</pre><pre>plt.figure(figsize=(18,10))</pre><pre>sns.heatmap(corr, annot=True)</pre><pre>plt.show()</pre><p>We can conclude that <strong>cp,thalach</strong> has maximum relation to the target (dependent variable).</p><p>Droping the target (dependent variable) and assigning target to new variable.</p><pre>from sklearn.preprocessing import StandardScaler</pre><pre>from sklearn.model_selection import train_test_split</pre><pre>from sklearn.model_selection import cross_val_score</pre><pre>from sklearn.metrics import accuracy_score, confusion_matrix</pre><pre>X = df.drop([&#39;target&#39;], axis=1).values</pre><pre>y = df[&#39;target&#39;].values</pre><p>Standard Scaling technique where the values are centered around the mean with a unit standard deviation. This means that the mean of the attribute becomes zero and the resultant distribution has a unit standard deviation from [-1, +1] and it makes our independent variable equally important to the data for prediction for target.</p><pre>scale = StandardScaler()</pre><pre>X = scale.fit_transform(X)</pre><p>Spliting the dataset into training and testing with 70% training and 30% testing.</p><pre>X_train, X_test, Y_train, Y_test = train_test_split(X,y,test_size = 0.3,random_state=42)</pre><p>Random Forest Classifier -It is one of the tree/ensemble method where independent variable is separated set of decision trees from randomly selected subset of training set. It aggregates the votes from different decision trees to decide the final class of the test object.</p><pre>from sklearn.ensemble import RandomForestClassifier</pre><pre>clf = Model(model=RandomForestClassifier(), X=X_train, y=Y_train)</pre><p>we are using cross validation for better result in random forest</p><pre>clf.crossValScore(cv=10)</pre><pre>#OUTPUT</pre><pre>Model accuracy : 0.975</pre><pre>Model precision : 0.800</pre><pre>Model recall : 0.758</pre><pre>Model roc_auc : 0.903</pre><p>Similarly we will check on the test dataset for prediction to avoid overfitting to the data so we will apply it make a decision as we are doing healthcare project we want true positive value ,false negative value.</p><pre>clf_test = Model(model=RandomForestClassifier(), X=X_test, y=Y_test)</pre><pre>clf_test.crossValScore(cv=10)</pre><pre>#OUTPUT</pre><pre>Model accuracy : 0.955</pre><pre>Model precision : 0.830</pre><pre>Model recall : 0.712</pre><pre>Model roc_auc : 0.889</pre><p>From output of test data we can see that the results are not affecting our dataset similarly we will make the conclusion our classifier is optimal for the results. We can apply other classifiers for the prediction of the heart whether it is healthy or unhealthy. But we have to find the results according to the precision and results.</p><p>Saving the model as we will not create it each time for this we have to use package pkl and save it for further use in deployment.</p><p>from sklearn.externals import joblib</p><p><strong>joblib.dump(clf, ‘Heart_model.pkl’)</strong></p><p>Machine Learning classification is done and model is saved in the form of pickle file.</p><p>Now, comes the deployment part for the model of heart disease. Where we will be using Html, css , java script for the deployment of it and forming app.py file where the home and result html file will come as an ouput for the prediction if a person has heart disease or not.</p><p>Here is the code of app.py file where we are using flask as an frame work to deploy the project and come to a decision.</p><pre>from flask import Flask, render_template ,url_for ,request</pre><pre>import pandas as pd</pre><pre>from sklearn.externals import joblib</pre><pre>import numpy as np</pre><pre>app = Flask ( __name__ )</pre><pre>@app.route(&#39;/&#39;)</pre><pre>def home():</pre><pre>return render_template(&#39;home.html&#39;)</pre><pre>def getParameters():</pre><pre>parameters = []</pre><pre>#parameters .append( request.form (&#39;name&#39;))</pre><pre>parameters .append( request.form [&#39;age&#39;])</pre><pre>parameters. append( request.form [&#39;sex&#39;])</pre><pre>parameters. append( request.form [&#39;cp&#39;])</pre><pre>parameters. append( request.form [&#39;trestbps&#39;])</pre><pre>parameters. append( request.form [&#39;chol&#39;])</pre><pre>parameters. append( request.form [&#39;fbs&#39;])</pre><pre>parameters. append( request.form [&#39;restecg&#39;])</pre><pre>parameters. append( request.form [&#39;thalach&#39;])</pre><pre>parameters. append( request.form [&#39;exang&#39;])</pre><pre>parameters. append( request.form [&#39;oldpeak&#39;])</pre><pre>parameters. append( request.form [&#39;slope&#39;])</pre><pre>parameters. append( request.form [&#39;ca&#39;])</pre><pre>parameters. append( request.form [&#39;thal&#39;])</pre><pre>return parameters</pre><pre>@app.route(&#39;/predict&#39;,methods=[&#39;POST&#39;])</pre><pre>def predict():</pre><pre>model = open( &quot;data/Heart_model.pkl&quot; , &quot;rb&quot; )</pre><pre>clfr = joblib.load(model)</pre><pre>if request.method  == &#39;POST&#39;:</pre><pre>parameters = getParameters()</pre><pre>inputFeature = np.asarray( parameters ).reshape(1,-1)</pre><pre>my_prediction = clfr.predict( inputFeature )</pre><pre>return render_template (&#39;result.html&#39;,prediction = int(my_prediction[0]))</pre><pre>if __name__ == &#39;__main__&#39;:</pre><pre>app.run( debug = True)</pre><p>Then we have the predict function which will be implemented when we will enter the input 13 constraints as an input in the box and then array of size 13 goes to the data frame and the output will be predicted and come to know about the result of whether a person has heart disease or not.</p><p><a href="https://www.datadriveninvestor.com/2020/07/23/learn-data-science-in-a-flash/">Learn Data Science in a Flash!? | DataDrivenInvestor</a></p><p>Here is the code for the home.html file where we have the home screen of our deployment part as of to enter field as an independent event.</p><pre>&lt;!DOCTYPE html&gt;</pre><pre>&lt;html&gt;</pre><pre>&lt;head&gt;</pre><pre>&lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css&quot; integrity=&quot;sha512-SfTiTlX6kk+qitfevl/7LibUOeJWlt9rbyDn92a1DqWOw9vWG2MFoays0sgObmWazO5BQPiFucnnEAjpAB+/Sw==&quot; crossorigin=&quot;anonymous&quot; /&gt;</pre><pre>&lt;link rel=&quot;stylesheet&quot; href=&quot;https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css&quot; integrity=&quot;sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk&quot; crossorigin=&quot;anonymous&quot;&gt;</pre><pre>&lt;/head&gt;</pre><pre>&lt;section id=&quot;nav-bar&quot;&gt;</pre><pre>&lt;nav class=&quot;navbar navbar-expand-lg navbar-light bg-dark&quot;&gt;</pre><pre>&lt;a class=&quot;navbar-brand font-weight-bold&quot; href=&quot;&quot; style=&quot;color: red;&quot;&gt;&lt;MARQUEE bgcolor=&quot;&quot;&gt;HEART DISEASE PREDICTION&lt;/MARQUEE&gt;&lt;/a&gt;</pre><pre>&lt;button class=&quot;navbar-toggler&quot; type=&quot;button&quot; data-–toggle=&quot;collapse&quot; data-target=&quot;#navbarNav&quot; aria-controls=&quot;navbarNav&quot; aria-expanded=&quot;True&quot; aria-label=&quot;Toggle navigation&quot;&gt;</pre><pre>&lt;span class=&quot;navbar-toggler-icon&quot;&gt;&lt;/span&gt;</pre><pre>&lt;/button&gt;</pre><pre>&lt;div class=&quot;collapse navbar-collapse&quot; id=&quot;navbarNav&quot;&gt;</pre><pre>&lt;ul class=&quot;navbar-nav ml-auto&quot;&gt;</pre><pre>&lt;li class=&quot;nav-item active&quot;&gt;</pre><pre>&lt;a class=&quot;nav-link&quot; type=&quot;button&quot; color=&quot;red&quot; href=&quot;&quot; style=&quot;color: red&quot; &gt;Home &lt;span class=&quot;sr-only&quot;&gt;(current)&lt;/span&gt;&lt;/a&gt;</pre><pre>&lt;/li&gt;</pre><pre>&lt;li class=&quot;nav-item&quot;&gt;</pre><pre>&lt;a class=&quot;nav-link&quot; href=&quot;index.html&quot;&gt;&lt;/a&gt;</pre><pre>&lt;/li&gt;</pre><pre>&lt;li class=&quot;nav-item&quot;&gt;</pre><pre>&lt;a class=&quot;nav-link&quot; href=&quot;&quot; style=&quot;color: red&quot; &gt;&lt;p&gt;Statistics&lt;/p&gt;&lt;/a&gt;</pre><pre>&lt;/li&gt;</pre><pre>&lt;li class=&quot;nav-item&quot;&gt;</pre><pre>&lt;a class=&quot;nav-link&quot; href=&quot;&quot; style=&quot;color: red&quot;&gt;Contact&lt;/a&gt;</pre><pre>&lt;/li&gt;</pre><pre>&lt;/ul&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;/nav&gt;</pre><pre>&lt;/section&gt;</pre><pre>&lt;div class=&quot;btn btn-primary btn-block btn-large&quot; fontsize=&quot;15&quot; color=&quot;Asymtomatic&quot;&gt;</pre><pre>&lt;center&gt;&lt;h2&gt;ENTER FILEDS&lt;/h2&gt;&lt;/center&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;style&gt;</pre><pre>body {background-image: url(https://medium.com/&#39;static/css/123.gif&#39;);</pre><pre>background-repeat: repeat;</pre><pre>background-attachment: fixed;</pre><pre>background-size: cover</pre><pre>}</pre><pre>/* CSS code for button */</pre><pre>.button_css {</pre><pre>color: #494949 !important;</pre><pre>text-transform: uppercase;</pre><pre>text-decoration: none;</pre><pre>background: #ffffff;</pre><pre>padding: 20px;</pre><pre>border: 4px solid #494949 !important;</pre><pre>display: inline-block;</pre><pre>transition: all 0.4s ease 0s;</pre><pre>}</pre><pre>.button_css:hover {</pre><pre>color: #ffffff !important;</pre><pre>background: #f6b93b;</pre><pre>border-color: #f6b93b !important;</pre><pre>transition: all 0.4s ease 0s;</pre><pre>}</pre><pre>&lt;/style&gt;</pre><pre>&lt;body&gt;</pre><pre>&lt;h3&gt;</pre><pre>&lt;br&gt;&lt;center&gt;</pre><pre>&lt;img src=&quot;static/css/1211.gif&quot; border=&quot;50%&quot;  border= 1px ; height=&quot;250px&quot;</pre><pre>padding= 50px; bgcolor=&quot;red&quot;</pre><pre>width= 600px;</pre><pre>border= #555;&gt;</pre><pre>&lt;/center&gt;</pre><pre>&lt;div class=&quot;login&quot;&gt;</pre><pre>&lt;br&gt;</pre><pre>&lt;!-- Get input for predict the cancer --&gt;</pre><pre>&lt;center&gt;</pre><pre>&lt;form action=&quot;{{ url_for(&#39;predict&#39;)}}&quot;method=&quot;post&quot;&gt;</pre><pre>&lt;p class=&quot;col-2 &quot;style=&quot;background-color: red&quot;&gt;NAME&lt;/p&gt;&lt;input type=&quot;text&quot; id=&quot;name&quot; name=&quot;name&quot; placeholder=&quot;Full name&quot; required=&quot;required&quot; /&gt;&lt;br&gt;&lt;hr&gt;</pre><pre>&lt;p class=&quot;col-2 &quot;style=&quot;background-color: red&quot;&gt;AGE&lt;/p&gt;&lt;input type=&quot;text&quot; id=&quot;age&quot; name=&quot;age&quot; placeholder=&quot;Age in numeric&quot;&gt;</pre><pre>&lt;hr&gt;&lt;br&gt;</pre><pre>&lt;p class=&quot;col-2 &quot;style=&quot;background-color: red&quot;&gt;GENDER&lt;/p&gt;&lt;select id=&quot;sex&quot; name=&quot;sex&quot;&gt;*</pre><pre>&lt;option value=&quot;1&quot;&gt;Male&lt;/option&gt;</pre><pre>&lt;option value=&quot;0&quot;&gt;Female&lt;/option&gt;</pre><pre>&lt;/select&gt;</pre><pre>&lt;hr&gt;&lt;br&gt;</pre><pre>&lt;p class=&quot;col-2 &quot;style=&quot;background-color: red&quot;&gt;Chest Pain Type&lt;/p&gt;</pre><pre>&lt;select id=&quot;cp&quot; name=&quot;cp&quot;&gt;</pre><pre>&lt;option value=&quot;1&quot;&gt;Typical Angina&lt;/option&gt;</pre><pre>&lt;option value=&quot;2&quot;&gt;Atypical Angina&lt;/option&gt;</pre><pre>&lt;option value=&quot;3&quot;&gt;Non-anginal Pain&lt;/option&gt;</pre><pre>&lt;option value=&quot;4&quot;&gt;Asymtomatic&lt;/option&gt;</pre><pre>&lt;/select&gt;</pre><pre>&lt;hr&gt;&lt;br&gt;</pre><pre>&lt;p class=&quot;col-2 &quot;style=&quot;background-color: red&quot;&gt;Resting Blood Pressure&lt;/p&gt;</pre><pre>&lt;input type=&quot;text&quot; id=&quot;trestbps&quot; name=&quot;trestbps&quot; placeholder=&quot;A number in range [94, 200]&quot;&gt;</pre><pre>&lt;hr&gt;&lt;br&gt;</pre><pre>&lt;p class=&quot;col-2 &quot;style=&quot;background-color: red&quot;&gt;Serum Cholestrol&lt;/p&gt;</pre><pre>&lt;input type=&quot;text&quot; id=&quot;chol&quot; name=&quot;chol&quot; placeholder=&quot;A number in range [126, 564]&quot;&gt;</pre><pre>&lt;hr&gt;&lt;br&gt;</pre><pre>&lt;p class=&quot;col-2 &quot;style=&quot;background-color: red&quot;&gt;Fasting Blood Sugar&lt;/p&gt;</pre><pre>&lt;select id=&quot;fbs&quot; name=&quot;fbs&quot;&gt;</pre><pre>&lt;option value=&quot;1&quot;&gt;Greater than 120 mg/dl&lt;/option&gt;</pre><pre>&lt;option value=&quot;0&quot;&gt;Less than 120 mg/dl&lt;/option&gt;</pre><pre>&lt;/select&gt;</pre><pre>&lt;hr&gt;&lt;br&gt;</pre><pre>&lt;p class=&quot;col-2 &quot;style=&quot;background-color: red&quot;&gt;Resting ECG Results&lt;/p&gt;</pre><pre>&lt;select id=&quot;restecg&quot; name=&quot;restecg&quot;&gt;</pre><pre>&lt;option value=&quot;0&quot;&gt;Normal&lt;/option&gt;</pre><pre>&lt;option value=&quot;1&quot;&gt;Having ST-T wave abnormality&lt;/option&gt;</pre><pre>&lt;/select&gt;</pre><pre>&lt;hr&gt;&lt;br&gt;</pre><pre>&lt;p class=&quot;col-2 &quot;style=&quot;background-color: red&quot;&gt;Max Heart Rate Achieved&lt;/p&gt;</pre><pre>&lt;input type=&quot;text&quot; id=&quot;thalach&quot; name=&quot;thalach&quot; placeholder=&quot;A number in range [71, 202]&quot;&gt;</pre><pre>&lt;hr&gt;</pre><pre>&lt;p class=&quot;col-2 &quot;style=&quot;background-color: red&quot;&gt;Exercise-induced Angina&lt;/p&gt;</pre><pre>&lt;select id=&quot;exang&quot; name=&quot;exang&quot;&gt;</pre><pre>&lt;option value=&quot;1&quot;&gt;Yes&lt;/option&gt;</pre><pre>&lt;option value=&quot;0&quot;&gt;No&lt;/option&gt;</pre><pre>&lt;/select&gt;</pre><pre>&lt;hr&gt;    &lt;br&gt;</pre><pre>&lt;p class=&quot;col-2 &quot;style=&quot;background-color: red&quot;&gt;ST depression induced by exercise relative to rest&lt;/p&gt;</pre><pre>&lt;input type=&quot;text&quot; id=&quot;oldpeak&quot; name=&quot;oldpeak&quot; placeholder=&quot;ST depression, typically in [0, 6.2]&quot;&gt;</pre><pre>&lt;hr&gt;  &lt;br&gt;</pre><pre>&lt;p class=&quot;col-2 &quot;style=&quot;background-color: red&quot;&gt;Slope of the peak exercise ST segment&lt;/p&gt;</pre><pre>&lt;input type=&quot;text&quot; id=&quot;slope&quot; name=&quot;slope&quot; placeholder=&quot;Typically in [1, 3]&quot;&gt;</pre><pre>&lt;hr&gt;&lt;br&gt;</pre><pre>&lt;p class=&quot;col-2 &quot;style=&quot;background-color: red&quot;&gt;Number of Major vessels&lt;/p&gt;</pre><pre>&lt;input type=&quot;text&quot; id=&quot;ca&quot; name=&quot;ca&quot; placeholder=&quot;Typically in [0, 3]&quot;&gt;</pre><pre>&lt;hr&gt;&lt;br&gt;</pre><pre>&lt;p class=&quot;col-2 &quot;style=&quot;background-color: red&quot;&gt;THAL&lt;/p&gt;</pre><pre>&lt;select id=&quot;thal&quot; name=&quot;thal&quot;&gt;</pre><pre>&lt;option value=&quot;3&quot;&gt;Normal&lt;/option&gt;</pre><pre>&lt;option value=&quot;6&quot;&gt;Fixed Defect&lt;/option&gt;</pre><pre>&lt;option value=&quot;7&quot;&gt;Reversible Defect&lt;/option&gt;</pre><pre>&lt;/select&gt;</pre><pre>&lt;hr&gt;&lt;br&gt;</pre><pre>&lt;div class=&quot;button_cont&quot; align=&quot;center&quot; &gt;&lt;a class=&quot;button_css&quot;&gt;</pre><pre>&lt;button  type=&quot;submit&quot; class=&quot;btn btn-primary btn-block btn-large&quot; style=&quot;background-color: black &quot;&gt;&lt;strong&gt;&lt;h1 style=&quot;color:white;&quot;&gt;            CLICK HERE TO  &lt;br&gt; PREDICT             &lt;/h4&gt;&lt;/strong&gt;&lt;/button&gt;&lt;/a&gt;&lt;/div&gt;&lt;/form&gt;</pre><pre>&lt;br&gt;</pre><pre>&lt;br&gt;</pre><pre>&lt;div class=&quot;btn btn-primary btn-block btn-large&quot; style=&quot;background-color: red &quot; &gt;</pre><pre>&lt;b&gt;&lt;center&gt;&lt;p style=&quot;text-shadow: transparent;&quot; style=&quot;background-color: red&quot;&gt;&amp;copy; 2020 Karan Choudhary&lt;p&gt;&lt;/center&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;/html&gt;</pre><p>Here we have used the home.html file where we come across 14 variable and we have input them for the prediction. Mainly it consists of navigation bar with moving HEART DISEASE PREDICTION moving from right direction to left direction and footer with copyright icon. Then comes the filled to</p><p>This will work when we have data input from the home.html file where user will enter the data on the basis of his/her profile and its report.</p><pre>&lt;!DOCTYPE html&gt;</pre><pre>&lt;html&gt;</pre><pre>&lt;head&gt;</pre><pre>&lt;title&gt;&lt;/title&gt;</pre><pre>&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;{{ url_for(&#39;static&#39;, filename=&#39;css/my_style.css&#39;) }}&quot;&gt;</pre><pre>&lt;/head&gt;</pre><pre>&lt;section id=&quot;nav-bar&quot;&gt;</pre><pre>&lt;nav class=&quot;navbar navbar-expand-lg navbar-light bg-dark&quot;&gt;</pre><pre>&lt;a class=&quot;navbar-brand font-weight-bold&quot; href=&quot;&quot;&gt;&lt;MARQUEE bgcolor=&quot;&quot;&gt;HEART DISEASE PREDICTION&lt;/MARQUEE&gt;&lt;/a&gt;</pre><pre>&lt;button class=&quot;navbar-toggler&quot; type=&quot;button&quot; data-toggle=&quot;collapse&quot; data-target=&quot;#navbarNav&quot; aria-controls=&quot;navbarNav&quot; aria-expanded=&quot;True&quot; aria-label=&quot;Toggle navigation&quot;&gt;</pre><pre>&lt;span class=&quot;navbar-toggler-icon&quot;&gt;&lt;/span&gt;</pre><pre>&lt;/button&gt;</pre><pre>&lt;div class=&quot;collapse navbar-collapse&quot; id=&quot;navbarNav&quot;&gt;</pre><pre>&lt;ul class=&quot;navbar-nav ml-auto&quot;&gt;</pre><pre>&lt;li class=&quot;nav-item active&quot;&gt;</pre><pre>&lt;a class=&quot;nav-link&quot; type=&quot;button&quot; color=&quot;red&quot; href=&quot;/home.html&quot; style=&quot;color: red&quot;&gt;Home &lt;span class=&quot;sr-only&quot;&gt;(current)&lt;/span&gt;&lt;/a&gt;</pre><pre>&lt;/li&gt;</pre><pre>&lt;li class=&quot;nav-item&quot;&gt;</pre><pre>&lt;a class=&quot;nav-link&quot; href=&quot;&quot;&gt;&lt;/a&gt;</pre><pre>&lt;/li&gt;</pre><pre>&lt;li class=&quot;nav-item&quot;&gt;</pre><pre>&lt;a class=&quot;nav-link&quot; href=&quot; &quot; style=&quot;color: red&quot;&gt;Statistics&lt;/a&gt;</pre><pre>&lt;/li&gt;</pre><pre>&lt;li class=&quot;nav-item&quot;&gt;</pre><pre>&lt;a class=&quot;nav-link&quot; href=&quot;&quot; style=&quot;color: red&quot;&gt;Contact&lt;/a&gt;</pre><pre>&lt;/li&gt;</pre><pre>&lt;/ul&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;/nav&gt;</pre><pre>&lt;/section&gt;</pre><pre>&lt;br&gt;</pre><pre>&lt;br&gt;</pre><pre>&lt;style&gt;</pre><pre>body {background-image: url(https://medium.com/&#39;static/css/41.jpg&#39;);</pre><pre>background-repeat: repeat;</pre><pre>background-attachment: fixed;</pre><pre>background-size: cover;</pre><pre>}</pre><pre>/* CSS code for button */</pre><pre>.button_css {</pre><pre>color: #494949 !important;</pre><pre>text-transform: uppercase;</pre><pre>text-decoration: none;</pre><pre>background: #ffffff;</pre><pre>padding: 20px;</pre><pre>border: 4px solid #494949 !important;</pre><pre>display: inline-block;</pre><pre>transition: all 0.4s ease 0s;</pre><pre>}</pre><pre>.button_css:hover {</pre><pre>color: #ffffff !important;</pre><pre>background: #f6b93b;</pre><pre>border-color: #f6b93b !important;</pre><pre>transition: all 0.4s ease 0s;</pre><pre>}</pre><pre>&lt;/style&gt;</pre><pre>&lt;body&gt;</pre><pre>&lt;header &gt;</pre><pre>&lt;div class=&quot;container&quot; style=&quot;color: black&quot;&gt;</pre><pre>&lt;div id=&quot;brandname&quot; &gt;</pre><pre>&lt;h2&gt;   &lt;center&gt;      Heart Disease  &lt;/center&gt;&lt;/h3&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;/header&gt;</pre><pre>&lt;p style=&quot;color:blue;font-size:30;text-align: center;&quot;&gt;&lt;b&gt;Prediction &lt;/b&gt;&lt;/p&gt;</pre><pre>&lt;div class=&quot;results&quot;&gt;</pre><pre>&lt;center       &gt;</pre><pre>&lt;div class=&quot;container&quot;&gt;</pre><pre>{% if prediction == 1%}</pre><pre>&lt;h2 style=&quot;color:red;&quot; &gt;YES! You might have a  heart Disease.&lt;br&gt;&lt;h1&gt;Do consult to Doctor.&lt;/h1&gt;&lt;/h2&gt;</pre><pre>{% elif prediction == 0%}</pre><pre>&lt;h2 style=&quot;color:green;&quot;&gt;NO! You might not have a heart Disease.&lt;br&gt;&lt;h1&gt;Healthy Heart&lt;/h2&gt;</pre><pre>&lt;ol class=&quot;col-4 &quot; style=&quot;background-color: red &quot;&gt;</pre><pre>{% endif %}</pre><pre>&lt;/div&gt;</pre><pre>&lt;br&gt;</pre><pre>&lt;div class=&quot;col-6&quot;&gt;</pre><pre>&lt;IMG SRC=&quot;static/css/432.gif&quot; width=600px height= 400px style=&quot;background-blend-mode: all;&quot;&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;/center&gt;</pre><pre>&lt;br&gt;</pre><pre>&lt;/body&gt;</pre><pre>&lt;/html&gt;</pre><p>Basically this file works as an home page to the web app through flask. We are counter with the input value on the basic of a person profile and how a person will be responsible for his health and how to mange its health for the future for long lasting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*KpyRJ8CjpD2lpUjoeKIjjA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*NEl2N9EEbWMlE7BoSeC-HQ.png" /></figure><p>At last we come up with an output as an result Healthy heart or unhealthy on the basis of fileds/variable value’s of a person.</p><p>Here is the complete video of the deployment of heart disease prediction.</p><h4>Gain Access to Expert View — <a href="https://datadriveninvestor.com/ddi-intel">Subscribe to DDI Intel</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b07ac961c3b" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/end-to-end-deployment-of-heart-disease-prediction-using-flask-detailed-explanation-1b07ac961c3b">END TO END DEPLOYMENT OF HEART DISEASE PREDICTION USING FLASK (Detailed Explanation)</a> was originally published in <a href="https://medium.datadriveninvestor.com/">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Market Basket Analysis Using Association Rule Mining With Apriori ECLAT and FPGROWTH Algorithm]]></title>
            <link>https://karan18csu103.medium.com/market-basket-analysis-usinhhg-association-rule-mining-with-apriori-eclat-and-fpgrowth-algorithm-6a9737c1f573?source=rss-c6b7aa233755------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a9737c1f573</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Karan Choudhary]]></dc:creator>
            <pubDate>Mon, 05 Oct 2020 14:39:15 GMT</pubDate>
            <atom:updated>2021-01-05T18:08:24.153Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*hMpvlmNdf5sr8IWt6RttZw.jpeg" /></figure><p>ABOUT DATASET</p><p>The dataset consists of various item which are brought by user in various transactions . The goal of the competition is to predict which products will be in a user’s next order. The dataset is anonymized and contains a sample of over7501 rows with 20 plus unique item in the dataset transcations . For each transactions we have, with the sequence of products purchased in each order. All other information we want to conclude for better selling of products with another products.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*xpvoNtbQ3xSnyPUcKneSnA.jpeg" /></figure><p>Library</p><p>The libraries used here are:-</p><p>1)NumPy</p><p>2)Pandas</p><p>3)Matplotlib</p><p>4)Apyori</p><p>5) Mlextend</p><p>6) pyfpgrowth</p><p><strong>Association rule mining</strong></p><p>Association rule mining finds interesting associations and relationships among large sets of data items. This rule shows how frequently a itemset occurs in a transaction. A typical example is Market Based Analysis.</p><p>Market Based Analysis is one of the key techniques used by large relations to show associations between items.It allows retailers to identify relationships between the items that people buy together frequently.</p><p>Given a set of transactions, we can find rules that will predict the occurrence of an item based on the occurrences of other items in the transaction.</p><p>In this dataset we will be using various algorithm to predict the relation between the item sets and Make a strong confidence so we will put these items along them to have better sell of products in the market for better profit.</p><p>ALORITHM FOR ASSOCIATION RULE MINING</p><p>We will be implementing 3 algorithm for prediction</p><p>1. Apriori</p><p>2. ECLAT</p><p>3. FP-growth</p><p>For each algorithm we will using our data with different approach according to the algorithm need and analysis result according to the lift score and various value for better reach of market basket analysis to achieve profit.</p><p>Data Pre-processing</p><p>We will be importing libraries and then through pandas importing the dataset for using and finding relation between them.</p><p>Then we will be doing the analysis of the dataset through pandas and numpy for making the fruitfull information from the dataset</p><p>which consists of info , describe and null functions for better reach</p><p>of data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*5s8UsuQKcXtJth7BKMZOTA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H9IxRTtskuIw-o3m5_hq3Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*80dqxZwb40I6juIuPQdalA.png" /></figure><p><strong>Apriori</strong></p><p><strong>Apriori</strong> is an algorithm used for Association Rule Mining. It searches for a series of frequent sets of items in the datasets. It builds on associations and correlations between the itemsets. It is the algorithm behind “You may also like” where you commonly saw in recommendation platforms.</p><p>General Process of the <strong>Apriori algorithm</strong><br> The entire <strong>algorithm</strong> can be divided into two steps:</p><p>Step 1: <strong>Apply</strong> minimum support to find all the frequent sets with k items in a database.</p><p>Step 2: Use the self-join rule to find the frequent sets with k+1 items with the help of frequent k-itemsets.</p><p>We have different hyperparameters for the association rule mining</p><p>The hyperparameters choosen on this training are:</p><p>min_support = items bought in rows to the total number of transcations.</p><p>min_confidence: at least 20%, min_lift = minimum of 2 (less than that is too low) and max= 5 depends on the need rather.</p><p>min_length: we want at least 2 items or according to needs to be associated. No point in having a single item in the result</p><p>lift : confidence/support</p><p>conviction : tell s about the how the dataset is wrongly assigned to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8hQtjke-hHAd5UusXC_nSg.png" /></figure><p><strong>Hyperparameters</strong></p><p>We have taken minimum support = 3 , minimum confidence=70%</p><p>and minimum length = 3 to have better output and we found the results satisfactory.</p><p>Then we have result generated for the hyperparameters according to them .</p><p>Then we come up with the result of hyper parameters in the dataset with the confidence in it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tGmqp_bxDzj_uY9Ie5WK6g.png" /></figure><p>Now we will go for the lift and association rules among the itemsets and then print lift and association rues and then get result which has the highest we give as optimal item set for market basket analysis.</p><p><a href="https://www.datadriveninvestor.com/2020/06/24/disclosure-and-resolution-program-wont-prevent-physicians-from-practicing-defensive-medicine/">Artificial Intelligence, Deep Learning, and Medical Practice | DataDrivenInvestor</a></p><p>Then we will make the data frame for the lift and association rule mining and ascending the value of it for having batter understanding of the lift with X -&gt; Y.</p><p>The association rule generated are as follows according the hyperparamters.</p><p>RESULTS for better understanding</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RW9nlA2ZAX9tT8rid8fuiA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1qk57_gTK_U3o5AxQUFjAQ.png" /></figure><p>ECLAT ALORITHM</p><p>The ECLAT algorithm stands for Equivalence Class Clustering and bottom-up Lattice Traversal. It is one of the popular methods of Association Rule mining. It is a more efficient and scalable version of the Apriori algorith</p><p>While the Apriori algorithm works in a horizontal sense imitating the Breadth-First Search of a graph,</p><p>the ECLAT algorithm works in a vertical manner just like the Depth-First Search of a graph.</p><p>This vertical approach of the ECLAT algorithm makes it a faster algorithm than the Apriori algorithm.</p><p>How the algorithm work? :</p><p>The basic idea is to use Transaction Id Sets(tidsets) intersections to compute the support value of a candidate and avoiding the generation of subsets which do not exist in the prefix tree.</p><p>In the first call of the function, all single items are used along with their tidsets.</p><p>Then the function is called recursively and in each recursive call, each item-tidset pair is verified</p><p>and combined with other item-tidset pairs. This process is continued until no candidate item-tidset pairs can be combined.</p><p>Steps to perform eclat algorithm-</p><p>1.Get transcition ID of each dataset and scan it.</p><p>2.TID of {a} has only transcation of a in its coloumns or containg {a} only.</p><p>3.Intersect TID list of with other TIDS of other items other than {a} and make result with combination o with each item {a,b},{a,c},{a,d},… upto nth item in dataset and similary for each itemthen we have</p><p>={a}-condition of data(if {a} is removed)</p><p>4.repeat for n th rows with the same condition {a}-conditional data(item removed)</p><p>5.reapeat all the other item set for the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3T3sJB0JORrS3pCcKTjZzg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lHE0GPBP5haDBR80A5t2IQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*09tkwZFVVijC7f8iw2hNzg.png" /></figure><p>IMPLEMENTATION WITH CODE</p><p>Converting the dataset a particluar row into a single transcation of a user in the form of transcations.</p><p>IMPORTANT LIBRARY</p><p>pip install mlxtend</p><p>pip install — no-binary :all: mlxtend</p><p>Mlxtend (machine learning extensions) is a Python library of useful tools for the day-to-day data science tasks.</p><p>this basically hepls to genearte frequent pattern in data and then find the association rule mining between</p><p>them.this helps us in plottig the dataset and helps data with certian tools.</p><p>We come up with the main result that have quick action by generating rules.</p><p>df_rules.sort_values(‘lift’,ascending=False).head(50)</p><p>#top 5 result</p><p>Drawbacks of the Apriori Algorithm also has are:-</p><p>1. At each step, candidate sets have to be built.</p><p>2. To build the candidate sets, the algorithm has to repeatedly scan the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DxSD7umxmsJVVMBtdQkGRA.png" /></figure><p>To overcome this we have use algorithm éclat for avoid repeation and have a faster in terms of searching method for relation.</p><p>FP GROWTH ALGORITHM</p><p>The FP-Growth Algorithm, proposed by Han in, is an efficient and scalable method for mining the complete set of frequent patterns by pattern fragment growth, using an extended prefix-tree structure for storing compressed and crucial information about frequent patterns named frequent-pattern tree (FP-tree).</p><p>steps</p><p>1.Following are the steps for FP Growth Algorithm</p><p>2.Scan DB once, find frequent 1-itemset (single item pattern)</p><p>3.Sort frequent items in frequency descending order, f-list.</p><p>4.Scan DB again, construct FP-tree.</p><p>5.Construct the conditional FP tree in the sequence of reverse order of F — List — generate frequent item set.</p><p>6.Reapeat and then Finish until we come up with strong association mining rule.</p><p>In this we are adding the transcations into the find_frequent_patterns of pyfpgrowth .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ibR9W9PYTt1Zh6BnmJItkA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vgr0NwZ3tt3SRS-yrS-tnQ.png" /></figure><p>Assingning value of support_threshold 2 is min and we can go according to requirements</p><p>It will help us generating confidence among the items to the other item with its score value through.</p><p>generate_association_rules and confidence value is assign for ptimal sell of the products.</p><p>{(left): ((right), confidence)}</p><p>As we can’t find lift and conviction directly on the rules generated we have to make a function for this.</p><p>As, it is not predifed in pyfpgrowth library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*opofjupNCw7a2W9tdqpLaA.png" /></figure><p>I am thankful to mentors at <a href="https://internship.suvenconsultants.com/"><strong>https://internship.suvenconsultants.com</strong></a> for providing awesome problem statements and giving many of us a Coding Internship Exprience. Thank you www.suvenconsultants.com&quot;</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a9737c1f573" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My First Kaggle notebook covering majority of algorithm and visualization of machine learning]]></title>
            <link>https://medium.com/swlh/my-first-kaggle-notebook-covering-majority-of-algorithm-and-visualization-of-machine-learning-2aa0a96b2ca3?source=rss-c6b7aa233755------2</link>
            <guid isPermaLink="false">https://medium.com/p/2aa0a96b2ca3</guid>
            <category><![CDATA[space]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[kaggle]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Karan Choudhary]]></dc:creator>
            <pubDate>Tue, 01 Sep 2020 12:58:39 GMT</pubDate>
            <atom:updated>2020-09-01T12:58:39.839Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*Fwomx0hOCsLLJOYKUrqZmA.png" /></figure><h3>NASA ASTEROID PREDICTION DATASET FROM KAGGLE TOPICS TO BE COVERED:</h3><h3>1.KNN</h3><h3>2.SVC</h3><h3>3.RANDOM FOREST CLASSIFIER</h3><h3>4.ADA BOOST</h3><h3>5.GRADIENT BOSSTING</h3><h3>6.XG BOOST</h3><h3>7.FEATURE SELECTION,CROSS VALIDATION ,HYPERPARAMETER TUNING,RUC AUC GRAPH FOR ALL THE MODELS</h3><h3>8.ARTIFICAL NEURAL NETWORK (DEEP LEARNING)</h3><p>In [ ]:</p><pre><em>#Importing library</em></pre><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br>import numpy as np<br>import seaborn as sns</pre><pre>from sklearn import metrics</pre><pre><em>#importing datset</em><br>dataset=pd.read_csv(&quot;www.kaggle.com/karanchoudhary103/nasa_as/nasa.csv&quot;)</pre><pre><em># import time for comparing Tuning methods</em><br>from time import time<br>start=0<br><em>#droping dataset coloumns</em><br>dataset.drop( [&#39;Close Approach Date&#39;], axis = 1, inplace = True)<br>dataset.drop( [&#39;Orbiting Body&#39;], axis = 1, inplace = True)<br>dataset.drop( [&#39;Orbit Determination Date&#39;], axis = 1, inplace = True)<br>dataset.drop( [&#39;Equinox&#39;], axis = 1, inplace = True)</pre><pre>dataset.drop(dataset.iloc[:,[0,1,2,4,5,6,7,8,9,10,11,12,13,14,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34]],axis=1, inplace = True)<br></pre><pre><em>#data conversion into dependent and target varible </em><br>X = dataset.iloc[:,:-1]<br>Y = dataset.iloc[:,-1]</pre><p>In [ ]:</p><p>In [ ]:</p><pre><em>#Label Encoding for enodig the raget varibles</em><br>from sklearn.preprocessing import LabelEncoder<br>labelencoder_Y = LabelEncoder()<br>labelencoder_Y.fit_transform(Y)<br><em>#spiltting data into training and testing </em><br>from sklearn.model_selection import train_test_split<br>X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2,random_state=22)<br></pre><pre><em>#standard scaling</em><br>from sklearn.preprocessing import StandardScaler<br>sc = StandardScaler()<br>X_train = sc.fit_transform(X_train)<br>X_test = sc.transform(X_test)</pre><h3>KNN</h3><p>BASIC IMPLEMENATION OF KNN 1.Load the data 2.Initialize K to your chosen number of neighbors 3. For each example in the data 3.1 Calculate the distance between the query example and the current example from the data. 3.2 Add the distance and the index of the example to an ordered collection 4. Sort the ordered collection of distances and indices from smallest to largest (in ascending order) by the distances 5. Pick the first K entries from the sorted collection 6. Get the labels of the selected K entries 7. If regression, return the mean of the K labels 8. If classification, return the mode of the K labels</p><p>In [ ]:</p><pre><em>#Loading and fitting data into Knn</em><br>from sklearn.neighbors import KNeighborsClassifier<br>neighbors = KNeighborsClassifier(n_neighbors=10)  <br>neighbors.fit(X_train, Y_train)<br>neighbors</pre><p>In [ ]:</p><p>In [ ]:</p><p>In [ ]:</p><p>In [ ]:</p><pre><em>#Accuracy</em><br>from sklearn.metrics import accuracy_score<br><em># Predict using 10-NN Classifier</em><br>y_pred = neighbors.predict(X_test)<br>y_pred[0:20]<br>accuracy_score(Y_test,y_pred)*100</pre><p>In [ ]:</p><pre><em>#FEATURE SELECTION</em><br><em>#the selction of k value method</em><br><em>#Searching for the best K in the dataset</em><br>K = 10<br>mean_acc = np.zeros((K-1))<br><em>#feature selection of k from 1 to 10 which has better accuracy</em><br>for n <strong>in</strong> range(1,K):     <em>#range (start ,end)</em><br>    <br>    <em>#Train Model and Predict </em><br>    <em>#constructing it  for k=1 to k=10 cross validation</em><br>    neighbors = KNeighborsClassifier(n_neighbors = n)                 <em>#Assigning value of n(1 to 10) in the loop</em><br>    neighbors.fit(X_train,Y_train)       <em>#fitting data</em><br>    y_pred=neighbors.predict(X_test)    <em>#predicting</em><br>    mean_acc[n-1] = metrics.accuracy_score(Y_test, y_pred)    <em>#Storing Accuracy of the each cross validation</em></pre><p>In [ ]:</p><pre>mean_acc                                 <em>#printing values of k</em><br>print(&quot;For the values k=1 to k=9: <strong>\n</strong>&quot;,mean_acc)</pre><p>In [ ]:</p><pre>mean_acc.mean()                       <em>#mean of all rhe values of k (1 to10)</em><br>print(&quot;The value is mean of all values k=1 to k=9   : &quot;,mean_acc.mean()*100)</pre><p>In [ ]:</p><pre><em>#plotting the graph for the selection of the k th values</em><br><em>#Bar plot for training data</em><br>fig = plt.figure()<br>ax = fig.add_axes([0,0,1,1])<em>#left,bootom ,width ,height                                                                                             #Add an axes to the figure.</em></pre><pre>value_k = [&quot;1&quot;,&quot;2&quot;,&quot;3&quot;,&quot;4&quot;,&quot;5&quot;,&quot;6&quot;,&quot;7&quot;,&quot;8&quot;,&quot;9&quot;]     <em>#X AXIS</em><br>accuracy = [0.81236674, 0.84434968, 0.8336887,  0.84648188 ,0.84221748, 0.86034115,<br> 0.84861407, 0.85927505 ,0.85607676]                         <em>#Y AXIS</em><br>ax.bar(value_k,accuracy,color=&#39;rgkyc&#39;)        <em>#rgkyc-different color</em><br>plt.title(&quot;Training Accuracy&quot;,fontsize=25)    <em>#title label</em><br>plt.xlabel(&quot;Value of k&quot;,fontsize=15)    <em>#X label</em><br>plt.ylabel(&quot;Rate in terms of percent&quot;,fontsize=15)    <em>#Y label</em><br>plt.show()    <em>#Display a figure</em></pre><h3>KNN cv</h3><p>In [ ]:</p><pre><em>#For cross validation</em><br>from sklearn.model_selection import cross_val_score<br>knn_scores = []<br><em>#cross validation for the k value from 1 to 10</em><br>for k <strong>in</strong> range(1,10):<br>    knn_classifier = KNeighborsClassifier(n_neighbors = k)         <em>#Assigniing value of k form 1 to 10</em><br>    score=cross_val_score(knn_classifier,X_train,Y_train,cv=10)      <em>#cross validation forr va;lues 1 to 10 each time running cv=10</em><br>    knn_scores.append(score.mean())</pre><p>In [ ]:</p><pre>score   <em>#values of accuracy for the k=1 to k=10</em></pre><p>In [ ]:</p><pre>score.mean()*100    <em>#mean of cross validation</em></pre><p>In [ ]:</p><pre><em>#Plot y versus x as lines and/or markers for the ten values in it</em><br>plt.plot([k for k <strong>in</strong> range(1, 10)], knn_scores, color = &#39;blue&#39;)<br>for i <strong>in</strong> range(1,10):     <em>#start,stop</em><br>    plt.text(i, knn_scores[i-1], (i,&#39;<strong>{:.2f}</strong>&#39;.format(knn_scores[i-1]*100)) )     <br>    <em>#text for te  values accuracy in X-Y plot</em><br>plt.xticks([i for i <strong>in</strong> range(1, 10)])      <em>#Set the current  locations and labels of the x-axis.</em><br>plt.xlabel(&#39;Number of Neighbors (K)&#39;,fontsize=15)   <em>#assign labels for the X axis</em><br>plt.ylabel(&#39;Scores&#39;,fontsize=15,color=&quot;RED&quot;)        <em>#assign labels for the Y axis</em><br>plt.title(&#39;K Neighbors Classifier scores [1-9]&#39;,fontsize=15,color=&quot;BLUE&quot;)    <em>#assign labels for the Title of the graph</em></pre><p>In [ ]:</p><pre>print(&quot;The best accuracy of k is 6    k=6 --&gt; 86.482&quot;)</pre><pre>print(&quot;Accuracy with K-NN with CROSS VALIDATION: <strong>%0.2f</strong>     STD--&gt; (+/- <strong>%f</strong>)&quot; % (score.mean()*100, score.std() *2*100))</pre><p>In [ ]:</p><pre><em>#starting of the tuning methods</em><br>from sklearn.model_selection import RandomizedSearchCV<br><em>#RandomizedSearchCV tuning method which does tuning on sample</em><br>from scipy.stats import randint    <em>#for importing random values </em></pre><pre>est = KNeighborsClassifier(n_jobs=-1)<br><em>#assigning hyperameters for randomized search </em><br>rf_p_dist={  &#39;leaf_size&#39; : randint(1,50),<br>&#39;n_neighbors&#39; : randint(1,30),<br>&#39;p&#39;:[1,2]<br>  }<br><em>#combinations  50*30*2=3000</em><br><em>#it will be working for limited sample randomly </em><br>def hypertuning_rscv(est, rf_p_distr, nbr_iter,X,y):<br>    rdmsearch = RandomizedSearchCV(est, param_distributions=rf_p_distr,<br>                                  n_jobs=-1, n_iter=nbr_iter, cv=5)<br>    <em>#CV = Cross-Validation (Stratified KFold CV)</em><br>    rdmsearch.fit(X,y)               <em>#fitting training data</em><br>    ht_params = rdmsearch.best_params_            <em>#best parameter</em><br>    ht_score = rdmsearch.best_score_               <em>#best accuracy</em><br>    return ht_params, ht_score                       <em>#returning values for the best paramterand its score</em><br></pre><pre>rf_parameters, rf_ht_score = hypertuning_rscv(est, rf_p_dist, 5, X_train, Y_train)<br><em>#classifier,iteartions,ttraining data</em><br>print(&quot;best aprmeters&quot;,rf_parameters)<br>print(&quot;best score&quot;,rf_ht_score)</pre><h3>Classification report of knn for the best knn value</h3><p>In [ ]:</p><pre><em>#evaluting for the best k=6 values from feature selection</em><br>from sklearn.neighbors import KNeighborsClassifier<br>neighbors = KNeighborsClassifier(n_neighbors=6)  <em>#neighbours=6 </em><br>neighbors.fit(X_train, Y_train) <em>#fitting data</em><br>y_pred=neighbors.predict(X_train)  <em>#predciting training data</em></pre><p>In [ ]:</p><pre>from sklearn.metrics import classification_report<br>report = classification_report(Y_train,y_pred)<br>print(report)<br><em>#for the training data</em></pre><p>In [ ]:</p><pre><em>#PLOTTING AUC AND ROC FOR CLASSIFICATION PROBLEM </em><br>from sklearn.metrics import roc_curve<br>from sklearn.metrics import auc, precision_recall_curve,f1_score<br>import matplotlib.pyplot as plt<br>from sklearn.neighbors import KNeighborsClassifier<br>from sklearn.metrics import roc_curve<br>from sklearn.metrics import roc_auc_score<br>from matplotlib import pyplot</pre><pre>ns_probs = [0 for _ <strong>in</strong> range(len(Y_test))]<br><em># fit a model</em><br></pre><pre><em># predict probabilities</em><br>lr_probs = neighbors.predict_proba(X_test)<br><em># keep probabilities for the positive outcome only</em><br>lr_probs = lr_probs[:, 1]<br><em># calculate scores</em><br>ns_auc = roc_auc_score(Y_test, ns_probs)<br>lr_auc = roc_auc_score(Y_test, lr_probs)<br><em># summarize scores</em><br>print(&#39;AUC=<strong>%.3f</strong>&#39; % (ns_auc))<br>print(&#39;ROC=<strong>%.3f</strong>&#39; % (lr_auc))<br><em># calculate roc curves</em><br>ns_fpr, ns_tpr, _ = roc_curve(Y_test, ns_probs)<br>lr_fpr, lr_tpr, _ = roc_curve(Y_test, lr_probs)<br><em># plot the roc curve for the model</em><br>pyplot.plot(ns_fpr, ns_tpr, linestyle=&#39;--&#39;, label=&#39;AUC&#39;)<br>pyplot.plot(lr_fpr, lr_tpr, marker=&#39;.&#39;, label=&#39;ROC&#39;)<br><em># axis labels</em><br>pyplot.xlabel(&#39;False Positive Rate&#39;)<br>pyplot.ylabel(&#39;True Positive Rate&#39;)<br><em># show the legend</em><br>pyplot.legend()<br><em># show the plot</em><br>pyplot.show()</pre><h3>SVC</h3><p>OVERVIEW</p><ol><li>Load the data and fit it</li><li>Now the speration aprt which separte the classes through a hyperplane</li><li>For the maximum sepration we should have maximum seration between the classes we will assighn support vectors</li><li>maximum sepertaion tell which data belongs to which class it classify.</li></ol><p>In [ ]:</p><pre><em>#loading and fitting the dataset</em><br>from sklearn.svm import SVC<br>clf = SVC(kernel = &#39;linear&#39;)               <em>#Assigning kernel(linear,rbf,ploy.) according to the dataset </em><br>clf.fit(X_train, Y_train)                     <em>#fitting in to training data</em><br><em>#training</em><br>y_pred=clf.predict(X_train)                     <em>#fitting in to training data for prediction</em><br><em>#testing</em><br>y_pred1=clf.predict(X_test)                            <em>#fitting in to testing data for prediction</em><br>clf</pre><p>In [ ]:</p><pre>from sklearn.metrics import accuracy_score<br>print(&quot;training accuracy for SVC  :&quot;,accuracy_score(Y_train,y_pred)*100)    <em>#Accuarcy for training</em><br>print(&quot;test accuracy  for SVC     :&quot;,accuracy_score(Y_test,y_pred1)*100)    <em>#Accuracy for testing</em></pre><p>In [ ]:</p><p>In [ ]:</p><pre><em>#3D view of scattter plot for the independent varibales with target variable</em><br>from mpl_toolkits.mplot3d import Axes3D   <em>#tool kit of matplotlib for plotting 3d data into 2d</em><br>fig = plt.figure()                 <em>#for creating new figure</em><br>ax = fig.add_subplot(111, projection=&#39;3d&#39;)                   <em>#*nrows*, *ncols*, and *index*</em><br>x = dataset[&#39;Est Dia in KM(min)&#39;]                     <br>y = dataset[&#39;Miss Dist.(Astronomical)&#39;]<br>z= dataset[&#39;Hazardous&#39;]<br>ax.scatter(x, y, z)    <em>#array like data positions for X,Y,Z</em><br>ax.set_xlabel(&#39;Est Dia in KM(min)&#39;)                     <em>#Assigning labels for the dataset which we have computed in  x axis</em><br>ax.set_ylabel(&#39;Miss Dist.(Astronomical)&#39;)               <em>#Assigning labels for the dataset which we have computed in  y axis</em><br>ax.set_zlabel(&#39;Hazardous&#39;)                               <em>#similarly for z axis</em><br>plt.title(&#39;3D plot of X1 ,X2 and Y &#39;)                    <em>#title label</em><br>plt.show()                                              <em>#plotiing the figure</em></pre><p>In [ ]:</p><pre><em>#visulizing the plane which would seperate the the points</em><br>tmp = np.linspace(-1,20,20)   <em>#Return evenly spaced numbers over a specified interval.</em></pre><pre>x,y = np.meshgrid(tmp,tmp)  <em>#Return coordinate matrices from coordinate vectors</em><br><em>#Lambda functions solve this problem. First, we create a lambda function, and assign it to a variable. </em><br><em>#Then we show that variable is a function, and that we can call it with an argument.</em><br>z = lambda x,y: (-clf.intercept_[0]-clf.coef_[0][0]*x-clf.coef_[0][1]*y) / clf.coef_[0][1]<br><em># The equation of the separating plane is given by all x so that np.dot(svc.coef_[0], x) + b = 0.</em><br>fig = plt.figure()<br>ax  = fig.add_subplot(111, projection=&#39;3d&#39;)   <em>#(111)--&gt;row,col,index of particular</em><br>ax.plot_surface(x, y, z(x,y),cmap=&quot;hot&quot;)            <em>#For Creating a surface plot.</em><br>ax.set_xlabel(&#39;Est Dia in KM(min)&#39;)                   <em>#Assigning labels for the x ,y ,z</em><br>ax.set_ylabel(&#39;Miss Dist.(Astronomical)&#39;)             <em>#Assigning labels for the x ,y ,z</em><br>ax.set_zlabel(&quot;HAZARDOUS&quot;)                            <em>#Assigning labels for the x ,y ,z</em><br>plt.title(&quot;3d plot for SVM&quot;)                             <em>#Assigning label ffor thr titls</em><br>plt.show()</pre><p>In [ ]:</p><p>In [ ]:</p><pre><em>#cross validation value with accuracy and standard deviation</em><br>from sklearn.model_selection import cross_val_score</pre><pre>pred_kfold = cross_val_score(clf, X_train, Y_train, cv=10)  <em>#apllying on training data with cv=10 default </em><br> <br>print(&quot;Accuracy with SVC and K-FOLD CROSS VALIDATION: <strong>%0.2f</strong> (+/- <strong>%0.4f</strong>)&quot; % (pred_kfold.mean()*100, pred_kfold.std() * 2))</pre><p>In [ ]:</p><pre><em>#starting of the tuning methods</em><br>from sklearn.model_selection import RandomizedSearchCV<br>from sklearn.svm import SVC</pre><pre><em>#RandomizedSearchCV tuning method which does tuning on sample</em><br>from scipy.stats import randint    <em>#for importing random values </em></pre><pre>est = SVC()<br><em>#assigning hyperameters for randomized search </em><br>rf_p_dist={  <br>  &#39;kernel&#39;:[&#39;linear&#39;,&quot;rbf&quot;,&quot;sigmoid&quot;],<br>          &quot;decision_function_shape&quot;:[&quot;ovo&quot;,&quot;ovr&quot;],<br>&#39;gamma&#39;:[&quot;scale&quot;, &quot;auto&quot;]}<br><em>#it will be working for limited sample randomly </em><br>def hypertuning_rscv(est, rf_p_distr, nbr_iter,X,y):<br>    rdmsearch = RandomizedSearchCV(est, param_distributions=rf_p_distr,<br>                                  n_jobs=-1, n_iter=nbr_iter, cv=5)<br>    <em>#CV = Cross-Validation (Stratified KFold CV)</em><br>    rdmsearch.fit(X,y)               <em>#fitting training data</em><br>    ht_params = rdmsearch.best_params_            <em>#best parameter</em><br>    ht_score = rdmsearch.best_score_               <em>#best accuracy</em><br>    return ht_params, ht_score                       <em>#returning values for the best paramterand its score</em><br></pre><pre>rf_parameters, rf_ht_score = hypertuning_rscv(est, rf_p_dist, 5, X_train, Y_train)<br><em>#classifier,iteartions,ttraining data</em><br>print(&quot;best aprmeters&quot;,rf_parameters)<br>print(&quot;best score&quot;,rf_ht_score)</pre><p>In [ ]:</p><p>In [ ]:</p><pre><em>#cross validation value with accuracy and standard deviation</em><br>from sklearn.metrics import classification_report<br>report = classification_report(Y_train,y_pred)    <em>#Build a text report showing the main classification metrics</em><br>print(&quot;                  Classification report of training data &quot;)<br>print(report)</pre><pre>from sklearn.metrics import accuracy_score<br>accuracy_score(Y_test,y_pred1)                           <em>#Accuarcy</em><br>print(&quot;The accuracy of the SVM will be:&quot;,accuracy_score(Y_train,y_pred))</pre><p>In [ ]:</p><p>In [ ]:</p><h3>Random forest</h3><p>In [ ]:</p><pre><em>#INCREASING THE NUMBER OF TREES</em></pre><p>In [ ]:</p><pre><em># Fitting Random Forest Classification to the Training set</em><br>from sklearn.ensemble import RandomForestClassifier<br>classifier = RandomForestClassifier(n_estimators = 10, criterion = &#39;entropy&#39;)       <em>#n_estimators-int value #entropy here defines criteria for info. gain and   </em><br>classifier.fit(X_train, Y_train)        <em>#fitting dat into training</em><br>print(classifier)</pre><p>In [ ]:</p><pre><em>#starting of the tuning methods</em><br>from sklearn.model_selection import RandomizedSearchCV<br><em>#RandomizedSearchCV tuning method which does tuning on sample</em><br>from scipy.stats import randint    <em>#for importing random values </em></pre><pre>est = RandomForestClassifier(n_jobs=-1)<br><em>#assigning hyperameters for randomized search </em><br>rf_p_dist={&#39;max_depth&#39;:[3,5,10],                               <em>#max_depth=depth of tree</em><br>              &#39;n_estimators&#39;:[10,100,200,300,400,500],          <em>#NO. of tree</em><br>              &#39;max_features&#39;:randint(1,3),               <em>#features</em><br>               &#39;criterion&#39;:[&#39;gini&#39;,&#39;entropy&#39;],                <em>#infoo gain,gini index, gain ratio</em><br>               &#39;bootstrap&#39;:[True,False],   <em>#with replacement</em><br>               &#39;min_samples_leaf&#39;:randint(1,4),   <em>#leafes</em><br>              }</pre><pre><em>#we have  3*6*3*2*2*4=864 combinations for the randomised search we will be using</em><br><em>#it will be working for limited sample randomly</em></pre><p>In [ ]:</p><pre>def hypertuning_rscv(est, rf_p_distr, nbr_iter,X,y):<br>    rdmsearch = RandomizedSearchCV(est, param_distributions=rf_p_distr,<br>                                  n_jobs=-1, n_iter=nbr_iter, cv=5)<br>    <em>#CV = Cross-Validation (Stratified KFold CV)</em><br>    rdmsearch.fit(X,y)               <em>#fitting training data</em><br>    ht_params = rdmsearch.best_params_            <em>#best parameter</em><br>    ht_score = rdmsearch.best_score_               <em>#best accuracy</em><br>    return ht_params, ht_score                       <em>#returning values for the best paramterand its score</em></pre><p>In [ ]:</p><pre>rf_parameters, rf_ht_score = hypertuning_rscv(est, rf_p_dist, 5, X_train, Y_train)<br><em>#classifier,iteartions,ttraining data</em><br>rf_parameters<br>rf_ht_score</pre><p>In [ ]:</p><p>In [ ]:</p><pre><em>#Assigning best values for trainig data with hyperparmetrs</em><br>claasifier_tune=RandomForestClassifier(bootstrap= True,<br> criterion= &#39;gini&#39;,<br> max_depth= 5,<br> max_features=2,<br> min_samples_leaf= 2,<br> n_estimators= 10)</pre><p>In [ ]:</p><pre><em>#fitting data</em><br><em>#prediction for training data</em><br><em>#prediction for testing data</em><br>claasifier_tune.fit(X_train, Y_train)<br>y_pred=claasifier_tune.predict(X_train)<br>y_pred1=claasifier_tune.predict(X_test)<br>print(&quot;The train accuracy of the random forest randizedtuned:&quot;,accuracy_score(Y_train,y_pred)*100)<br>print(&quot;The test accuracy of the random forest randizedtuned:&quot;,accuracy_score(Y_test,y_pred1)*100)</pre><p>In [ ]:</p><pre>from sklearn.metrics import confusion_matrix,accuracy_score<br>from sklearn.metrics import precision_score<br>from sklearn.metrics import recall_score<br></pre><pre>cm = confusion_matrix(Y_train, y_pred)<br><em>#precision values for false positive rate</em><br><em>#recall values for false negative rate</em><br>cross_val=cross_val_score(claasifier_tune,X_train,Y_train,cv=10,scoring=&#39;accuracy&#39;)<br>cross_val1=cross_val_score(claasifier_tune,X_train,Y_train,cv=10,scoring=&#39;precision&#39;)<br>cross_val2=cross_val_score(claasifier_tune,X_train,Y_train,cv=10,scoring=&#39;recall&#39;)</pre><p>In [ ]:</p><pre>print(&quot;The value of training data for 10 values:&quot;)<br>print(cross_val)<br>print(&quot;  The value of training data mean for accuracy :&quot;,cross_val.mean()*100)<br>print(&quot; &quot;)<br>print(&quot; &quot;)<br>print(&quot;The value of training data for 10 values of precsion:&quot;)<br>print(cross_val1)<br>print(&quot;  The value of training data mean for precision:&quot;,cross_val1.mean()*100)<br>print(&quot; &quot;)<br>print(&quot; &quot;)<br>print(&quot;The value of training data for 10 values of recall:&quot;)<br>print(cross_val2)<br>print(&quot;  The value of training data meanfor recall:&quot;,cross_val2.mean()*100)</pre><p>In [ ]:</p><pre>print(&quot;Accuracy  of the training data through randomised tuning:&quot;,rf_ht_score*100)</pre><pre>print(&quot;The value of  acuuracy training data through k-croos validation:&quot;,cross_val.mean()*100)</pre><pre>print(&quot;The value of precision training data through k-croos validation :&quot;,cross_val1.mean()*100)</pre><pre>print(&quot;The value of recall training data through k-croos validation :&quot;,cross_val2.mean()*100)</pre><p>In [ ]:</p><pre><em>#PLOTTING AUC AND ROC FOR CLASSIFICATION PROBLEM </em><br>from sklearn.metrics import roc_curve<br>from sklearn.metrics import auc</pre><pre>from matplotlib import pyplot</pre><pre><em># Fitting Random Forest Classification to the Training set</em><br>from sklearn.ensemble import RandomForestClassifier<br>classifier = RandomForestClassifier(n_estimators = 10, criterion = &#39;entropy&#39;)       <em>#n_estimators-int value #entropy here defines criteria for info. gain and   </em><br>classifier.fit(X_train, Y_train)        <em>#fitting dat into training</em></pre><pre>ns_probs = [0 for _ <strong>in</strong> range(len(Y_test))]<br><em># fit a model</em></pre><pre><em># predict probabilities</em><br>lr_probs = classifier.predict_proba(X_test)<br><em># keep probabilities for the positive outcome only</em><br>lr_probs = lr_probs[:, 1]<br><em># calculate scores</em><br>ns_auc = roc_auc_score(Y_test, ns_probs)<br>lr_auc = roc_auc_score(Y_test, lr_probs)<br><em># summarize scores</em><br>print(&#39;AUC=<strong>%.3f</strong>&#39; % (ns_auc))<br>print(&#39;ROC=<strong>%.3f</strong>&#39; % (lr_auc))</pre><pre><em># calculate roc curves</em><br>ns_fpr, ns_tpr, _ = roc_curve(Y_test, ns_probs)<br>lr_fpr, lr_tpr, _ = roc_curve(Y_test, lr_probs)<br><em># plot the roc curve for the model</em><br>pyplot.plot(ns_fpr, ns_tpr, linestyle=&#39;--&#39;, label=&#39;AOC&#39;)<br>pyplot.plot(lr_fpr, lr_tpr, marker=&#39;.&#39;, label=&#39;ROC&#39;)<br><em># axis labels</em><br>pyplot.xlabel(&#39;False Positive Rate&#39;)<br>pyplot.ylabel(&#39;True Positive Rate&#39;)<br>pyplot.title(&quot;Random forest classifier&quot;)<br><em># show the legend</em><br>pyplot.legend()<br><em># show the plot</em><br>pyplot.show()</pre><h3>Ada boost and campare of tuning methods</h3><p>In [ ]:</p><pre><em>#Comparring of randomizedserachCV and gridsearchCV</em><br>from sklearn.ensemble import AdaBoostClassifier<br>ada=AdaBoostClassifier()<br>ada.fit(X_train,Y_train)   <em>#training data</em><br>ada</pre><h3>Prediction</h3><p>In [ ]:</p><pre><em>#prediction for ADA boost</em><br>y_pred = ada.predict(X_train)                  <em>#prediction for the training data</em><br>y_pred[:20]                                     <em>#predction for the first 20 values</em></pre><p>In [ ]:</p><pre><em>#Tuning methods and comparing Them</em></pre><p>In [ ]:</p><pre>from sklearn.ensemble import AdaBoostClassifier</pre><pre>from sklearn.model_selection import RandomizedSearchCV<br><em>#RandomizedSearchCV-</em><br>from scipy.stats import randint  <em>#for random integer values</em></pre><pre>est = AdaBoostClassifier()<br>rf_p_dist={<br> &#39;n_estimators&#39;: [50, 100,200,300,90],<br> &#39;learning_rate&#39; : [0.01,0.05,0.1,0.3,1,0.8],<br>              <br>  &#39;algorithm&#39;:[&#39;SAMME.R&#39;,&#39;SAMME&#39;]                        <em>#algo here is for more data SAMME.R  for lower computaion</em><br>  <br>          }<br>def hypertuning_grid(est, rf_p_dist, nbr_iter,X_train,Y_train):<br>    rdmsearch = RandomizedSearchCV(est, param_distributions=rf_p_dist,<br>                                  n_jobs=-1, n_iter=nbr_iter, cv=5)<br>    rdmsearch.fit(X_train,Y_train)                  <em>#fitting data</em><br>    ht_params = rdmsearch.best_params_             <em>#best paramter</em><br>    ht_score = rdmsearch.best_score_                     <em>#best scorer</em><br>    return ht_params, ht_score                      <em>#returning values for the best accuracy and the best paprmeters</em></pre><p>In [ ]:</p><pre>rf_parameters_ran, rf_ht_score_ran = hypertuning_grid(est, rf_p_dist, 1, X_train, Y_train)<br>end=time()                         <em>#starting time</em><br>train_time_adatune=end-start                 <em>#end time</em><br>print(&quot;train_time_ada_rand_tune  :&quot;,train_time_adatune)</pre><p>In [ ]:</p><pre>print(&quot;accuracy of training data &quot;,rf_ht_score_ran*100)                    <em>#accuracy with traing data</em></pre><p>In [ ]:</p><pre><em>#Now compute the time for Grid Search CV and campare</em><br>from sklearn.ensemble import AdaBoostClassifier</pre><pre>from sklearn.model_selection import GridSearchCV<br>est=AdaBoostClassifier()<br>from scipy.stats import randint<br>parameters={<br> &#39;n_estimators&#39;: [50, 100,200,300,90],           <em>#no of trees</em><br> &#39;learning_rate&#39; : [0.01,0.05,0.1,0.3,1,0.8],             <em>#rate of learning for assigning optimal local iinima.</em><br>              <br>  &#39;algorithm&#39;:[&#39;SAMME.R&#39;,&#39;SAMME&#39;]<br>  <br>          }</pre><pre>grid_search = GridSearchCV(estimator = est,<br>                           param_grid = parameters,<br>                           scoring = &#39;accuracy&#39;,<br>                           cv =5,<br>                           n_jobs = -1)<br>grid_search = grid_search.fit(X_train, Y_train)                    <em>#fitting data</em><br>end=time()                                          <em>#starting time</em><br>train_aadagrid=end-start              <em>#end time</em><br>print(&quot;train_aadagrid&quot;,train_aadagrid)</pre><p>In [ ]:</p><pre>accuracy = grid_search.best_score_</pre><pre>print(&quot;Accuracy of the training ada boost gridsearch &quot;,accuracy*100)</pre><h3>Time to check the better ones in terms of computation time</h3><p>In [ ]:</p><pre><em>#taking the last 3 values</em><br>time_randomised=630.1231083    <em>#158707630.123183 time for training</em><br>time_grid=904.1174705      <em>#1587070904.1174705 time for training</em></pre><pre>time_diff=time_grid-time_randomised<br>print(&quot;time_randomised  :&quot;,time_randomised)<em># in this we are making iterations 20</em><br>print(&quot;time_grid        :&quot;,time_grid)<em># In this we are making iterations 5</em><br>print(&quot;time_diff        :&quot;,time_diff)<br>print(&quot; &quot;)</pre><p>In [ ]:</p><p>In [ ]:</p><p>In [ ]:</p><pre><em>#Plotting the difference for these values</em></pre><p>In [ ]:</p><pre>model = [   &quot;adaboost_rand&quot; ,&quot;adaboost_grid&quot;,&quot;adaboost_diff&quot;]   <em>#X-axis</em><br>Train_Time = [<br>    <br>    time_randomised,<br>    time_grid,<br>    time_diff                <em>#diff is small in terms of value</em><br>]<br>plt.bar(model, Train_Time,color=&quot;grb&quot;)    <em>#bar plotting</em><br>plt.xlabel(&#39;Models&#39;, fontsize=15)    <em>#  X-labels</em><br>plt.ylabel(&#39;Training Time&#39;, fontsize=15)   <em>#  Y-labels</em><br>plt.title(&#39;Comparison of Training Time &#39;,fontsize=25)   <em>#title</em><br>plt.show()                 <em>#plot figure</em></pre><p>In [ ]:</p><pre><em>#PLOTTING AUC AND ROC FOR CLASSIFICATION PROBLEM </em><br>from sklearn.metrics import roc_curve<br>from sklearn.metrics import auc</pre><pre>from matplotlib import pyplot<br>from sklearn.ensemble import AdaBoostClassifier<br>ada=AdaBoostClassifier()<br>ada.fit(X_train,Y_train)   <em>#training data</em></pre><pre>ns_probs = [0 for _ <strong>in</strong> range(len(Y_test))]<br><em># fit a model</em></pre><pre><em># predict probabilities</em><br>lr_probs = ada.predict_proba(X_test)<br><em># keep probabilities for the positive outcome only</em><br>lr_probs = lr_probs[:, 1]<br><em># calculate scores</em><br>ns_auc = roc_auc_score(Y_test, ns_probs)<br>lr_auc = roc_auc_score(Y_test, lr_probs)<br><em># summarize scores</em><br>print(&#39;AUC=<strong>%.3f</strong>&#39; % (ns_auc))<br>print(&#39;ROC=<strong>%.3f</strong>&#39; % (lr_auc))</pre><pre><em># calculate roc curves</em><br>ns_fpr, ns_tpr, _ = roc_curve(Y_test, ns_probs)<br>lr_fpr, lr_tpr, _ = roc_curve(Y_test, lr_probs)<br><em># plot the roc curve for the model</em><br>pyplot.plot(ns_fpr, ns_tpr, linestyle=&#39;--&#39;, label=&#39;AOC&#39;)<br>pyplot.plot(lr_fpr, lr_tpr, marker=&#39;.&#39;, label=&#39;ROC&#39;)<br><em># axis labels</em><br>pyplot.xlabel(&#39;False Positive Rate&#39;)<br>pyplot.ylabel(&#39;True Positive Rate&#39;)<br>pyplot.title(&quot;ADA BOOST&quot;)<br><em># show the legend</em><br>pyplot.legend()<br><em># show the plot</em><br>pyplot.show()</pre><p>In [ ]:</p><p>In [ ]:</p><h3>GRADIENT BOOSTING</h3><p>In [ ]:</p><pre><em>#ensemble learning works on boosting parallel learning from the errror from the </em><br>from sklearn.ensemble import GradientBoostingClassifier<br>GBC=GradientBoostingClassifier()<br>GBC.fit(X_train,Y_train)   <em>#fitting training data</em></pre><p>In [ ]:</p><pre>y_pred=GBC.predict(X_train)   <em>#prediction for the x train</em><br>y_pred[:10]        <em>#prediction for the 10 values</em></pre><p>In [ ]:</p><pre>accuracy_score(Y_train,y_pred)*100                 <em>#acuuracy</em></pre><p>In [ ]:</p><pre>from sklearn.ensemble import GradientBoostingClassifier</pre><pre>from sklearn.model_selection import GridSearchCV<br>est=GradientBoostingClassifier()  <br>from scipy.stats import randint<br>parameters={<br>    &#39;learning_rate&#39;:[0.15,0.1,0.05,0.01,0.005,0.001],       <em>#rate of learning for assigning optimal local iinima </em><br>    &quot;max_depth&quot;:[1,3,5,7,9],                                   <em>#assigning depth for the trees</em><br>    &#39;n_estimators&#39;:[100,250,500,750,1000,1250,1500,1750]}             <em>#assigning valies for theom of trees</em><br><em>#combinations 6*5*8=240 combinantions</em><br>grid_search = GridSearchCV(estimator = est,<br>                           param_grid = parameters,<br>                           scoring = &#39;accuracy&#39;,<br>                           cv = 5,<br>                           n_jobs = -1)</pre><p>In [ ]:</p><pre>grid_search = grid_search.fit(X_test, Y_test)    <em>#fitting data</em><br>print(&quot;Accuracy for the training Gradient descent :&quot;,accuracy_score(Y_train,y_pred)*100)<br>print(&quot;Accuracy for the testing Gradient descent :&quot;,accuracy_score(Y_test,y_pred1)*100)</pre><p>In [ ]:</p><pre><em>#PLOTTING AUC AND ROC FOR CLASSIFICATION PROBLEM </em><br>from sklearn.metrics import roc_curve<br>from sklearn.metrics import auc</pre><pre>from matplotlib import pyplot<br>from sklearn.ensemble import AdaBoostClassifier<br>ada=AdaBoostClassifier()<br>ada.fit(X_train,Y_train)   <em>#training data</em></pre><pre>ns_probs = [0 for _ <strong>in</strong> range(len(Y_test))]<br><em># fit a model</em><br><em>#ensemble learning works on boosting parallel learning from the errror from the </em><br>from sklearn.ensemble import GradientBoostingClassifier<br>GBC=GradientBoostingClassifier()<br>GBC.fit(X_train,Y_train)   <em>#fitting training data</em></pre><pre><em># predict probabilities</em><br>lr_probs = GBC.predict_proba(X_test)<br><em># keep probabilities for the positive outcome only</em><br>lr_probs = lr_probs[:, 1]<br><em># calculate scores</em><br>ns_auc = roc_auc_score(Y_test, ns_probs)<br>lr_auc = roc_auc_score(Y_test, lr_probs)<br><em># summarize scores</em><br>print(&#39;AUC=<strong>%.3f</strong>&#39; % (ns_auc))<br>print(&#39;ROC=<strong>%.3f</strong>&#39; % (lr_auc))</pre><pre><em># calculate roc curves</em><br>ns_fpr, ns_tpr, _ = roc_curve(Y_test, ns_probs)<br>lr_fpr, lr_tpr, _ = roc_curve(Y_test, lr_probs)<br><em># plot the roc curve for the model</em><br>pyplot.plot(ns_fpr, ns_tpr, linestyle=&#39;--&#39;, label=&#39;AOC&#39;)<br>pyplot.plot(lr_fpr, lr_tpr, marker=&#39;.&#39;, label=&#39;ROC&#39;)<br><em># axis labels</em><br>pyplot.xlabel(&#39;False Positive Rate&#39;)<br>pyplot.ylabel(&#39;True Positive Rate&#39;)<br>pyplot.title(&quot;GRADIENT BOOSTING&quot;)<br><em># show the legend</em><br>pyplot.legend()<br><em># show the plot</em><br>pyplot.show()</pre><p>In [ ]:</p><p>In [ ]:</p><p>In [ ]:</p><p>In [ ]:</p><p>In [ ]:</p><pre><em>#XGBOOST  BEST MODEL</em></pre><p>In [ ]:</p><pre>from xgboost import XGBClassifier<br>xgb = XGBClassifier()<br>xgb.fit(X_train,Y_train)</pre><p>In [ ]:</p><pre><em>#fitting data</em><br><em>#prediction for training data</em><br><em>#prediction for testing data</em><br>y_pred=claasifier_tune.predict(X_train)<br>y_pred1=claasifier_tune.predict(X_test)<br>print(&quot;The train accuracy of the random forest randizedtuned:&quot;,accuracy_score(Y_train,y_pred)*100)<br>print(&quot;The test accuracy of the random forest randizedtuned:&quot;,accuracy_score(Y_test,y_pred1)*100)</pre><p>In [ ]:</p><pre><em>#prediction for XG boost</em><br>y_pred = xgb.predict(X_train)                  <em>#prediction for the training data</em><br>y_pred[:20]                                     <em>#predction for the first 20 values</em></pre><pre>from xgb import XGBClassifier</pre><pre>from sklearn.model_selection import RandomizedSearchCV<br><em>#RandomizedSearchCV-tuning approach which works on sample of the dataset</em><br>from scipy.stats import randint  <em>#for random integer values</em></pre><pre>est =XGBClassifier()<br>rf_p_dist={<br>    &#39;subsample&#39;:[0.8,0.2,0.5,0.4,0.36],                        <br>    &#39;min_child_weight&#39;:[5,10,15,4,2],<br>    &#39;max_depth&#39;:[1,2,3,5,4],<br>    &#39;gamma&#39;:[0.1,0.2,0.5,0.60,0.8,0.91]<br>}<br>def hypertuning_grid(est, rf_p_dist, nbr_iter,X_train,Y_train):<br>    rdmsearch = RandomizedSearchCV(est, param_distributions=rf_p_dist,<br>                                  n_jobs=-1, n_iter=nbr_iter, cv=15)<br>    rdmsearch.fit(X_train,Y_train)                  <em>#fitting data</em><br>    ht_params = rdmsearch.best_params_             <em>#best paramter</em><br>    ht_score = rdmsearch.best_score_                     <em>#best scorer</em><br>    return ht_params, ht_score                      <em>#returning values for the best accuracy and the best paprmeters</em></pre><p>In [ ]:</p><pre>rf_parameters, rf_ht_score = hypertuning_rscv(est, rf_p_dist, 15, X_train, Y_train)<br><em>#classifier,iteartions,ttraining data</em><br>rf_parameters<br>print(&quot;best parameters  :&quot;,rf_parameters)<br>print(&quot;best scorer  :&quot;,rf_ht_score*100)</pre><p>In [ ]:</p><pre><em>#PLOTTING AUC AND ROC FOR CLASSIFICATION PROBLEM </em><br>from sklearn.metrics import roc_curve<br>from sklearn.metrics import auc</pre><pre>from matplotlib import pyplot<br>ns_probs = [0 for _ <strong>in</strong> range(len(Y_test))]<br><em># fit a model</em><br><em>#ensemble learning works on boosting parallel learning from the errror from the </em><br>from xgboost import XGBClassifier<br>xgb = XGBClassifier()<br>xgb.fit(X_train,Y_train)</pre><pre><em># predict probabilities</em><br>lr_probs = xgb.predict_proba(X_test)<br><em># keep probabilities for the positive outcome only</em><br>lr_probs = lr_probs[:, 1]<br><em># calculate scores</em><br>ns_auc = roc_auc_score(Y_test, ns_probs)<br>lr_auc = roc_auc_score(Y_test, lr_probs)<br><em># summarize scores</em><br>print(&#39;AUC=<strong>%.3f</strong>&#39; % (ns_auc))<br>print(&#39;ROC=<strong>%.3f</strong>&#39; % (lr_auc))</pre><pre><em># calculate roc curves</em><br>ns_fpr, ns_tpr, _ = roc_curve(Y_test, ns_probs)<br>lr_fpr, lr_tpr, _ = roc_curve(Y_test, lr_probs)<br><em># plot the roc curve for the model</em><br>pyplot.plot(ns_fpr, ns_tpr, linestyle=&#39;--&#39;, label=&#39;AOC&#39;)<br>pyplot.plot(lr_fpr, lr_tpr, marker=&#39;.&#39;, label=&#39;ROC&#39;)<br><em># axis labels</em><br>pyplot.xlabel(&#39;False Positive Rate&#39;)<br>pyplot.ylabel(&#39;True Positive Rate&#39;)<br>pyplot.title(&quot;XG BOOST&quot;)<br><em># show the legend</em><br>pyplot.legend()<br><em># show the plot</em><br>pyplot.show()</pre><p>In [ ]:</p><pre><em>#Bagging Fot</em><br>from sklearn.ensemble import BaggingClassifier<br>from sklearn.neighbors import KNeighborsClassifier<br>bagging = BaggingClassifier(KNeighborsClassifier(n_neighbors=11),<br>                            max_samples=0.9, max_features=2)<br>bagging.fit(X_train, Y_train)<br></pre><pre>from sklearn.metrics import accuracy_score<br><em># Predict using 10-NN Classifier</em><br>a=accuracy_score(Y_test,y_pred)*100<br>y_pred = bagging.predict(X_test)<br>y_pred[:20]<br>print(a)</pre><p>In [ ]:</p><pre><em>#Bar plot for training data</em><br>fig = plt.figure()  <em>#creating anew figure</em><br>ax = fig.add_axes([0,0,1,1])<em>#width,height</em><br>Algorithms = [&#39;logistic regression&#39;,&#39;naive bayes&#39;,&#39;decision tree&#39;,&#39;Svm&#39;,&#39;knn&#39;,&#39;ada boost&#39;,&#39;Random_tree_cv&#39;,&#39;Random_tree_tuning&#39;,&#39;GradientBoosting&#39;]<br>accuracy = [84.2,82.5,84.648,85.382,82.3,87.409,85.463,86.567,87.803]<br>ax.barh(Algorithms,accuracy,color=&#39;rbgy&#39;)                  <em>#horizontal bargraph with color</em></pre><pre>plt.title(&quot;model vs accuracy&quot;,fontsize=25)           <em>#label of title</em><br>plt.xlabel(&quot;Algorithms&quot;,fontsize=20)                       <em>#X label</em><br>plt.ylabel(&quot;Accuracy&quot;,fontsize=20)                             <em>#Y label</em><br>plt.show()                                                     <em>#creating plot</em></pre><p>In [ ]:</p><pre><em>#Saving all the images and then used in if andd else loop </em><br>import cv2<br><em>#reading the images in the form of arrays</em><br>img = cv2.imread(&#39;knn1.png&#39;)<br>img1 = cv2.imread(&#39;knn2.png&#39;)<br>img2 = cv2.imread(&#39;svc1.png&#39;)<br>img3 = cv2.imread(&#39;svc2.png&#39;)<br>img4 = cv2.imread(&#39;ADA.png&#39;)<br>img5 = cv2.imread(&#39;Models.png&#39;)<br>img6 = cv2.imread(&#39;xgB.png&#39;)<br><em>#plotting the images in the png format</em><br>plt.imshow(img)<br>plt.imshow(img1)<br>plt.imshow(img2)<br>plt.imshow(img3)<br>plt.imshow(img4)<br>plt.imshow(img5)<br>plt.imshow(img6)<br>print(plt.imshow(img5))</pre><pre>print(plt.imshow(img4))<br>print(plt.imshow(img))<br>print(plt.imshow(img2))<br>print(plt.imshow(img1))</pre><pre>print(plt.imshow(img3))</pre><p>In [ ]:</p><pre><em>#Enter the name of classifier and then check the value for it</em><br>classifier_search = int(input(&#39;PRESS KEY<strong>\n</strong>1.KNN for featuere selection of K <strong>\n</strong>2.KNN for CROSS VALIDATION <strong>\n</strong>3.KNN CAMPARE CROSS VALIDATION VS ACCUARCY OF THE BEST K VALUE<strong>\n</strong>4.SVC ACCURACY FOR TRANING AND TESTING ACCURACY<strong>\n</strong>5.SVC CROSS VALIDATION AND HYPERPLANE:<strong>\n</strong>6.Random forest randizedtuned<strong>\n</strong>7.Random forest accuracy,precesion,recall<strong>\n</strong>8.Time of random and grid searchCV and accuracy<strong>\n</strong>9.Comparing the time of tuning methods and plotting graph<strong>\n</strong>10.Models ACCUARCY<strong>\n</strong>11.Xg boost acuuracy with tuning&#39;)) </pre><pre>if classifier_search== 1: <br>    print(&quot;KNN&quot;)<br>    print(&quot;For the values k=9 to k=1:&quot;,mean_acc)</pre><pre>    print(plt.imshow(img))</pre><pre>elif classifier_search==2: <br>    print(&quot;Croos validation score for Cv=10 for 10 values of k&quot;,score)<br>    print(&quot;Croos validation score for Cv=10 for 10 values of k mean&quot;,score.mean())<br>    print(plt.imshow(img1))</pre><pre>elif classifier_search==3:<br>    print(&quot;The best accuracy of k is 2    k=2 &amp; its acuuracy value is 84.482&quot;)<br>    print(&quot;Accuracy with K-NN and K-FOLD CROSS VALIDATION: <strong>%0.2f</strong>     STD--&gt; (+/- <strong>%f</strong>)&quot; % (score.mean()*100, score.std() *2))<br>    print(&quot;Switch to other model&quot;)<br>    <br>elif classifier_search==4:</pre><pre>    print(&quot;training accuracy for SVC:&quot;,accuracy_score(Y_train,y_pred))<br>    print(&quot;test accuracy  for SVC   :&quot;,accuracy_score(Y_test,y_pred1))    <br>    print(&quot;The 3d plot of the SVC  &quot;,plt.imshow(img2))<br>elif classifier_search==5:<br>    print(&quot;The hyperplane of the points  SVC(3-D)  &quot;,plt.imshow(img3))<br>    print(report)<br>    print(&quot;The accuracy of the SVM will be:&quot;,accuracy_score(Y_train,y_pred))</pre><pre>elif classifier_search==6:    <br>    print(&quot; RANDOM FOREST TUNED &quot;)<br>    print(&quot;The train accuracy of the random forest randizedtuned:&quot;,accuracy_score(Y_train,y_pred)*100)<br>    print(&quot;The test accuracy of the random forest randizedtuned:&quot;,accuracy_score(Y_test,y_pred1)*100)</pre><pre>elif classifier_search==7:</pre><pre>    print(&quot;The value of training data for 10 values:&quot;)<br>    print(cross_val)<br>    print(&quot;  The value of training data mean:&quot;,cross_val.mean()*100)<br>    print(&quot; &quot;)<br>    print(&quot; &quot;)<br>    print(&quot;The value of training data for 10 values of precsion:&quot;)<br>    print(cross_val1)<br>    print(&quot;  The value of training data mean:&quot;,cross_val1.mean()*100)<br>    print(&quot; &quot;)<br>    print(&quot; &quot;)<br>    print(&quot;The value of training data for 10 values of recall:&quot;)<br>    print(cross_val2)<br>    print(&quot;  The value of training data mean:&quot;,cross_val2.mean()*100)<br>    <br>elif classifier_search==8:<br>    <br>    print(&quot;train_time_ada_rand_tune  :&quot;,train_time_adatune)<br>    print(&quot;accuracy of training data &quot;,rf_ht_score_ran*100)<br>    print(&quot;train_ada_grid&quot;,train_aadagrid)<br>    print(&quot;Accuracy of the training ada boost gridsearch for each value&quot;,accuracy*100)<br>    <br>elif classifier_search==9:<br>    <br>    print(&quot;Accuracy of the training ada boost gridsearch    : 86.70944251800479&quot;)<br>    print(&quot;accuracy of training data  for ada Ransearch_cv  :&quot;  ,rf_ht_score_ran*100)<br>    print(&quot;Bar plot for the differnece in the time &quot;)<br>    print(plt.imshow(img4))<br>        </pre><pre>elif classifier_search==10:<br>    print(&quot;HERE ARE THE DIFFERENT MODELS AND THERE ACCURACY &quot;)<br>    print(plt.imshow(img5))<br>elif classifier_search==11:<br>    print(&quot;Accuracy of the training xgboost random search : 88.36  &quot;)<br>    <br>else :<br>    print(&quot;<strong>\t</strong>                                            Wrong Input Value&quot;)<br>    print(&quot;                                          Enter value lies betwwen 1 to 10 &quot;)<br>    print(&quot;&quot;)</pre><p>In [ ]:</p><h3>DEEP LEARNING</h3><p>Now,then we go for the deep learning part →ANN(Artifical Neural Networks)</p><p>HERE ARE THE STEPS: Weight are assigned at each layer of neural network Forward propogation takes place by assigning weight and then applying activation function from input values to the end of hidden layer and Evaluating the predicted dependent variable with the actual dependent variable Evaluating of output of input layer to hidden layer Evaluating of output of hidden layer to output layer Evaluating of Error Then reassigning the optimal weights for the same neural networks through Backpropgation Until the cost function of it not be in Decreases further. ‘’’</p><p>In [ ]:</p><pre><em>#USE ANN method For the dataset to compute more accuracy in terms of count</em><br><em>#install library</em><br>import keras <br>from keras.models import Sequential<br>from keras.layers import Dense</pre><pre><em>#Initalizing the Ann</em></pre><pre><em>#Making the prediction model test and results</em><br>classifier=Sequential()<br><em>#adding the firstinput layer and the first hidden layers in the neural</em><br>classifier.add(Dense(output_dim=5,init=&quot;uniform&quot;,Activation=&quot;relu&quot;,input_dim=2))<br><em>#As, deep learning is consist of  all the input,hidden,output layers where hidden layers are more for better acauuracy in terms</em><br><em>#of actual nad predicted so we can end with this layer but more better undersatnding we keep adding of the layers</em></pre><pre><em>#adding second hidden layer</em><br>classifier.add(Dense(output_dim=2,init=&quot;uniform&quot;,Activation=&quot;relu&quot;))</pre><pre><em>#making the final layer output layer where ewe use sigmoid function we will have prbability for the 0 or 1</em></pre><pre>classifier.add(Dense(output_dim=1,init=&quot;uniform&quot;,Activation=&quot;sigmoid&quot;))<br><em># if we have more than 2 catequiers in the dependent function we will have tochnage sigmoid to shift-max and also out_deim</em></pre><pre><em>#prediction from the actual ones.</em><br>classifier.compile(optimizer=&quot;adam&quot;,loss=&quot;binary_crossentropy&quot;,metrices=[&#39;accuracy&#39;])   <em>#metrices we wnat fot precision of TP</em><br></pre><pre><em>#to choose the epox at each round</em><br><em>#A epoch here is process a complete visit of forward and backward propgation once.  </em><br>classifier.fit(X_train,Y_train,batch_size=10,nb_epoch=100)   </pre><pre><em>#prediction of the classifier</em><br>y_pred=classifier(X_test)<br>y_pred= (y_pred&gt;0.5)  <em># assigninhg threshold value to it genearlly we shold take value 0.65</em><br><em>#confusion matricx,accuracy</em><br>from sklearn.metrics import confusion_metrics<br>from sklearn.metrics import accuracy_score<br>cm=confusion_metrics(Y_train,y_pred)<br>accuracy_score(Y_train, y_pred)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2aa0a96b2ca3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/my-first-kaggle-notebook-covering-majority-of-algorithm-and-visualization-of-machine-learning-2aa0a96b2ca3">My First Kaggle notebook covering majority of algorithm and visualization of machine learning</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All in one clustering techniques in machine learning you should know in unsupervised learning]]></title>
            <link>https://medium.com/analytics-vidhya/all-in-one-clustering-techniques-in-machine-learning-you-should-know-in-unsupervised-learning-b7ca8d5c4894?source=rss-c6b7aa233755------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7ca8d5c4894</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <dc:creator><![CDATA[Karan Choudhary]]></dc:creator>
            <pubDate>Sat, 22 Aug 2020 18:53:49 GMT</pubDate>
            <atom:updated>2020-08-24T13:34:42.533Z</atom:updated>
            <content:encoded><![CDATA[<p>Clustering algorithms are a powerful technique for <a href="https://datafloq.com/read/?q=Machine%20learning#utm=internal">machine learning</a> on unsupervised data. The most common algorithms in <a href="https://datafloq.com/read/?q=Machine%20learning#utm=internal">machine learning</a> are hierarchical clustering and K-Means clustering. These two algorithms are incredibly powerful when applied to different machine learning problems.</p><p><strong>Cluster</strong> analysis can be a powerful data-mining tool for any organization that needs to identify discrete groups of customers, sales transactions, or other types of behaviors and things. For example, insurance providers <strong>use cluster</strong> analysis to detect fraudulent claims, and banks <strong>use</strong> it for credit scoring.</p><p>Algorithm mostly in →</p><ol><li>Identification of fake news .</li><li>Spam filter</li><li>marketing sales</li><li>Classify network traffic.</li><li>Identifying fraudulent or criminal activity</li></ol><p>Here are the topics we will be covering in this clustering techniques.</p><p>* PCA Decomposition (Dimensionality Reduction)<br>* K-Means Clustering (Centroid Based) Clustering<br>* Hierarchical (Divisive and Agglomerative) Clustering<br>* DBSCAN (Density Based) Clustering</p><blockquote># Importing Data</blockquote><blockquote>import pandas as pd<br>data = pd.read_csv(‘../input/unsupervised-learning-on-country-data/Country-data.csv’)</blockquote><p>Let’s check the contents of data</p><blockquote>data.head()</blockquote><p>#describtion of dataset</p><blockquote>data.describe()</blockquote><p>What do the column headings mean? Let’s check the data dictionary.</p><blockquote>import pandas as pd<br>data_dict = pd.read_csv(‘../input/unsupervised-learning-on-country-data/data-dictionary.csv’)<br>data_dict.head(10)</blockquote><p># Analyzing Data</p><blockquote>#Data analysis baseline library<br>!pip install dabl</blockquote><p>We are using Data Analysis Baseline Library here. It will help us analyze the data with respect to the target column.</p><blockquote>import dabl<br>import warnings<br>import matplotlib.pyplot as plt<br>warnings.filterwarnings(‘ignore’)<br>plt.style.use(‘ggplot’)<br>plt.rcParams[‘figure.figsize’] = (12, 6)<br>dabl.plot(data, target_col = ‘gdpp’)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*Wqf8NGyt5BxeIXYu-ev4Aw.png" /></figure><p>We can observe very close positive correlation between “Income” and “GDPP”. Also, “Exports”, “Imports”, “Health” have sort of positive correlation with “GDPP”.</p><p>However, we will now drop the column “Country” not because it is the only categorical (object type) parameter, but because it is not a deciding parameter to keep/not-keep a particular record within a cluster. In short, “Country” is a feature which is not required here for unsupervised learning.</p><blockquote># Exclude “Country” column<br>data = data.drop(‘country’, axis=1)</blockquote><p>We will use simple profile reporting where we can get an easy overview of variables, and we can explore interactions (pair-wise scatter plots), correlations (Pearson’s, Spearman’s, Kendall’s, Phik), missing value information — all in one place. The output it produces is a bit long though, and we need to scroll down and toggle different tabs to view all the results, but the time you spend on it is worth it.</p><p><strong>Gist of Overview:</strong></p><ul><li>Average death of children under age 5 in every 100 people: 38.27</li><li>Average life expectancy: 70.56 (highly negatively skewed distribution)</li><li>Health has a perfectly symmetric distribution with mean 6.82</li><li>Average exports of goods and services per capita: 41.11</li><li>Average imports of goods and services per capita: 46.89 (which is &gt; avg. exports)</li><li>Average net income per person: 17144.69 (highly positively skewed distribution)</li><li>Average inflation: 7.78 (has a wide spread ranging from min -4.21 till +104)</li><li>Average GDP per capita: 12964.15 (highly negatively skewed distribution)</li></ul><p><strong>Gist of Interactions:</strong></p><ul><li>Child Mortality has a perfect negative correlation with Life Expectancy</li><li>Total Fertility has somewhat positive correlation with Child Mortality</li><li>Exports and Imports have rough positive correlation</li><li>Income and GDPP have fairly positive correlation</li></ul><p><strong>Gist of Missing Values:</strong></p><ul><li>There is no missing value in data</li></ul><p>We will discuss correlation coefficients in detail later.</p><blockquote>#More prominent correlation plot<br>import numpy as np<br>import seaborn as sns<br>corr = data.corr()<br>mask = np.triu(np.ones_like(corr, dtype=np.bool))<br>f, ax = plt.subplots(figsize=(12, 12))<br>cmap = sns.light_palette(‘black’, as_cmap=True)<br>sns.heatmap(corr, mask=mask, cmap=cmap, vmax=None, center=0,square=True, annot=True, linewidths=.5, cbar_kws={“shrink”: .9})</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*MQ_AyeARZ7O2vF0cjTCvSw.png" /></figure><p><strong>Insights from Pearson’s Correlation Coefficient Plot :</strong></p><ul><li>Imports have high positive correlation with Exports (+0.74)</li><li>Income has fairly high positive correlation with Exports (+0.52)</li><li>Life Expectancy has fairly high positive correlation with Income (+0.61)</li><li>Total Fertility has very high positive correlation with Child Mortality (+0.85)</li><li>GDPP has very high positive correlation with Income (+0.90)</li><li>GDPP has fairly high positive correlation with Life Expectancy (+0.60)</li><li>Total Fertility has fairly high negative correlation with Life Expectancy (-0.76) — Well, I found this particular thing as an interesting insight but let’s not forget <strong>“Correlation does not imply causation”!</strong></li></ul><h3>(1) Principal Component Analysis</h3><p>Principal Component Analysis (PCA) is a popular technique for deriving a set of low dimensional features from a large set of variables. Sometimes reduced dimensional set of features can represent distinct no. of groups with similar characteristics. Hence PCA can be an insightful clustering tool (or a preprocessing tool before applying clustering as well). We will standardize our data first and will use the scaled data for all clustering works in future.</p><blockquote>from sklearn.preprocessing import StandardScaler<br>sc=StandardScaler()<br>data_scaled=sc.fit_transform(data)</blockquote><p>Here, I have used singular value decomposition solver “auto” to get the no. of principal components. You can also use solver “randomized” introducing a random state seed like “0” or “12345”.</p><blockquote>from sklearn.decomposition import PCA<br>pc = PCA(svd_solver=’auto’)<br>pc.fit(data_scaled)<br>print(‘Total no. of principal components =’,pc.n_components_)</blockquote><blockquote>#Print Principal Components<br>print(‘Principal Component Matrix :\n’,pc.components_)</blockquote><p>Let us check the amount of variance explained by each principal component here. They will be arranged in decreasing order of their explained variance ratio.</p><blockquote>#The amount of variance that each PC explains<br>var = pc.explained_variance_ratio_<br>print(var)</blockquote><blockquote>#Plot explained variance ratio for each PC<br><em>plt.bar([i for i, _ in enumerate(var)],var,color=’black’)<br>plt.title(‘PCs and their Explained Variance Ratio’, fontsize=15)<br>plt.xlabel(‘Number of components’,fontsize=12)<br>plt.ylabel(‘Explained Variance Ratio’,fontsize=12)</em></blockquote><p>Using these cumulative variance ratios for all PCs, we will now draw a scree plot. It is used to determine the number of principal components to keep in this principal component analysis.</p><blockquote># Scree Plot<br>plt.plot(cum_var, marker=’o’)<br>plt.title(‘Scree Plot: PCs and their Cumulative Explained Variance Ratio’,fontsize=15)<br>plt.xlabel(‘Number of components’,fontsize=12)<br>plt.ylabel(‘Cumulative Explained Variance Ratio’,fontsize=12)</blockquote><p>The plot indicates the threshold of 90% is getting crossed at PC = 4. Ideally, we can keep 4 (or atmost 5) components here. Before PC = 5, the plot is following an upward trend. After crossing 5, it is almost steady. However, we have retailed all 9 PCs here to get the full data in results. And for visualization purpose in 2-D figure, we have plotted only PC1 vs PC2.</p><blockquote>#Principal Component Data Decomposition<br>colnames = list(data.columns)<br>pca_data = pd.DataFrame({ ‘Features’:colnames,’PC1&#39;:pc.components_[0],’PC2&#39;:pc.components_[1],’PC3&#39;:pc.components_[2],<br> ‘PC4’:pc.components_[3],’PC5&#39;:pc.components_[4], ‘PC6’:pc.components_[5], ‘PC7’:pc.components_[6], <br> ‘PC8’:pc.components_[7], ‘PC9’:pc.components_[8]})<br>pca_data</blockquote><p>we will se then</p><blockquote>#Visualize 2 main PCs<br>fig = plt.figure(figsize = (12,6))<br>sns.scatterplot(pca_data.PC1, pca_data.PC2,hue=pca_data.Features,marker=’o’, s=500)<br>plt.title(‘PC1 vs PC2’,fontsize=15)<br>plt.xlabel(‘Principal Component 1’,fontsize=12)<br>plt.ylabel(‘Principal Component 2’,fontsize=12)<br>plt.show()</blockquote><p>We can see that 1st Principal Component (X-axis) is gravitated mainly towards features like: life expectancy, gdpp, income. 2nd Principal Component (Y-axis) is gravitated predominantly towards features like: imports, exports.</p><blockquote>#Export PCA results to file<br>pca_data.to_csv(“PCA_results.csv”, index=False)</blockquote><p>(2) K-Means Clustering</p><p>This is the most popular method of clustering. It uses Euclidean distance between clusters in each iteration to decide a data point should belong to which cluster, and proceed accordingly. To decide how many no. of clusters to consider, we can employ several methods. The basic and most widely used method is **Elbow Curve**.</p><p>**Method-1: Plotting Elbow Curve**</p><p>In this curve, wherever we observe a “knee” like bent, we can take that number as the ideal no. of clusters to consider in K-Means algorithm.</p><blockquote>from yellowbrick.cluster import KElbowVisualizer</blockquote><blockquote>#Plotting Elbow Curve<br>from sklearn.cluster import KMeans<br>from yellowbrick.cluster import KElbowVisualizer<br>from sklearn import metrics</blockquote><blockquote>model = KMeans()<br>visualizer = KElbowVisualizer(model, k=(1,10))<br>visualizer.fit(data_scaled) <br>visualizer.show()</blockquote><p>Here, along Y-axis, “distortion” is defined as “the sum of the squared differences between the observations and the corresponding centroid”. It is same as WCSS (Within-Cluster-Sum-of-Squares).</p><p>Let’s see the centroids of the clusters. Afterwards, we will fit our scaled data into a K-Means model having 3 clusters, and then label each data point (each record) to one of these 3 clusters.</p><blockquote>#Fitting data into K-Means model with 3 clusters<br>km_3=KMeans(n_clusters=3,random_state=12345)<br>km_3.fit(data_scaled)<br>print(km_3.cluster_centers_)</blockquote><p>We can see each record has got a label among 0,1,2. This label is each of their cluster_id i.e. in which cluster they belong to. We can count the records in each cluster now.</p><blockquote>pd.Series(km_3.labels_).value_counts()</blockquote><p>We see, the highest no. of records belong to the first cluster.</p><blockquote>Now, we are interested to check how good is our K-Means clustering model. Silhouette Coefficient is one such metric to check that. The **Silhouette Coefficient** is calculated using: <br>* the mean intra-cluster distance ( a ) for each sample<br>* the mean nearest-cluster distance ( b ) for each sample<br>* The Silhouette Coefficient for a sample is (b — a) / max(a, b)</blockquote><p># calculate Silhouette Coefficient for K=3<br>from sklearn import metrics<br>metrics.silhouette_score(data_scaled, km_3.labels_)</p><blockquote># calculate SC for K=2 through K=10<br>k_range = range(2, 10)<br>scores = []<br>for k in k_range:<br> km = KMeans(n_clusters=k, random_state=12345)<br> km.fit(data_scaled)<br> scores.append(metrics.silhouette_score(data_scaled, km.labels_))</blockquote><p>We observe the highest silhouette score with no. of clusters 3 and 4. However, from Elbow Curve, we got to see the “knee” like bent at no. of clusters 3. So we will do further analysis to choose the ideal no. of clusters between 3 and 4.</p><p>For further analysis, we will consider **Davies-Bouldin Score** apart from Silhouette Score. **Davies-Bouldin Score** is defined as the average similarity measure of each cluster with its most similar cluster, where similarity is the ratio of within-cluster distances to between-cluster distances. Thus, clusters which are farther apart and less dispersed will result in a better score.</p><p>We will also analyze **SSE (Sum of Squared Errors)**. SSE is the sum of the squared differences between each observation and its cluster’s mean. It can be used as a measure of variation within a cluster. If all cases within a cluster are identical the SSE would then be equal to 0. The formula for SSE is: 1</p><p>Method-2: Plotting of SSE, Davies-Bouldin Scores, Silhouette Scores to Decide Ideal No. of Clusters</p><blockquote>from sklearn.metrics import davies_bouldin_score, silhouette_score, silhouette_samples<br>sse,db,slc = {}, {}, {}<br>for k in range(2, 10):<br> kmeans = KMeans(n_clusters=k, max_iter=1000,random_state=12345).fit(data_scaled)<br> if k == 4: labels = kmeans.labels_<br> clusters = kmeans.labels_<br> sse[k] = kmeans.inertia_ # Inertia: Sum of distances of samples to their closest cluster center<br> db[k] = davies_bouldin_score(data_scaled,clusters)<br> slc[k] = silhouette_score(data_scaled,clusters)</blockquote><blockquote>#Plotting SSE<br>plt.figure(figsize=(12,6))<br>plt.plot(list(sse.keys()), list(sse.values()))<br>plt.xlabel(“Number of cluster”, fontsize=12)<br>plt.ylabel(“SSE (Sum of Squared Errors)”, fontsize=12)<br>plt.title(“Sum of Squared Errors vs No. of Clusters”, fontsize=15)<br>plt.show()</blockquote><p>We can see “knee” like bent at both 3 and 4, still considering no. of clusters = 4 seems a better choice, because after 4, there is no further “knee” like bent observed. Still, we will analyse further to decide between 3 and 4.</p><blockquote>#Plotting Davies-Bouldin Scores<br>plt.figure(figsize=(12,6))<br>plt.plot(list(db.keys()), list(db.values()))<br>plt.xlabel(“Number of cluster”, fontsize=12)<br>plt.ylabel(“Davies-Bouldin values”, fontsize=12)<br>plt.title(“Davies-Bouldin Scores vs No. of Clusters”, fontsize=15)<br>plt.show()</blockquote><p>clearly no choice for =3 in best choice.</p><blockquote>plt.figure(figsize=(12,6))<br>plt.plot(list(slc.keys()), list(slc.values()))<br>plt.xlabel(“Number of cluster”, fontsize=12)<br>plt.ylabel(“Silhouette Score”, fontsize=12)<br>plt.title(“Silhouette Score vs No. of Clusters”, fontsize=15)<br>plt.show()</blockquote><p>No. of clusters = 3 seems the best choice here as well. The silhouette score ranges from −1 to +1, where a high value indicates that the object is well matched to its own cluster and poorly matched to neighboring clusters. A score nearly 0.28 seems a good one.</p><p>Silhouette Plots for Different No. of Clusters :**<br>We will now draw Silhouette Plots for different no. of clusters for getting more insights. Side by side, we will observe the shape of the clusters in 2-dimensional figure.</p><blockquote>#Silhouette Plots for Different No. of Clusters<br>import matplotlib.cm as cm<br>import numpy as np<br>for n_clusters in range(2, 10):<br> fig, (ax1, ax2) = plt.subplots(1, 2)<br> fig.set_size_inches(18, 8)<br> # The 1st subplot is the silhouette plot<br> # The silhouette coefficient can range from -1, 1 but here the range is from -0.2 till 1<br> ax1.set_xlim([-0.2, 1])<br> # The (n_clusters+1)*10 is for inserting blank space between silhouette plots of individual clusters, to demarcate them clearly.<br> ax1.set_ylim([0, len(data_scaled) + (n_clusters + 1) * 10])<br> # Initialize the clusterer with n_clusters value and a random generator seed of 12345 for reproducibility.<br> clusterer = KMeans(n_clusters=n_clusters,max_iter=1000, random_state=12345)<br> cluster_labels = clusterer.fit_predict(data_scaled)<br> # The silhouette_score gives the average value for all the samples<br> # This gives a perspective into the density and separation of the formed clusters<br> silhouette_avg = silhouette_score(data_scaled, cluster_labels)<br> print(“For n_clusters =”, n_clusters, “The average silhouette_score is :”, silhouette_avg)<br> # Compute the silhouette scores for each sample<br> sample_silhouette_values = silhouette_samples(data_scaled, cluster_labels)<br> y_lower = 10<br> for i in range(n_clusters):<br> # Aggregate the silhouette scores for samples belonging to cluster i and sort them<br> ith_cluster_silhouette_values = sample_silhouette_values[cluster_labels == i]<br> ith_cluster_silhouette_values.sort()<br> size_cluster_i = ith_cluster_silhouette_values.shape[0]<br> y_upper = y_lower + size_cluster_i<br> color = cm.nipy_spectral(float(i) / n_clusters)<br> ax1.fill_betweenx(np.arange(y_lower, y_upper),<br> 0, ith_cluster_silhouette_values,<br> facecolor=color, edgecolor=color, alpha=0.7)</blockquote><blockquote># Label the silhouette plots with their cluster numbers at the middle<br> ax1.text(-0.05, y_lower + 0.5 * size_cluster_i, str(i))</blockquote><blockquote># Compute the new y_lower for next plot<br> y_lower = y_upper + 10</blockquote><blockquote>ax1.set_title(“The silhouette plot for the various clusters.”)<br> ax1.set_xlabel(“The silhouette coefficient values”)<br> ax1.set_ylabel(“Cluster label”)</blockquote><blockquote># The vertical line for average silhouette score of all the values<br> ax1.axvline(x=silhouette_avg, color=”red”, linestyle=” — “)</blockquote><blockquote>ax1.set_yticks([]) # Clear the yaxis labels<br> ax1.set_xticks([-0.2, 0, 0.2, 0.4, 0.6, 0.8, 1])</blockquote><blockquote># 2nd Plot showing the actual clusters formed<br> colors = cm.nipy_spectral(cluster_labels.astype(float) / n_clusters)<br> ax2.scatter(data_scaled[:, 0], data_scaled[:, 1], marker=’.’, s=30, lw=0, alpha=0.7, c=colors, edgecolor=’k’)</blockquote><blockquote># Labeling the clusters<br> centers = clusterer.cluster_centers_<br> # Draw white circles at cluster centers<br> ax2.scatter(centers[:, 0], centers[:, 1], marker=’o’, c=”white”, alpha=1, s=200, edgecolor=’k’)</blockquote><blockquote>for i, c in enumerate(centers):<br> ax2.scatter(c[0], c[1], marker=’$%d$’ % i, alpha=1, s=50, edgecolor=’k’)</blockquote><blockquote>ax2.set_title(“The visualization of the clustered data.”)<br> ax2.set_xlabel(“Feature space for the 1st feature”)<br> ax2.set_ylabel(“Feature space for the 2nd feature”)</blockquote><blockquote>plt.suptitle((“Silhouette analysis for KMeans clustering on sample data with n_clusters = %d” % n_clusters), fontsize=14, fontweight=’bold’)</blockquote><blockquote>plt.show()</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_gUmTGsJOl1jmoDofnQxRA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5AhMD7aYz1mkpR-JlG8lIA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cw_PFw57nDy7M_5lEOMUJA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2e08UXKMETaVlM5fuvNndA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XntalvCwe3m0etvy8y6bsg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hIbTIVB71633RfeLTRkvPA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f5Hlgat3_miqfGCXd8CKug.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_gUmTGsJOl1jmoDofnQxRA.png" /></figure><blockquote>preds = km_3.labels_<br>data_df = pd.DataFrame(data)<br>data_df[‘KM_Clusters’] = preds<br>data_df.head(10)</blockquote><p>We will visualize 3 clusters now for various pairs of features. Initially, I chose the pairs randomly. Later, I chose the pairs including “GDPP”, “income”, “inflation” etc. important features. Since we are concerned about analyzing country profiles and “GDPP” is the main indicator to represent a country’s status, we are concerned with that mainly.</p><blockquote>#Visualize clusters: Feature Pair-1<br>import matplotlib.pyplot as plt_1<br>plt_1.rcParams[‘axes.facecolor’] = ‘lightblue’<br>plt_1.figure(figsize=(12,6))<br>plt_1.scatter(data_scaled[:,0],data_scaled[:,1],c=cluster_labels) #child mortality vs exports<br>plt_1.title(“Child Mortality vs Exports (Visualize KMeans Clusters)”, fontsize=15)<br>plt_1.xlabel(“Child Mortality”, fontsize=12)<br>plt_1.ylabel(“Exports”, fontsize=12)<br>plt_1.rcParams[‘axes.facecolor’] = ‘lightblue’<br>plt_1.show()</blockquote><h3>Hierarchical clustering</h3><p>There are two types of hierarchical clustering: **Divisive** and **Agglomerative**. In divisive (top-down) clustering method, all observations are assigned to a single cluster and then that cluster is partitioned to two least similar clusters, and then those two clusters are partitioned again to multiple clusters, and thus the process go on. In agglomerative (bottom-up), the opposite approach is followed. Here, the ideal no. of clusters is decided by **dendrogram**.</p><blockquote>Method-1: Dendrogram Plotting using Clustermap</blockquote><blockquote>import seaborn as sns<br>cmap = sns.cubehelix_palette(as_cmap=True, rot=-.3, light=1)<br>g = sns.clustermap(data_scaled, cmap=cmap, linewidths=.5)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*ayFW5dC48EV9X-AuNOiM3A.png" /></figure><p>From above dendrogram, we can consider 2 clusters at minimum or 6 clusters at maximum. We will again cross-check the dendrogram using **Ward’s Method**. Ward’s method is an alternative to single-link clustering. This algorithm works for finding a partition with small sum of squares (to minimise the within-cluster-variance).</p><p>Method-2: Dendrogram Plotting using Ward’s Method</p><blockquote># Using the dendrogram to find the optimal number of clusters<br>import scipy.cluster.hierarchy as sch</blockquote><blockquote>plt.rcParams[‘axes.facecolor’] = ‘white’<br>plt.rcParams[‘axes.grid’] = False<br>dendrogram = sch.dendrogram(sch.linkage(data_scaled, method=’ward’))<br>plt.title(“Dendrogram using Ward’s Method”, fontsize=15)<br>plt.xlabel(‘Clusters’, fontsize=12)<br>plt.ylabel(‘Euclidean distances’, fontsize=12)<br>plt.rcParams[‘axes.facecolor’] = ‘white’<br>plt.rcParams[‘axes.grid’] = False<br>plt.show()</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*zl5fEi5_cA8uBWqP4b7lMA.png" /></figure><h3><strong>DBSCAN Clustering</strong></h3><p>DBSCAN is an abbreviation of “Density-based spatial clustering of applications with noise”. This algorithm groups together points that are close to each other based on a distance measurement (usually Euclidean distance) and a minimum number of points. It also marks noise as outliers (noise means the points which are in low-density regions).</p><p>I found an interesting result with DBSCAN when I used all features of country data. It gave me a single cluster.** I presume, that was very evident to happen because our data is almost evenly spread, so density wise, this algorithm could not bifurcate the datapoints into more than one cluster. Hence, I used only the features which have high correlation with “GDPP”. I also kept “Child Mortality” and “Total Fertility” in my working dataset since they have polarizations — some data points have extremely high values, some have extremely low values (ref. to corresponding scatter plots in data profiling section in the beginning).</p><blockquote>from sklearn.cluster import DBSCAN<br>import sklearn.utils<br>from sklearn.preprocessing import StandardScaler</blockquote><blockquote>Clus_dataSet = data[[‘child_mort’,’exports’,’health’,’imports’,’income’,’inflation’,’life_expec’,’total_fer’,’gdpp’]]<br>Clus_dataSet = np.nan_to_num(Clus_dataSet)<br>Clus_dataSet = np.array(Clus_dataSet, dtype=np.float64)<br>Clus_dataSet = StandardScaler().fit_transform(Clus_dataSet)</blockquote><blockquote># Compute DBSCAN<br>db = DBSCAN(eps=1, min_samples=3).fit(Clus_dataSet)<br>core_samples_mask = np.zeros_like(db.labels_)<br>core_samples_mask[db.core_sample_indices_] = True<br>labels = db.labels_<br>#data[‘Clus_Db’]=labels</blockquote><blockquote>realClusterNum=len(set(labels)) — (1 if -1 in labels else 0)<br>clusterNum = len(set(labels))</blockquote><blockquote># A sample of clusters<br>print(data[[‘child_mort’,’exports’,’health’,’imports’,’income’,’inflation’,’life_expec’,’total_fer’,’gdpp’]].head())</blockquote><blockquote># number of labels<br>print(“number of labels: “, set(labels))</blockquote><p>We have got 7 clusters using density based clustering which is a distinct observation (7 is much higher than 3 which we got in all three different clustering algorithms we used earlier).</p><blockquote># save the cluster labels and sort by cluster<br>datacopy = data.copy()<br>datacopy = datacopy.drop(‘KM_Clusters’, axis=1)<br>datacopy[‘DB_cluster’] = db.labels_</blockquote><blockquote>#Visualize clusters: Random Feature Pair-1 (income vs gdpp)<br>import matplotlib.pyplot as plt_3<br>plt_3.rcParams[‘axes.facecolor’] = ‘orange’<br>plt_3.figure(figsize=(12,6))<br>plt_3.scatter(datacopy[‘income’],datacopy[‘gdpp’],c=db.labels_) <br>plt_3.title(‘Income vs GDPP (Visualize DBSCAN Clusters)’, fontsize=15)<br>plt_3.xlabel(“Income”, fontsize=12)<br>plt_3.ylabel(“GDPP”, fontsize=12)<br>plt_3.rcParams[‘axes.facecolor’] = ‘orange’<br>plt_3.show()</blockquote><blockquote>#Visualize clusters: Random Feature Pair-2 (inflation vs gdpp)<br>import matplotlib.pyplot as plt_3<br>plt_3.figure(figsize=(12,6))<br>plt_3.scatter(datacopy[‘inflation’],datacopy[‘gdpp’],c=db.labels_) <br>plt_3.title(‘Inflation vs GDPP (Visualize DBSCAN Clusters)’, fontsize=15)<br>plt_3.xlabel(“Inflation”, fontsize=12)<br>plt_3.ylabel(“GDPP”, fontsize=12)<br>plt_3.rcParams[‘axes.facecolor’] = ‘orange’<br>plt_3.show()</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*1xtmV12nxLswrwAaHFqcSA.png" /></figure><p>If you want to implement code from your hand then click the <a href="https://mail.google.com/mail/u/0/#sent/KtbxLvhKPCWtKcNHKdVwPzGkMzJQjRJjnq"><strong>button</strong></a> and implement code end to end with explanation in brief.</p><p>If u like to read this article and have common interest in similar projects then we can grow our network and can work for more real time projects.</p><p>For more details connect with me on my <a href="https://www.linkedin.com/in/karan-choudhary-9102b81a0/"><strong>Linkedin account</strong></a><strong><em>!</em></strong></p><p><strong>THANKS!!!!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7ca8d5c4894" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/all-in-one-clustering-techniques-in-machine-learning-you-should-know-in-unsupervised-learning-b7ca8d5c4894">All in one clustering techniques in machine learning you should know in unsupervised 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[End to End Deployment of Heart Disease Prediction Through Flask With Machine learning Algorithm]]></title>
            <link>https://medium.com/swlh/end-to-end-deployment-of-heart-disease-prediction-through-flask-with-machine-learning-algorithm-5cedd1e31b46?source=rss-c6b7aa233755------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cedd1e31b46</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[healthcare]]></category>
            <dc:creator><![CDATA[Karan Choudhary]]></dc:creator>
            <pubDate>Tue, 18 Aug 2020 13:18:20 GMT</pubDate>
            <atom:updated>2020-08-19T13:43:54.223Z</atom:updated>
            <content:encoded><![CDATA[<h3>End to End Deployment of Heart Disease Prediction Through Flask With Machine Learning Algorithm</h3><p><strong>Artificial Intelligence</strong> directly translates to conceptualizing and building machines that can think and hence are independently capable of performing tasks, thus exhibiting intelligence. If this advancement in technology is a <strong>boon</strong> or a <strong>bane</strong> to humans and our surroundings is a never-ending debate.</p><p>Every coin has its two faces so it is difficult to judge on the basis as a human being and make a quick decision about it and say about the technology. Everything in this world whether it is living or no living it has its positive and negative impact over the world and is cache is popularity when it is fruitful for the society and living being other than its ill and major impact for the long term on the living beings.</p><p>Healthcare is no different. Particularly in the case of automation, machine learning, and artificial intelligence (AI), doctors, hospitals, insurance companies, and industries with ties to healthcare have all been impacted — in many cases in more positive, substantial ways than other industries.</p><p>Before starting we should discuss about the dataset we are using for the prediction .</p><blockquote><strong><em>Age,Sex,cp,trestbps,chol,fbs,restecg,thalach,exang,oldpeak,slope,ca,</em></strong></blockquote><blockquote><strong><em>thal, Target</em></strong></blockquote><p>These are some of the major independent value of the dataset which we are training for the prediction of the heart disease.</p><h3>Installing Flask on your Machine</h3><p>Installing Flask is simple and straightforward. Here, I am assuming you already have Python 3 and pip installed. To install Flask, you need to run the following command:</p><pre>sudo apt-get install python3-flask<br>pip install flask</pre><p>That’s it! You’re all set to dive into the problem statement take one step closer to deploying your machine learning model through flask.</p><h3>Starting of implementation</h3><p>Here we have folder structure of the machine learning deployment model through flask.</p><p>We will be implementing these code in jupyter and sublime text editor.Implementing the machine learning models lets go for importing library.</p><pre># import libraries<br>import pandas as pd # for data manipulation or analysis<br>import numpy as np # for numeric calculation<br>import matplotlib.pyplot as plt # for data visualization<br>import seaborn as sns # for data visualization<br>import pickle #for dumping the model or we can use joblib library</pre><p>Now next step is to load the data through pandas.</p><pre>heart_df = pd.read_csv(‘heart_disease.csv’)</pre><p>Now next step is to see the data frame of the data.</p><pre># Head of heart DataFrame<br>heart_df.head(6)</pre><p>Info about the model(gives null value and count the non float values)</p><pre># Information of heart Dataframe<br>heart_df.info()</pre><p>Numerical description about the data (mean,median,25%,interquantile range and many other value of each feature.</p><pre># Numerical distribution of data<br>heart_df.describe()</pre><h3>Heatmap</h3><pre># heatmap of DataFrame<br>plt.figure(figsize=(16,9))<br>sns.heatmap(heart_df)</pre><h3>Heatmap of a correlation matrix</h3><pre>heart_df.corr()#gives the correlation between them</pre><pre># Heatmap of Correlation matrix of breast heartDataFrame<br>plt.figure(figsize=(20,20))<br>sns.heatmap(heart_df.corr(), annot = True, cmap =&#39;coolwarm&#39;, linewidths=2)</pre><h3>Split DataFrame in Train and Test</h3><p>Input variable</p><pre># input variable<br>X = heart_df.drop([‘target’], axis = 1) <br>X.head(6)</pre><p>Output variable</p><pre># output variable<br>y = heart_df[&#39;target&#39;] <br>y.head(6)</pre><h3>Split dataset for training and</h3><pre># split dataset into train and test<br>from sklearn.model_selection import train_test_split<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state= 5)</pre><h3>Feature scaling of data</h3><pre>from sklearn.preprocessing import StandardScaler<br>sc = StandardScaler()<br>X_train_sc = sc.fit_transform(X_train)<br>X_test_sc = sc.transform(X_test)</pre><h3>Machine Learning Model Building</h3><p>1.Suppor vector Classifier</p><pre>from sklearn.metrics import confusion_matrix, classification_report, accuracy_score  #for classification report<br>#Svm model<br>from sklearn.svm import SVC<br>svc_classifier = SVC()<br>svc_classifier.fit(X_train, y_train)<br>y_pred_scv = svc_classifier.predict(X_test)<br>accuarcy_svm=accuracy_score(y_test, y_pred_scv)<br>print(accuarcy_svm)#Output 0.5789473684210527</pre><p>2.Logistic Regression</p><pre># Logistic Regression<br>from sklearn.linear_model import LogisticRegression<br>lr_classifier = LogisticRegression(random_state = 51, penalty = ‘l1’)<br>lr_classifier.fit(X_train, y_train)<br>y_pred_lr = lr_classifier.predict(X_test)<br>accuracy_score(y_test, y_pred_lr)<br>accuarcy_lr=accuracy_score(y_test, y_pred_lr)<br>print(accuarcy_lr)#Output 0.9736842105263158</pre><p>3.<strong>Decision Tree Classifier</strong></p><pre>#Decision Tree Classifier<br>from sklearn.tree import DecisionTreeClassifier<br>dt_classifier = DecisionTreeClassifier(criterion = ‘entropy’, random_state = 51)<br>dt_classifier.fit(X_train, y_train)<br>y_pred_dt = dt_classifier.predict(X_test)<br>accuarcy_dt=accuracy_score(y_test, y_pred_dt)<br>print(accuarcy_dt)</pre><pre>#Output 0.9473684210526315</pre><p>4. XGboost classsifier</p><pre># XGBoost Classifier<br>from xgboost import XGBClassifier<br>xgb_classifier = XGBClassifier()<br>xgb_classifier.fit(X_train, y_train)<br>y_pred_xgb = xgb_classifier.predict(X_test)<br>y_pred_xgb=accuracy_score(y_test, y_pred_xgb)<br>accuarcy_xgb=accuracy_score(y_test, y_pred_xgb)<br>print(accuarcy_xgb)</pre><pre>#Output 0.9823684210526315</pre><p>Similarly, we have to do for test data and implement them on we can see that their will be no overfitting and underfitting the test data. their should low bias and low variance.</p><p><strong>Accuracy on test data and the similar code for test data .</strong></p><pre>#accuracy of all the classifier test data<br>Accuracy of Support vector Classifier - 0.5789456522520<br>Accuracy of Decision tree Classifier -0.8473684210526315<br>Accuracy of Logistic regression- 0.570456140350877<br>Accuracy of XGBoost Classifier - 0.982456140350877</pre><p>As,we can conclude the test data is performing nearly good result in Xgboost classifier with low bias and variance.</p><p>For further improving we should go for the tuning method such as randomised search and grid search on Xgboost because we want our accuracy to be more optimal and fix all contraints like precision ,recall ,beta value and support which are import to satisfy to overcome the Type I and Type II Error.</p><h3>Randomized search</h3><p>Applying randomized search on the model which works on sample of data and it works more faster than any search tuning method</p><pre>params={<br> “learning_rate” : [0.05, 0.10, 0.15, 0.20, 0.25, 0.30 ] ,<br> “max_depth” : [ 3, 4, 5, 6, 8, 10, 12, 15],<br> “min_child_weight” : [ 1, 3, 5, 7 ],<br> “gamma” : [ 0.0, 0.1, 0.2 , 0.3, 0.4 ],<br> “colsample_bytree” : [ 0.3, 0.4, 0.5 , 0.7 ] <br>}</pre><p># Randomized Search</p><pre>from sklearn.model_selection import RandomizedSearchCV<br>random_search = RandomizedSearchCV(xgb_classifier, param_distributions=params, scoring= ‘roc_auc’, n_jobs= -1, verbose= 3)<br>random_search.fit(X_train, y_train)</pre><p>Finding the best and optimize parameter.</p><pre>random_search.best_params_#output<br>{&#39;min_child_weight&#39;: 1,<br> &#39;max_depth&#39;: 12,<br> &#39;learning_rate&#39;: 0.3,<br> &#39;gamma&#39;: 0.3,<br> &#39;colsample_bytree&#39;: 0.7}</pre><p>random_search.best_estimator_</p><pre>#output<br>XGBClassifier(base_score=0.5, booster=&#39;gbtree&#39;, colsample_bylevel=1,<br>       colsample_bynode=1, colsample_bytree=0.7, gamma=0.3,<br>       learning_rate=0.3, max_delta_step=0, max_depth=12,<br>       min_child_weight=1, missing=None, n_estimators=100, n_jobs=1,<br>       nthread=None, objective=&#39;binary:logistic&#39;, random_state=0,<br>       reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=None,<br>       silent=None, subsample=1, verbosity=1)</pre><p># training XGBoost classifier with best parameters</p><pre>xgb_classifier_pt = XGBClassifier(base_score=0.5, booster=’gbtree’, colsample_bylevel=1,<br> colsample_bynode=1, colsample_bytree=0.4, gamma=0.2,<br> learning_rate=0.1, max_delta_step=0, max_depth=15,<br> min_child_weight=1, missing=None, n_estimators=100, n_jobs=1,<br> nthread=None, objective=’binary:logistic’, random_state=0,<br> reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=None,<br> silent=None, subsample=1, verbosity=1)xgb_classifier_pt.fit(X_train, y_train)<br>y_pred_xgb_pt = xgb_classifier_pt.predict(X_test)</pre><p>Accuracy after model</p><pre>accuracy_score(y_test, y_pred_xgb_pt)#output  - 0.9824561403508771</pre><h3>Grid search</h3><p>Applying grid search on the model which works on whole data.</p><p>Training the model</p><pre>from sklearn.model_selection import GridSearchCV <br>grid_search = GridSearchCV(xgb_classifier, param_grid=params, scoring= ‘roc_auc’, n_jobs= -1, verbose= 3)<br>grid_search.fit(X_train, y_train)</pre><p>Now comes the implementing it</p><pre>xgb_classifier_pt_gs = XGBClassifier(base_score=0.5, booster=’gbtree’, colsample_bylevel=1,<br> colsample_bynode=1, colsample_bytree=0.3, gamma=0.0,<br> learning_rate=0.3, max_delta_step=0, max_depth=3,<br> min_child_weight=1, missing=None, n_estimators=100, n_jobs=1,<br> nthread=None, objective=’binary:logistic’, random_state=0,<br> reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=None,<br> silent=None, subsample=1, verbosity=1)xgb_classifier_pt_gs.fit(X_train, y_train)<br>y_pred_xgb_pt_gs = xgb_classifier_pt_gs.predict(X_test)<br>accuracy_score(y_test, y_pred_xgb_pt_gs)</pre><pre>#output 0.9824561403508771</pre><p>As,we are getting the nearly same accuracy after applying these tuning method so we will use grid search in this know comes the part of classification report and types of error.</p><h3>Confusion matrix</h3><p>It gives the value of true positive and false negative which will help to predict how much our model is optimized to predict it.</p><pre>from sklearn.metrics import confusion_matrix, classification_report<br>cm = confusion_matrix(y_test, y_pred_xgb_pt)<br>plt.title(‘Heatmap of Confusion Matrix’, fontsize = 15)<br>sns.heatmap(cm, annot = True)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*peg4Mf2UXP1PwBL2GGB7NA.png" /></figure><p>Saving model for deployment</p><pre>pickle.dump(xgb_classifier_pt, open(&#39;heart_disease_detector.pickle&#39;, &#39;wb&#39;))# load model<br>heart_disease_detector_model = pickle.load(open(&#39;heart_disease_detector_detector.pickle&#39;, &#39;rb&#39;))</pre><p>Now are model is dumb into pickle file.now its time for the flask for the model to deploy.</p><p>Now we have to switch towards sublime text editor for the deployment.the main aim is to used html,css with flask in it.</p><blockquote><em>from flask import Flask,render_template,url_for,request<br>import pandas as pd <br>from sklearn.externals import joblib<br>import numpy as np</em></blockquote><blockquote><em>app = Flask(__name__)</em></blockquote><blockquote><a href="http://twitter.com/app"><em>@app</em></a><em>.route(‘/’)<br>def home():<br> return render_template(‘home.html’)</em></blockquote><blockquote><em>def getParameters():<br> parameters = []<br> #parameters.append(request.form(‘name’))<br> parameters.append(request.form[‘age’])<br> parameters.append(request.form[‘sex’])<br> parameters.append(request.form[‘cp’])<br> parameters.append(request.form[‘trestbps’])<br> parameters.append(request.form[‘chol’])<br> parameters.append(request.form[‘fbs’])<br> parameters.append(request.form[‘restecg’])<br> parameters.append(request.form[‘thalach’])<br> parameters.append(request.form[‘exang’])<br> parameters.append(request.form[‘oldpeak’])<br> parameters.append(request.form[‘slope’])<br> parameters.append(request.form[‘ca’])<br> parameters.append(request.form[‘thal’])<br> return parameters</em></blockquote><blockquote><a href="http://twitter.com/app"><em>@app</em></a><em>.route(‘/predict’,methods=[‘POST’])<br>def predict():<br> model = open(“data/Heart_model.pkl”,”rb”)<br> clfr = joblib.load(model)</em></blockquote><blockquote><em>if request.method == ‘POST’:<br> parameters = getParameters()<br> inputFeature = np.asarray(parameters).reshape(1,-1)<br> my_prediction = clfr.predict(inputFeature)<br> return render_template(‘result.html’,prediction = int(my_prediction[0]))</em></blockquote><blockquote><em>if __name__ == ‘__main__’:<br> app.run(debug=True)</em></blockquote><p>The code here depicts the loading of dumb model and then we are accessing the home.html file for the home page which we can discuss further.</p><p>then we have the predict function which will be implemented when we will enter the input 13 constraints as an input in the box and then array of size 13 goes to the data frame for the prediction and return will make the after.html file which tell about the output as an healthy heart according to the value input by user and new webpage open with this classification whelther aperson suffering from it or not.</p><p>In this file we have stored the data and then we will come to know about the input through the data entered by the user and we will come to output and with best prediction on the basis of input value we will enter .Basically this file will work when we have data input from the home.html file where user wll enter the data on the basis of his/her profile.</p><p>Basically this file works as an home page to the web app through flask. We are counter with the input value on the basic of a person profile and how a person will be responsible for his health and how to mange its health for the future for long lasting .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HxDcmw1Nfioh5tAEU8vdUA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qf0FDiw9tyD7Ti1JXq85hw.png" /><figcaption>home of flask app</figcaption></figure><p>This webpage helps us to enter the details and then by clicking the predict button we will come to an output about personal heart’s health.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F-tx4vUwhDzvAm1BYwWj5Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uWaUBVv_SvYgn40lncabHA.png" /></figure><p>This will be predict that the prediction will be healthy heart .</p><p>If you want to implement code from your hand then click the <a href="https://mail.google.com/mail/u/0/#sent/KtbxLvhKPCWtKcNHKdVwPzGkMzJQjRJjnq"><strong>button</strong></a> and implement code end to end with explanation in brief.</p><p>If u like to read this article and have common interest in similar projects then we can grow our network and can work for more real time projects.</p><p>For more details connect with me on my <a href="https://www.linkedin.com/in/karan-choudhary-9102b81a0/"><strong>Linkedin account</strong></a><strong><em>!</em></strong></p><p><strong>THANKS!!!!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cedd1e31b46" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/end-to-end-deployment-of-heart-disease-prediction-through-flask-with-machine-learning-algorithm-5cedd1e31b46">End to End Deployment of Heart Disease Prediction Through Flask With Machine learning Algorithm</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>