<?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 Caner Dabakoglu on Medium]]></title>
        <description><![CDATA[Stories by Caner Dabakoglu on Medium]]></description>
        <link>https://medium.com/@cdabakoglu?source=rss-3ea29de4bb5d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NP_NdEM-ab2XW8qEYZQ3cg.jpeg</url>
            <title>Stories by Caner Dabakoglu on Medium</title>
            <link>https://medium.com/@cdabakoglu?source=rss-3ea29de4bb5d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 03:32:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cdabakoglu/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[Time Series Forecasting — ARIMA, LSTM, Prophet with Python]]></title>
            <link>https://medium.com/@cdabakoglu/time-series-forecasting-arima-lstm-prophet-with-python-e73a750a9887?source=rss-3ea29de4bb5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e73a750a9887</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[facebook]]></category>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <dc:creator><![CDATA[Caner Dabakoglu]]></dc:creator>
            <pubDate>Sun, 23 Jun 2019 08:54:58 GMT</pubDate>
            <atom:updated>2019-06-23T08:54:58.820Z</atom:updated>
            <content:encoded><![CDATA[<h3>Time Series Forecasting — ARIMA, LSTM, Prophet with Python</h3><p>In this article we will try to forecast a time series data basically. We’ll build three different model with Python and inspect their results. Models we will use are ARIMA (Autoregressive Integrated Moving Average), LSTM (Long Short Term Memory Neural Network) and Facebook Prophet. Let’s jump in and start with ARIMA.</p><h3>ARIMA (Autoregressive Integrated Moving Average)</h3><p>ARIMA is a model which is used for predicting future trends on a time series data. It is model that form of regression analysis.</p><ul><li><strong>AR (Autoregression) :</strong> Model that shows a changing variable that regresses on its own lagged/prior values.</li><li><strong>I (Integrated) :</strong> Differencing of raw observations to allow for the time series to become stationary</li><li><strong>MA (Moving average) :</strong> Dependency between an observation and a residual error from a moving average model</li></ul><p>For ARIMA models, a standard notation would be ARIMA with p, d, and q, where integer values substitute for the parameters to indicate the type of ARIMA model used.</p><ul><li><strong>p:</strong> the number of lag observations in the model; also known as the lag order.</li><li><strong>d:</strong> the number of times that the raw observations are differenced; also known as the degree of differencing.</li><li><strong>q:</strong> the size of the moving average window; also known as the order of the moving average.</li></ul><p>For more information about ARIMA you can check: <br><a href="https://www.quora.com/What-is-ARIMA">What is ARIMA</a> <br><a href="https://www.investopedia.com/terms/a/autoregressive-integrated-moving-average-arima.asp">Autoregressive Integrated Moving Average (ARIMA)</a></p><h3>LSTM Neural Network</h3><blockquote><em>LSTM stands for long short term memory. It is a model or architecture that extends the memory of recurrent neural networks. Typically, recurrent neural networks have ‘short term memory’ in that they use persistent previous information to be used in the current neural network. Essentially, the previous information is used in the present task. That means we do not have a list of all of the previous information available for the neural node. LSTM introduces long-term memory into recurrent neural networks. It mitigates the vanishing gradient problem, which is where the neural network stops learning because the updates to the various weights within a given neural network become smaller and smaller. It does this by using a series of ‘gates’. These are contained in memory blocks which are connected through layers, like this:</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/0*kY5G6-jVm6iII65m.png" /></figure><blockquote><em>LSTM work There are three types of gates within a unit: Input Gate: Scales input to cell (write) Output Gate: Scales output to cell (read) Forget Gate: Scales old cell value (reset) Each gate is like a switch that controls the read/write, thus incorporating the long-term memory function into the model.</em></blockquote><p>For more detail: <br><a href="https://hub.packtpub.com/what-is-lstm/">What is LSTM?</a> <br><a href="https://www.quora.com/What-is-LSTM">What is LSTM? — Quora</a> <br><a href="https://en.wikipedia.org/wiki/Long_short-term_memory">Wikipedia</a></p><h3>Prophet</h3><blockquote><em>Prophet is a procedure for forecasting time series data based on an additive model where non-linear trends are fit with yearly, weekly, and daily seasonality, plus holiday effects. It works best with time series that have strong seasonal effects and several seasons of historical data. Prophet is robust to missing data and shifts in the trend, and typically handles outliers well.</em></blockquote><p><a href="https://facebook.github.io/prophet/">Facebook’s Prophet Web Page</a><br><a href="https://peerj.com/preprints/3190.pdf">Forecasting at Scale</a></p><h3>FORECAST</h3><h3>Read Dataset</h3><pre><strong>import</strong> <strong>numpy</strong> <strong>as</strong> <strong>np</strong><br><strong>import</strong> <strong>pandas</strong> <strong>as</strong> <strong>pd</strong><br><strong>from</strong> <strong>statsmodels.tsa.statespace.sarimax</strong> <strong>import</strong> SARIMAX<br><strong>from</strong> <strong>statsmodels.graphics.tsaplots</strong> <strong>import</strong> plot_acf,plot_pacf <br><strong>from</strong> <strong>statsmodels.tsa.seasonal</strong> <strong>import</strong> seasonal_decompose <br><strong>from</strong> <strong>pmdarima</strong> <strong>import</strong> auto_arima                        <br><strong>from</strong> <strong>sklearn.metrics</strong> <strong>import</strong> mean_squared_error<br><strong>from</strong> <strong>statsmodels.tools.eval_measures</strong> <strong>import</strong> rmse<br><strong>import</strong> <strong>warnings</strong><br>warnings.filterwarnings(&quot;ignore&quot;)</pre><pre>df = pd.read_csv(&#39;monthly-beer-production-in-austr.csv&#39;)</pre><pre>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*MGFHRlTIEjPL4m5soXQiLw.png" /></figure><pre>df.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*mqVJ9kJwdeWU0L3JD-KErQ.png" /></figure><pre>df.Month = pd.to_datetime(df.Month)</pre><pre>df = df.set_index(&quot;Month&quot;)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*o6AgrbT6NsLyTjyYjlkRkA.png" /></figure><pre>df.index.freq = &#39;MS&#39;</pre><pre>ax = df[&#39;Monthly beer production&#39;].plot(figsize = (16,5), title = &quot;Monthly Beer Production&quot;)<br>ax.set(xlabel=&#39;Dates&#39;, ylabel=&#39;Total Production&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*dRqUJR9aB84vDIXWwE6RHQ.png" /></figure><p>When we look at plot we can sey there is a seasonality in data. That’s why we will use SARIMA (Seasonal ARIMA) instead of ARIMA.</p><blockquote><em>Seasonal ARIMA, is an extension of ARIMA that explicitly supports univariate time series data with a seasonal component. It adds three new hyperparameters to specify the autoregression (AR), differencing (I) and moving average (MA) for the seasonal component of the series, as well as an additional parameter for the period of the seasonality.</em></blockquote><blockquote><em>There are four seasonal elements that are not part of ARIMA that must be configured; they are:<br></em><strong><em>P:</em></strong><em> Seasonal autoregressive order.<br></em><strong><em>D:</em></strong><em> Seasonal difference order.<br></em><strong><em>Q:</em></strong><em> Seasonal moving average order.<br></em><strong><em>m:</em></strong><em> The number of time steps for a single seasonal period.</em></blockquote><pre>a = seasonal_decompose(df[&quot;Monthly beer production&quot;], model = &quot;add&quot;)<br>a.plot();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*MooIzsjjfCtDcAx7ieFdXA.png" /></figure><pre><strong>import</strong> <strong>matplotlib.pyplot</strong> <strong>as</strong> <strong>plt</strong><br>plt.figure(figsize = (16,7))<br>a.seasonal.plot();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/981/1*xRZOB54d94v7inK6eBjwOA.png" /></figure><h3>ARIMA Forecast</h3><p>Let’s run auto_arima() function to get best p,d,q,P,D,Q values</p><pre>auto_arima(df[&#39;Monthly beer production&#39;], seasonal=<strong>True</strong>, m=12,max_p=7, max_d=5,max_q=7, max_P=4, max_D=4,max_Q=4).summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*N7vPqes-nGyOf2rt338vCQ.png" /></figure><p>As we can see best arima model chosen by auto_arima() is SARIMAX(2, 1, 1)x(4, 0, 3, 12)</p><p>Let’s split the data into train and test set</p><pre>train_data = df[:len(df)-12]<br>test_data = df[len(df)-12:]</pre><pre>arima_model = SARIMAX(train_data[&#39;Monthly beer production&#39;], order = (2,1,1), seasonal_order = (4,0,3,12))<br>arima_result = arima_model.fit()<br>arima_result.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*e_Dyh_KIBNS2iaBkzK3Oeg.png" /></figure><pre>arima_pred = arima_result.predict(start = len(train_data), end = len(df)-1, typ=&quot;levels&quot;).rename(&quot;ARIMA Predictions&quot;)</pre><pre>arima_pred</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*h4odOAhQ85QoyadOz7IlLw.png" /></figure><pre>test_data[&#39;Monthly beer production&#39;].plot(figsize = (16,5), legend=<strong>True</strong>)</pre><pre>arima_pred.plot(legend = <strong>True</strong>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*zH27A7dyCzLU0wiT9fM6vw.png" /></figure><pre>arima_rmse_error = rmse(test_data[&#39;Monthly beer production&#39;], arima_pred)<br>arima_mse_error = arima_rmse_error**2<br>mean_value = df[&#39;Monthly beer production&#39;].mean()<br><br>print(f&#39;MSE Error: <strong>{arima_mse_error}\n</strong>RMSE Error: <strong>{arima_rmse_error}\n</strong>Mean: <strong>{mean_value}</strong>&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*B8TdZZKQXMyHRqiQzZro3w.png" /></figure><pre>test_data[&#39;ARIMA_Predictions&#39;] = arima_pred</pre><h3>LSTM Forecast</h3><p>First we’ll scale our train and test data with MinMaxScaler</p><pre><strong>from</strong> <strong>sklearn.preprocessing</strong> <strong>import</strong> MinMaxScaler<br>scaler = MinMaxScaler()</pre><pre>scaler.fit(train_data)<br>scaled_train_data = scaler.transform(train_data)<br>scaled_test_data = scaler.transform(test_data)</pre><p>Before creating LSTM model we should create a Time Series Generator object.</p><pre><strong>from</strong> <strong>keras.preprocessing.sequence</strong> <strong>import</strong> TimeseriesGenerator<br><br>n_input = 12<br>n_features= 1<br>generator = TimeseriesGenerator(scaled_train_data, scaled_train_data, length=n_input, batch_size=1)</pre><pre><strong>from</strong> <strong>keras.models</strong> <strong>import</strong> Sequential<br><strong>from</strong> <strong>keras.layers</strong> <strong>import</strong> Dense<br><strong>from</strong> <strong>keras.layers</strong> <strong>import</strong> LSTM<br><br>lstm_model = Sequential()<br>lstm_model.add(LSTM(200, activation=&#39;relu&#39;, input_shape=(n_input, n_features)))<br>lstm_model.add(Dense(1))<br>lstm_model.compile(optimizer=&#39;adam&#39;, loss=&#39;mse&#39;)<br><br>lstm_model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*jZZ7T9UTGGvh4qUOQEddaA.png" /></figure><pre>lstm_model.fit_generator(generator,epochs=20)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*JEzznYPUn3L3WTdAPtV9aQ.png" /></figure><pre>losses_lstm = lstm_model.history.history[&#39;loss&#39;]<br>plt.figure(figsize=(12,4))<br>plt.xlabel(&quot;Epochs&quot;)<br>plt.ylabel(&quot;Loss&quot;)<br>plt.xticks(np.arange(0,21,1))<br>plt.plot(range(len(losses_lstm)),losses_lstm);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*qod5BC21-u6bzVXp_29KZg.png" /></figure><pre>lstm_predictions_scaled = list()<br><br>batch = scaled_train_data[-n_input:]<br>current_batch = batch.reshape((1, n_input, n_features))<br><br><strong>for</strong> i <strong>in</strong> range(len(test_data)):   <br>    lstm_pred = lstm_model.predict(current_batch)[0]<br>    lstm_predictions_scaled.append(lstm_pred) <br>    current_batch = np.append(current_batch[:,1:,:],[[lstm_pred]],axis=1)</pre><p>As you know we scaled our data that’s why we have to inverse it to see true predictions.</p><pre>lstm_predictions_scaled</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*tL5TY56qd9-GFdOJhtgPrQ.png" /></figure><pre>lstm_predictions = scaler.inverse_transform(lstm_predictions_scaled)</pre><pre>lstm_predictions</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/1*BYCzCEkTK3kIJlXzowz7Nw.png" /></figure><pre>test_data[&#39;LSTM_Predictions&#39;] = lstm_predictions</pre><pre>test_data</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*PBHJPPpLc_UR8fITmMbWaQ.png" /></figure><pre>test_data[&#39;Monthly beer production&#39;].plot(figsize = (16,5), legend=<strong>True</strong>)</pre><pre>test_data[&#39;LSTM_Predictions&#39;].plot(legend = <strong>True</strong>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*DGtuQzrWrZnY3CfOiTWTWw.png" /></figure><pre>lstm_rmse_error = rmse(test_data[&#39;Monthly beer production&#39;], test_data[&quot;LSTM_Predictions&quot;])<br>lstm_mse_error = lstm_rmse_error**2<br>mean_value = df[&#39;Monthly beer production&#39;].mean()<br><br>print(f&#39;MSE Error: <strong>{lstm_mse_error}\n</strong>RMSE Error: <strong>{lstm_rmse_error}\n</strong>Mean: <strong>{mean_value}</strong>&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*zKMB1Jh5gE6yDKEKocH71A.png" /></figure><h3>Prophet Forecast</h3><pre>df.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*SkrCJ8JSxxG3oB2BbU_x1w.png" /></figure><pre>df_pr = df.copy()<br>df_pr = df.reset_index()</pre><pre>df_pr.columns = [&#39;ds&#39;,&#39;y&#39;] <em># To use prophet column names should be like that</em></pre><pre>train_data_pr = df_pr.iloc[:len(df)-12]<br>test_data_pr = df_pr.iloc[len(df)-12:]</pre><pre><strong>from</strong> <strong>fbprophet</strong> <strong>import</strong> Prophet</pre><pre>m = Prophet()<br>m.fit(train_data_pr)<br>future = m.make_future_dataframe(periods=12,freq=&#39;MS&#39;)<br>prophet_pred = m.predict(future)</pre><pre>prophet_pred.tail()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*yJqlP02uzEFCBlUCDzWkuQ.png" /></figure><pre>prophet_pred = pd.DataFrame({&quot;Date&quot; : prophet_pred[-12:][&#39;ds&#39;], &quot;Pred&quot; : prophet_pred[-12:][&quot;yhat&quot;]})</pre><pre>prophet_pred = prophet_pred.set_index(&quot;Date&quot;)</pre><pre>prophet_pred.index.freq = &quot;MS&quot;</pre><pre>prophet_pred</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/171/1*9ALjEHUbWJS2XH4xf0d3kQ.png" /></figure><pre>test_data[&quot;Prophet_Predictions&quot;] = prophet_pred[&#39;Pred&#39;].values</pre><pre><strong>import</strong> <strong>seaborn</strong> <strong>as</strong> <strong>sns</strong></pre><pre>plt.figure(figsize=(16,5))<br>ax = sns.lineplot(x= test_data.index, y=test_data[&quot;Monthly beer production&quot;])<br>sns.lineplot(x=test_data.index, y = test_data[&quot;Prophet_Predictions&quot;]);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*AuHXShF2TXdayNvTbDOoHg.png" /></figure><pre>prophet_rmse_error = rmse(test_data[&#39;Monthly beer production&#39;], test_data[&quot;Prophet_Predictions&quot;])<br>prophet_mse_error = prophet_rmse_error**2<br>mean_value = df[&#39;Monthly beer production&#39;].mean()<br><br>print(f&#39;MSE Error: <strong>{prophet_mse_error}\n</strong>RMSE Error: <strong>{prophet_rmse_error}\n</strong>Mean: <strong>{mean_value}</strong>&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*xTnTDSq19LATi797dIaXgg.png" /></figure><pre>rmse_errors = [arima_rmse_error, lstm_rmse_error, prophet_rmse_error]<br>mse_errors = [arima_mse_error, lstm_mse_error, prophet_mse_error]<br>errors = pd.DataFrame({&quot;Models&quot; : [&quot;ARIMA&quot;, &quot;LSTM&quot;, &quot;Prophet&quot;],&quot;RMSE Errors&quot; : rmse_errors, &quot;MSE Errors&quot; : mse_errors})</pre><pre>plt.figure(figsize=(16,9))<br>plt.plot_date(test_data.index, test_data[&quot;Monthly beer production&quot;], linestyle=&quot;-&quot;)<br>plt.plot_date(test_data.index, test_data[&quot;ARIMA_Predictions&quot;], linestyle=&quot;-.&quot;)<br>plt.plot_date(test_data.index, test_data[&quot;LSTM_Predictions&quot;], linestyle=&quot;--&quot;)<br>plt.plot_date(test_data.index, test_data[&quot;Prophet_Predictions&quot;], linestyle=&quot;:&quot;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*ajY4C-kiIxwUjUNEyx_Omw.png" /></figure><pre>print(f&quot;Mean: {test_data[&#39;Monthly beer production&#39;].mean()}&quot;)</pre><pre>errors</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*-lfbWzlMmkmChbE-x9K75w.png" /></figure><pre>test_data</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*F3cD4cNyh0b9t6X1XynazQ.png" /></figure><p>Don’t forget they are just quick and basic predictions so you can improve these models with tuning and according to your data and business knowledge.</p><p>Thanks!</p><p>LinkedIn: <a href="https://www.linkedin.com/in/canerdabakoglu/">https://www.linkedin.com/in/canerdabakoglu/</a></p><p>GitHub: <a href="https://github.com/cdabakoglu">https://github.com/cdabakoglu</a></p><p>Kaggle: <a href="https://www.kaggle.com/cdabakoglu">https://www.kaggle.com/cdabakoglu</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e73a750a9887" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fraud Detection — ANN and SMOTE Sampling with Python]]></title>
            <link>https://medium.com/@cdabakoglu/fraud-detection-ann-and-smote-sampling-with-python-c12f2f55c00a?source=rss-3ea29de4bb5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c12f2f55c00a</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[fraud-detection]]></category>
            <category><![CDATA[credit-cards]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Caner Dabakoglu]]></dc:creator>
            <pubDate>Thu, 03 Jan 2019 16:40:43 GMT</pubDate>
            <atom:updated>2019-01-03T16:40:43.063Z</atom:updated>
            <content:encoded><![CDATA[<h3>Fraud Detection — ANN and SMOTE Sampling with Python</h3><h3>Credit Card Fraud Detection — Neural Networks and SMOTE Sampling</h3><h3>About Dataset</h3><p>“The datasets contains transactions made by credit cards in September 2013 by european cardholders. This dataset presents transactions that occurred in two days, where we have 492 frauds out of 284,807 transactions. The dataset is highly unbalanced, the positive class (frauds) account for 0.172% of all transactions.</p><p>It contains only numerical input variables which are the result of a PCA transformation. Unfortunately, due to confidentiality issues, we cannot provide the original features and more background information about the data. Features V1, V2, … V28 are the principal components obtained with PCA, the only features which have not been transformed with PCA are ‘Time’ and ‘Amount’. Feature ‘Time’ contains the seconds elapsed between each transaction and the first transaction in the dataset. The feature ‘Amount’ is the transaction Amount, this feature can be used for example-dependant cost-senstive learning. Feature ‘Class’ is the response variable and it takes value 1 in case of fraud and 0 otherwise.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/0*_rBvHqhR34UnZ9Q7.jpg" /></figure><h3>Import Libraries</h3><pre>import numpy as np <br>import pandas as pd <br>import keras<br>import matplotlib.pyplot as plt<br>import seaborn as sns</pre><h3>Read and Explore Data</h3><pre>df = pd.read_csv(&quot;../input/creditcard.csv&quot;)</pre><pre><em># First 5 rows of data</em><br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*fnVgyFmL0_uWYTR_QlxBtw.png" /></figure><pre>df.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*oI6qP0S5hg_Ss1_5r3OXcQ.png" /></figure><pre>df.columns</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*tfTkUwT3knP5gpxG4lgRyQ.png" /></figure><h3>Normalize ‘Amount’</h3><pre>from sklearn.preprocessing import StandardScaler</pre><pre>df[&#39;Amount(Normalized)&#39;] = StandardScaler().fit_transform(df[&#39;Amount&#39;].values.reshape(-1,1))</pre><pre>df.iloc[:,[29,31]].head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*vThpx8cMvGs_KkoY27aPvQ.png" /></figure><pre>df = df.drop(columns = [&#39;Amount&#39;, &#39;Time&#39;], axis=1) <em># This columns are not necessary anymore.</em></pre><h3>Data PreProcessing</h3><pre>X = df.drop(&#39;Class&#39;, axis=1)<br>y = df[&#39;Class&#39;]</pre><h3>Train-Test Split</h3><pre>from sklearn.model_selection import train_test_split</pre><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)</pre><pre><em># We are transforming data to numpy array to implementing with keras</em><br>X_train = np.array(X_train)<br>X_test = np.array(X_test)<br>y_train = np.array(y_train)<br>y_test = np.array(y_test)</pre><h3>Artificial Neural Networks</h3><pre>from keras.models import Sequential<br>from keras.layers import Dense, Dropout</pre><pre>model = Sequential([<br>    Dense(units=20, input_dim = X_train.shape[1], activation=&#39;relu&#39;),<br>    Dense(units=24,activation=&#39;relu&#39;),<br>    Dropout(0.5),<br>    Dense(units=20,activation=&#39;relu&#39;),<br>    Dense(units=24,activation=&#39;relu&#39;),<br>    Dense(1, activation=&#39;sigmoid&#39;)<br>])</pre><pre>model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*whJfV6fZv0rZUz4ejn1FxA.png" /></figure><pre>model.compile(optimizer=&#39;adam&#39;, loss=&#39;binary_crossentropy&#39;, metrics=[&#39;accuracy&#39;])<br>model.fit(X_train, y_train, batch_size=30, epochs=5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*VDiKlQP8IR7C0tNXMEQUkA.png" /></figure><pre>score = model.evaluate(X_test, y_test)<br>print(&#39;Test Accuracy: <strong>{:.2f}</strong>%<strong>\n</strong>Test Loss: <strong>{}</strong>&#39;.format(score[1]*100,score[0]))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*yDmqmzB1dPqsF_LmWdAgaA.png" /></figure><pre>from sklearn.metrics import confusion_matrix, classification_report</pre><pre>y_pred = model.predict(X_test)<br>y_test = pd.DataFrame(y_test)</pre><pre>cm = confusion_matrix(y_test, y_pred.round())</pre><pre>sns.heatmap(cm, annot=True, fmt=&#39;.0f&#39;, cmap=&#39;cividis_r&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*NiwAmfiu0AUoircmebD9qQ.png" /></figure><p>Our results is fine however it is not the best way to do things like that. Since our dataset is unbalanced (we have 492 frauds out of 284,807 transactions) we will use ‘smote sampling’. Basically smote turn our inbalanced data to balanced data. For brief explanation you can check the link: <a href="http://rikunert.com/SMOTE_explained">http://rikunert.com/SMOTE_explained</a></p><h3>SMOTE Sampling</h3><pre>from imblearn.over_sampling import SMOTE</pre><pre>X_smote, y_smote = SMOTE().fit_sample(X, y)</pre><pre>X_smote = pd.DataFrame(X_smote)<br>y_smote = pd.DataFrame(y_smote)</pre><pre>y_smote.iloc[:,0].value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*rKiorvqpxdaAea9E9e3PUw.png" /></figure><pre>X_train, X_test, y_train, y_test = train_test_split(X_smote, y_smote, test_size=0.3, random_state=0)</pre><pre>X_train = np.array(X_train)<br>X_test = np.array(X_test)<br>y_train = np.array(y_train)<br>y_test = np.array(y_test)</pre><pre>model.compile(optimizer=&#39;adam&#39;, loss=&#39;binary_crossentropy&#39;, metrics=[&#39;accuracy&#39;])<br>model.fit(X_train, y_train, batch_size = 30, epochs = 5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*n7QRMn7Zu9n1Uqyu7eDd4g.png" /></figure><pre>score = model.evaluate(X_test, y_test)<br>print(&#39;Test Accuracy: <strong>{:.2f}</strong>%<strong>\n</strong>Test Loss: <strong>{}</strong>&#39;.format(score[1]*100,score[0]))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*LP_36VE5YPiXOCShdXEBxw.png" /></figure><pre>y_pred = model.predict(X_test)<br>y_test = pd.DataFrame(y_test)<br>cm = confusion_matrix(y_test, y_pred.round())<br>sns.heatmap(cm, annot=True, fmt=&#39;.0f&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*QhDytm9GDl_nIIyK_APNKw.png" /></figure><p>It is not the true result ’cause we used data with smote sampling because of that number of class 0 and class 1 are equal in here. That’s why we’ll use whole data we imported at the beginning.</p><pre>y_pred2 = model.predict(X)<br>y_test2 = pd.DataFrame(y)<br>cm2 = confusion_matrix(y_test2, y_pred2.round())<br>sns.heatmap(cm2, annot=True, fmt=&#39;.0f&#39;, cmap=&#39;coolwarm&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*62_Jcrkzp1RBwB6nDR3IUg.png" /></figure><pre>scoreNew = model.evaluate(X, y)<br>print(&#39;Test Accuracy: <strong>{:.2f}</strong>%<strong>\n</strong>Test Loss: <strong>{}</strong>&#39;.format(scoreNew[1]*100,scoreNew[0]))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*s3U7A-h7LKJM8ZLTV2gKXA.png" /></figure><pre>print(classification_report(y_test2, y_pred2.round()))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*QITziJTWPpSLnISl3EAMeg.png" /></figure><p>Thank you for your time!</p><p>LinkedIn: <a href="https://www.linkedin.com/in/canerdabakoglu/">https://www.linkedin.com/in/canerdabakoglu/</a></p><p>GitHub: <a href="https://github.com/cdabakoglu">https://github.com/cdabakoglu</a></p><p>Kaggle: <a href="https://www.kaggle.com/cdabakoglu">https://www.kaggle.com/cdabakoglu</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c12f2f55c00a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Support Vector Machine (SVM) ?]]></title>
            <link>https://medium.com/@cdabakoglu/what-is-support-vector-machine-svm-fd0e9e39514f?source=rss-3ea29de4bb5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd0e9e39514f</guid>
            <category><![CDATA[voices]]></category>
            <category><![CDATA[support-vector-machine]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[classification]]></category>
            <dc:creator><![CDATA[Caner Dabakoglu]]></dc:creator>
            <pubDate>Sun, 23 Dec 2018 08:01:00 GMT</pubDate>
            <atom:updated>2018-12-23T08:01:00.665Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is Support Vector Machine (SVM) ?-with Python</h3><h3>SUPPORT VECTOR MACHINE</h3><h3>CONTENT</h3><ol><li><a href="https://www.kaggleusercontent.com/kf/8753665/eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..bS4GrLE2I9JzfpoMrVI--A.M7nu7EhI89pbsFaAE6WCQiimtbTg0uRqcxh_nSorY-VHKeXP1Cm-3cvYmRW86U5M19ciyA_c72LjPDgjsNdJMB0DyT8eYzbmcDpMps6akJFR_l83Att85AltS1as4BlLccmw66bmDYfGs6fRNClF0tI8ZDr0IuXFo6pl3SwapT4.nY6Sl87oR1HDodx-6emNDA/__results__.html#1">What is Support Vector Machine(SVM)</a></li><li><a href="https://www.kaggleusercontent.com/kf/8753665/eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..bS4GrLE2I9JzfpoMrVI--A.M7nu7EhI89pbsFaAE6WCQiimtbTg0uRqcxh_nSorY-VHKeXP1Cm-3cvYmRW86U5M19ciyA_c72LjPDgjsNdJMB0DyT8eYzbmcDpMps6akJFR_l83Att85AltS1as4BlLccmw66bmDYfGs6fRNClF0tI8ZDr0IuXFo6pl3SwapT4.nY6Sl87oR1HDodx-6emNDA/__results__.html#2">SVM Parameters</a></li><li><a href="https://www.kaggleusercontent.com/kf/8753665/eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..bS4GrLE2I9JzfpoMrVI--A.M7nu7EhI89pbsFaAE6WCQiimtbTg0uRqcxh_nSorY-VHKeXP1Cm-3cvYmRW86U5M19ciyA_c72LjPDgjsNdJMB0DyT8eYzbmcDpMps6akJFR_l83Att85AltS1as4BlLccmw66bmDYfGs6fRNClF0tI8ZDr0IuXFo6pl3SwapT4.nY6Sl87oR1HDodx-6emNDA/__results__.html#3">Import Libraries and Read Data</a></li><li><a href="https://www.kaggleusercontent.com/kf/8753665/eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..bS4GrLE2I9JzfpoMrVI--A.M7nu7EhI89pbsFaAE6WCQiimtbTg0uRqcxh_nSorY-VHKeXP1Cm-3cvYmRW86U5M19ciyA_c72LjPDgjsNdJMB0DyT8eYzbmcDpMps6akJFR_l83Att85AltS1as4BlLccmw66bmDYfGs6fRNClF0tI8ZDr0IuXFo6pl3SwapT4.nY6Sl87oR1HDodx-6emNDA/__results__.html#4">Visualize Data</a></li><li><a href="https://www.kaggleusercontent.com/kf/8753665/eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0..bS4GrLE2I9JzfpoMrVI--A.M7nu7EhI89pbsFaAE6WCQiimtbTg0uRqcxh_nSorY-VHKeXP1Cm-3cvYmRW86U5M19ciyA_c72LjPDgjsNdJMB0DyT8eYzbmcDpMps6akJFR_l83Att85AltS1as4BlLccmw66bmDYfGs6fRNClF0tI8ZDr0IuXFo6pl3SwapT4.nY6Sl87oR1HDodx-6emNDA/__results__.html#5">Create and Evaluate Model</a></li></ol><h3>What is Support Vector Machine (SVM)</h3><p>SVM or Support Vector Machine algorithm tries to draw a hyperplane between two classes to seperate them. There can be many hyperplane but SVM’s purpose is finding maximum margin or finding maximum distance between data points from each classes. This data points are nearest data points to hyperlane from each classes. Let’s look image below it explains better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/0*rIGWbxfCPvxr_cz1" /></figure><p>Also SVM uses a technique called <strong>kernel trick</strong> to transform the data. If datapoints have low dimensional space and it wouldn’t be able to draw a hyperplane it tries to add a new dimension to data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*IlsAsELsoeN_7xtP" /></figure><p>Now I’ll explain some parameters in SVM and we’ll try to use SVM to classify voices according to features.</p><h3>SVM — Parameters</h3><p><strong>C Parameter</strong> <br>C parameter controls trade-off between training points.</p><ul><li>Small C: Large margin</li><li>Large C: Small margin, it has potential to overfit. <br>If you ask which is better to use, answer is ‘it depends on your data’. It would be better if you try different C values to find best score.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yOFKXNU24NBQRaA2.png" /></figure><p><strong>Kernel</strong> <br>You can choose the kernel type used by SVM. It can be ‘linear’, ‘rbf’, ‘poly’, ‘sigmoid’, ‘precomputed’. And yes, answer is still same ‘it depends your data’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*nW5lxj8YmVW59-Fd.png" /></figure><p><strong>Gamma Parameter</strong> <br>It is kernel coefficient. You use it if you choose ‘rbf’, ‘poly’ or ‘sigmoid’ as a kernel.</p><p>Also there is ‘degree’ parameters. It is used for ‘poly’ kernel to define degree of polynomial kernel. It is 3 by default.</p><h3>Import Libraries and Read Data</h3><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns</pre><pre><em># Read Data</em><br>df = pd.read_csv(&quot;../input/voice.csv&quot;)</pre><pre><em># First 5 Rows of Data</em><br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*P4z1Imbp8AdioyZfcxGXTw.png" /></figure><pre>df.columns</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*5Z9MykYI_r6RluBx2Txbag.png" /></figure><pre>df.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*XJx5S0A6wc--S6WvAwizLA.png" /></figure><h3>Visualize Data</h3><pre>sns.pairplot(df, hue=&#39;label&#39;, vars=[&#39;skew&#39;, &#39;kurt&#39;,<br>       &#39;sp.ent&#39;, &#39;sfm&#39;, &#39;mode&#39;,&#39;meanfun&#39;,<br>       &#39;meandom&#39;,&#39;dfrange&#39;])<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SVzXMTOCvj3Hxx6y.png" /></figure><pre>sns.countplot(df.label)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/0*BypHpf57WnHx_wLj.png" /></figure><pre>sns.scatterplot(x = &#39;skew&#39;, y = &#39;kurt&#39;, hue = &#39;label&#39;, data = df)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/0*1mYEudUQNfrXiAXV.png" /></figure><pre>plt.figure(figsize=(20,10))<br>sns.heatmap(df.corr(), annot=True, linewidth=.5, fmt=&#39;.2f&#39;, linecolor = &#39;grey&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t7_ofJ4blWBZVRsj.png" /></figure><h3>Create and Evaluate Model</h3><pre>X = df.drop([&#39;label&#39;],axis=1)<br>y = df.label</pre><p>We’ll use 70% of our data to train our model and we’ll test it with 30% of the data.</p><pre><strong>from</strong> sklearn.model_selection <strong>import</strong> train_test_split<br><br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state=42)</pre><pre><em># Import SVM</em><br><strong>from</strong> sklearn.svm <strong>import</strong> SVC<br><br>svm = SVC()<br>svm.fit(X_train, y_train)</pre><pre>y_pred = svm.predict(X_test)</pre><pre><strong>from</strong> sklearn.metrics <strong>import</strong> confusion_matrix, classification_report</pre><pre>cm = confusion_matrix(y_test, y_pred)</pre><pre>sns.heatmap(cm, annot=True, cmap=&quot;Paired_r&quot;, linewidth=2, linecolor=&#39;w&#39;, fmt=&#39;.0f&#39;)<br>plt.xlabel(&#39;Predicted Value&#39;)<br>plt.ylabel(&#39;True Value&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/0*PsJl_jzRyeT8wy7e.png" /></figure><p>Test Accuracy: 71.29%</p><p>Our accuracy is not well and as you can see confusion matrix above our prediction is not good. So let’s try to improve our model. At first we’ll normalize our data after that we’ll apply some parameter optimizations.</p><pre><em># Normalization</em><br>X = (X - np.min(X)) / (np.max(X) - np.min(X)).values</pre><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 42)</pre><p>Let’s fit our model.</p><pre>svm.fit(X_train, y_train)</pre><pre>y_pred = svm.predict(X_test)</pre><pre>cm = confusion_matrix(y_test,y_pred)</pre><pre>sns.heatmap(cm, annot=True, fmt=&#39;.0f&#39;, cmap=&#39;brg_r&#39;)<br>plt.xlabel(&#39;Predicted Value&#39;)<br>plt.ylabel(&#39;True Value&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/0*i0YCmVrsIQOF5DDB.png" /></figure><p>Test Accuracy: 97.27%</p><p>Wow! Our score increase to 97.27% and all we did is normalize the data! We can see importance of normalizaton in here. Let’s try to find best parameters for our model.</p><pre><strong>from</strong> sklearn.model_selection <strong>import</strong> GridSearchCV</pre><pre>param_grid = {&#39;C&#39;:[0.1, 1, 10, 100], &#39;gamma&#39;:[1, 0.1, 0.01, 0.001], &#39;kernel&#39; : [&#39;rbf&#39;, &#39;poly&#39;, &#39;sigmoid&#39;, &#39;linear&#39;]}</pre><pre>grid = GridSearchCV(SVC(), param_grid, refit=True, verbose=4)</pre><pre>grid.fit(X_train, y_train)</pre><pre>print(&quot;Best Parameters: &quot;,grid.best_params_)</pre><p>Best Parameters: {‘C’: 10, ‘gamma’: 1, ‘kernel’: ‘rbf’}</p><pre>grid_pred = grid.predict(X_test)</pre><pre>cmNew = confusion_matrix(y_test, grid_pred)</pre><pre>sns.heatmap(cmNew, annot=True, fmt=&#39;.0f&#39;, cmap=&#39;gray_r&#39;)<br>plt.xlabel(&#39;Predicted Value&#39;)<br>plt.ylabel(&#39;True Value&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/0*Q8P1WQwFBlbeBIJ5.png" /></figure><p>Test Accuracy: <strong>97.79%</strong></p><pre>print(classification_report(y_test, grid_pred))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*IcfXqAQd_pTyrLD6-2Sj-w.png" /></figure><p>Our test score incresed a little bit again and we reached <strong>97.79%</strong> of accuracy.</p><p>Thank you for your time!</p><p>LinkedIn: <a href="https://www.linkedin.com/in/canerdabakoglu/">https://www.linkedin.com/in/canerdabakoglu/</a></p><p>GitHub: <a href="https://github.com/cdabakoglu">https://github.com/cdabakoglu</a></p><p>Kaggle: <a href="https://www.kaggle.com/cdabakoglu">https://www.kaggle.com/cdabakoglu</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd0e9e39514f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Convolutional Neural Network (CNN) ? — with Keras]]></title>
            <link>https://medium.com/@cdabakoglu/what-is-convolutional-neural-network-cnn-with-keras-cab447ad204c?source=rss-3ea29de4bb5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/cab447ad204c</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[convolution-neural-net]]></category>
            <category><![CDATA[image-processing]]></category>
            <dc:creator><![CDATA[Caner Dabakoglu]]></dc:creator>
            <pubDate>Wed, 12 Dec 2018 14:05:47 GMT</pubDate>
            <atom:updated>2018-12-12T14:05:47.328Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is Convolutional Neural Network (CNN) ? — with Keras</h3><h3>CONVOLUTIONAL NEURAL NETWORK</h3><h4>What is Convolutional Neural Network (CNN or ConvNet) ?</h4><p>Convolutional Neural Network is a deep learning algorithm which is used for recognizing images. This algorithm clusters images by similarity and perform object recognition within scenes. CNN uses unique feature of images (e.g. cat’s tail and ears, airplane’s wing and engine etc.) to identify object that is placed on the image. Actually this process is very similar with what our brain does to identify objects. <br>Traditional neural networks are not ideal for image processing that’s why we are using CNN. Although CNN is not too different from ANN. Because in the end CNN algorithm uses Artificial Neural Networks but before that CNN uses some layers to gather information and determine some features from the image.</p><blockquote>Before we start you may check that:</blockquote><blockquote><strong>Logistic Regression and Implementing ML Algorithms: </strong><a href="https://medium.com/@cdabakoglu/heart-disease-logistic-regression-machine-learning-d0ebf08e55c0">https://medium.com/@cdabakoglu/heart-disease-logistic-regression-machine-learning-d0ebf08e55c0</a><br><strong>Artificial Neural Network- Implementing with Keras:</strong><br><a href="https://medium.com/@cdabakoglu/artificial-neural-network-with-keras-d858f82f90c5">https://medium.com/@cdabakoglu/artificial-neural-network-with-keras-d858f82f90c5</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*N4h1SgwbWNmtrRhszM9EJg.png" /></figure><p>What are these layers or processes? How CNN works?</p><ul><li>Convolution</li><li>Padding</li><li>Pooling</li><li>Flattening</li><li>Full Connection</li></ul><h4>Convolutional Layer (Convolutional Operation)</h4><p>This process is main process for CNN. In this operation there is a feature detector or filter. This filter detects edges or specific shapes. Filter is placed top left of image and multiplied with value on same indices. After that all results are summed and this result is written to output matrix. Then filter slips to right to do this whole processes again and again. Usually filter slips one by one but it can be change according to your model and this slipping process is called ‘stride’. Bigger stride means smaller output. Sometimes stride value is increased to decrease output size and time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/0*g55lEYL4tf8seMmc" /></figure><p>Let’s try to understand process mentioned above with a visualization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*JfvaKDD-G4SdfkAT" /></figure><p>After convolutional operations we will use an activation function to break up linearity. We want to increase non-linearity otherwise algorithm can’t understand image and act like it is a linear function. In other algorithms we usually use sigmoid and tanh functions as activation functions but in Convolutional Neural Network we are using <strong><em>ReLU. </em></strong>Becuase ReLU function is better for time-efficiency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*XxxiA0jJvPrHEJHD4z893g.png" /></figure><h4>Padding</h4><p>We have to keep as much information we can in early processes of CNN. But convolutional operations we mentioned above decrease size of image that’s why we apply <strong><em>Padding</em></strong> to preserve our input size. <br>For example our input size is 36x36x3 but after convolutional operations we have output with size of 32x32x3 we will fix it by adding some padding like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/0*qDCu-9NEBZ6oqpwz" /></figure><h4>Pooling</h4><p>This layer is used for reducing parameters and computating process. Also by using this layer features invariant to scale or orientation changes are detected and it prevents overfitting. There are some pooling process like average pooling, max pooling etc. But mostly <strong>max pooling</strong> is used. Let’s say we have a 2x2 filter and an 4x4 input(image) results of max pooling and average pooling will be like that: (stride = 2)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/0*0jDjxzEolApgABsz.jpg" /></figure><h4>Flattening</h4><p>Basically flattening is taking matrix came from convolutional and pooling processes and turn it into one dimensional array. This is important because input of fully-connected layer -or let’s say Artificial Neural Networks- consist of one dimensional array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*Lzx2pNLpHjGTKcofsaSH1g.png" /></figure><h4>Full Connection</h4><p>This layer takes data from one dimension array we saw above and starts learning process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*Gh5PS4R_A5drl5ebd_gNrg@2x.png" /></figure><h3>Convolutional Neural Network with Keras</h3><h4>Dropout</h4><p>Dropout is a regularization technique for reducing overfitting. It is called “dropout” because it drops out visible or hidden units in neural network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*VgOp3MXtsRmXSD50.png" /></figure><p>Let’s look dataset we’ll use.</p><h4>About Dataset</h4><p>Now we’ll try to use this algorithm with a dataset contains images of 10 different classes of clothing. Dataset consists a training set of 60,000 examples and a test set of 10,000 examples. Each example is a 28x28 grayscale image, associated with a label from 10 classes.</p><ul><li>Each image is 28 pixels in height and 28 pixels in width, for a total of 784 pixels in total.</li><li>Each pixel has a single pixel-value associated with it, indicating the lightness or darkness of that pixel, with higher numbers meaning darker. This pixel-value is an integer between 0 and 255.</li><li>The training and test data sets have 785 columns. The first column consists of the class labels, and represents class of clothing. The rest of the columns contain the pixel-values of the associated image.</li></ul><p>Each training and test example is assigned to one of the following labels:</p><ul><li>0 T-shirt/top</li><li>1 Trouser</li><li>2 Pullover</li><li>3 Dress</li><li>4 Coat</li><li>5 Sandal</li><li>6 Shirt</li><li>7 Sneaker</li><li>8 Bag</li><li>9 Ankle boot</li></ul><h4>Import Libraries and Read Data</h4><pre><strong>import</strong> numpy <strong>as</strong> np<br><strong>import</strong> pandas <strong>as</strong> pd<br><strong>import</strong> seaborn <strong>as</strong> sns<br><strong>import</strong> matplotlib.pyplot <strong>as</strong> plt</pre><pre># Reading Train Data<br>dfTrain = pd.read_csv(&quot;dataframes/fashion-mnist/fashion-mnist_train.csv&quot;)<br><strong>print</strong>(&quot;Shape of Train Data: &quot; + str(dfTrain.shape))</pre><p>Shape of Train Data: (60000, 785)</p><pre># First 5 rows of train data<br>dfTrain.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*q8mQz7ihmu6s-7r18QexRA.png" /></figure><pre># Reading Test Data<br>dfTest = pd.read_csv(&quot;dataframes/fashion-mnist/fashion-mnist_test.csv&quot;)<br><strong>print</strong>(&quot;Shape of Test Data: &quot; + str(dfTest.shape))</pre><p>Shape of Test Data: (10000, 785)</p><pre># First 5 rows of test data<br>dfTest.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*WvB7woEKTF4U2EV_8J2Q9A.png" /></figure><pre>Y_train = dfTrain.label<br>X_train = dfTrain.drop([&quot;label&quot;], axis=1)<br>X_test = dfTest.drop([&quot;label&quot;], axis=1)<br>Y_test = dfTest.label</pre><pre>plt.figure(figsize=(16,5))<br>sns.countplot(Y_train, palette=&quot;twilight_shifted_r&quot;)<br>plt.title(&quot;Number of Classes&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*9A_mUqk8LG6laWKw735eeg.png" /></figure><h4>Example Images from Dataset</h4><pre>plt.figure(figsize=(20,5))</pre><pre><strong>for</strong> i <strong>in</strong> range(10):<br>    plt.subplot(2,5,i+1)<br>    img = dfTrain[dfTrain.label==i].iloc[0,1:].values<br>    img = img.reshape((28,28))<br>    plt.imshow(img, cmap=&#39;gray&#39;)<br>    plt.title(&quot;Class: &quot; + str(i))<br>    plt.axis(&#39;off&#39;)<br>    <br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*ZXOWwx6JN6Uu5GP7scUt6w.png" /></figure><h4>Normalization</h4><p>We’ll use normalization to reduce effect of illumination’s differences. Also it contributes to works CNN faster.</p><pre># Normalization</pre><pre>X_train = X_train / 255.0<br>X_test = X_test / 255.0</pre><h4>Reshape</h4><p>Our images are 28x28 but to using Keras they have to be 3D matrices. That’s why we reshape them as 28x28x1, we’ll use 1 channel because our images are gray scaled. (e.g. <strong>grayscale</strong> images has only one channel, <strong>RGB</strong> image has three channels)</p><pre># Reshape</pre><pre>X_train = X_train.values.reshape(-1, 28, 28, 1)<br>X_test = X_test.values.reshape(-1, 28, 28, 1)<br><strong>print</strong>(&quot;X_train Shape: &quot;, X_train.shape)<br><strong>print</strong>(&quot;X_test Shape: &quot;, X_test.shape)</pre><p>X_train Shape: (60000, 28, 28, 1)<br>X_test Shape: (10000, 28, 28, 1)</p><h4>Label Encoding</h4><p>We turn our classes into one-hot encoding label.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/0*oXHUgfcY4BKww0bp.jpg" /></figure><pre># Label Encoding</pre><pre><strong>from</strong> keras.utils.np_utils <strong>import</strong> to_categorical</pre><pre>Y_train = to_categorical(Y_train, num_classes=10)</pre><h4>Train-Test Split</h4><p>We’ll split our train data. 30% of data will be validation data and 70% of data will be train data.</p><pre><strong>from</strong> sklearn.model_selection <strong>import</strong> train_test_split</pre><pre>x_train, x_val, y_train, y_val = train_test_split(X_train, Y_train, test_size = 0.3, random_state = 42)</pre><pre><strong>print</strong>(&quot;x_train shape&quot;,x_train.shape)<br><strong>print</strong>(&quot;x_test shape&quot;,x_val.shape)<br><strong>print</strong>(&quot;y_train shape&quot;,y_train.shape)<br><strong>print</strong>(&quot;y_test shape&quot;,y_val.shape)</pre><p>x_train shape (42000, 28, 28, 1)<br>x_test shape (18000, 28, 28, 1)<br>y_train shape (42000, 10)<br>y_test shape (18000, 10)</p><h3>Implementing Convolutional Neural Network Algorithm with Keras</h3><h4>Create Model</h4><pre><strong>from</strong> sklearn.metrics <strong>import</strong> confusion_matrix<br><strong>from</strong> keras.utils.np_utils <strong>import</strong> to_categorical<br><strong>from</strong> keras.models <strong>import</strong> Sequential<br><strong>from</strong> keras.layers <strong>import</strong> Dense, Dropout, Flatten, Conv2D, MaxPool2D<br><strong>from</strong> keras.optimizers <strong>import</strong> RMSprop, Adam<br><strong>from</strong> keras.preprocessing.image <strong>import</strong> ImageDataGenerator<br><strong>from</strong> keras.callbacks <strong>import</strong> ReduceLROnPlateau<br><strong>import</strong> itertools</pre><pre>model = Sequential()</pre><pre>model.add(Conv2D(filters = 32, kernel_size = (3,3), padding = &#39;Same&#39;, activation=&#39;relu&#39;, input_shape=(28,28,1)))<br>model.add(MaxPool2D(pool_size = (2,2)))<br>model.add(Dropout(0.25))</pre><pre>model.add(Conv2D(filters = 64, kernel_size = (3,3),padding = &#39;Same&#39;, activation =&#39;relu&#39;))<br>model.add(MaxPool2D(pool_size=(2,2)))<br>model.add(Dropout(0.25))</pre><pre>model.add(Conv2D(filters = 128, kernel_size = (3,3),padding = &#39;Same&#39;, activation =&#39;relu&#39;))<br>model.add(MaxPool2D(pool_size=(2,2)))<br>model.add(Dropout(0.25))</pre><pre>model.add(Flatten())</pre><pre>model.add(Dense(256, activation=&#39;relu&#39;))<br>model.add(Dropout(0.25))<br>model.add(Dense(256, activation=&#39;relu&#39;))<br>model.add(Dropout(0.1))<br>model.add(Dense(10, activation=&#39;softmax&#39;))</pre><h4>Optimizer</h4><p>We’ll use ‘Adam Optimizer’. Adam is an optimization algorithm that can used instead of the classical stochastic gradient descent procedure to update network weights iterative based in training data. It is different to classical stochastic gradient descent. SGD pursues a single learning rate for all weights updates and learning rate(alpha) doesn’t change during training process. However in adam optimizer we can say adam optimizer updates leraning rate dynamically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/0*_WJJ989JituXPIBM.png" /></figure><pre>optimizer = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)</pre><h4>Compile Model</h4><p>Since we have 10 classes we’ll use categorical crossentropy.</p><pre>model.compile(optimizer = optimizer, loss = &#39;categorical_crossentropy&#39;, metrics=[&#39;accuracy&#39;])</pre><h4>Epoch and Batch Size</h4><p>Epoch is the number of times the algorithm sees the entire data set. If one epoch is too big to run to the computer at once we divide it smaller parts and number of this parts is called batch.</p><pre>epochs = 50<br>batchSize = 300</pre><h4>Data Augmentation</h4><p>By using “data augmentation” we can create new data with different orientations. It prevents overfitting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*_bPZy6nko8BSMySq.png" /></figure><pre># Data Augmentation</pre><pre>datagen = ImageDataGenerator(<br>        featurewise_center=<strong>False</strong>,  # set input mean to 0 over the dataset<br>        samplewise_center=<strong>False</strong>,  # set each sample mean to 0<br>        featurewise_std_normalization=<strong>False</strong>,  # divide inputs by std of the dataset<br>        samplewise_std_normalization=<strong>False</strong>,  # divide each input by its std<br>        zca_whitening=<strong>False</strong>,  # dimesion reduction<br>        rotation_range=0.1,  # randomly rotate images in the range<br>        zoom_range = 0.1, # Randomly zoom image<br>        width_shift_range=0.1,  # randomly shift images horizontally<br>        height_shift_range=0.1,  # randomly shift images vertically<br>        horizontal_flip=<strong>False</strong>,  # randomly flip images<br>        vertical_flip=<strong>False</strong>)  # randomly flip images</pre><pre>datagen.fit(x_train)</pre><h4>Fit The Model</h4><pre>cnn = model.fit_generator(datagen.flow(x_train, y_train, batch_size=batchSize), epochs=epochs, validation_data=(x_val, y_val), steps_per_epoch=x_train.shape[0] // batchSize)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QUyGPYxALrO3ZnIkZG3lnQ.png" /></figure><h4>Evaluate The Model</h4><pre><strong>print</strong>(&quot;Accuracy after fitting: {:.2f}%&quot;.format(cnn.history[&#39;acc&#39;][-1]*100))</pre><p>Accuracy after fitting: <strong>89.92%</strong></p><blockquote><strong>For better accuracy you can increase number of epochs or you can change parameters on layers or you can add additional layer to the model.For the moment I won’t do that because fitting process takes a lot of time.</strong></blockquote><pre>plt.figure(figsize=(18,6))</pre><pre>plt.subplot(1,2,1)<br>plt.plot(cnn.history[&#39;loss&#39;], color=&quot;blue&quot;, label = &quot;Loss&quot;)<br>plt.plot(cnn.history[&#39;val_loss&#39;], color=&quot;orange&quot;, label = &quot;Validation Loss&quot;)<br>plt.ylabel(&quot;Loss&quot;)<br>plt.xlabel(&quot;Number of Epochs&quot;)<br>plt.legend()</pre><pre>plt.subplot(1,2,2)<br>plt.plot(cnn.history[&#39;acc&#39;], color=&quot;green&quot;, label = &quot;Accuracy&quot;)<br>plt.plot(cnn.history[&#39;val_acc&#39;], color=&quot;red&quot;, label = &quot;Validation Accuracy&quot;)<br>plt.ylabel(&quot;Accuracy&quot;)<br>plt.xlabel(&quot;Number of Epochs&quot;)<br>plt.legend()</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zrvqsrJoO6kRkoNKYQYkkQ.png" /></figure><p>Let’s find out score by giving test data we imported before.</p><pre>Y_test = to_categorical(Y_test, num_classes=10) # One-Hot Encoding</pre><pre>score = model.evaluate(X_test, Y_test)<br><strong>print</strong>(&quot;Test Loss: {:.4f}&quot;.format(score[0]))<br><strong>print</strong>(&quot;Test Accuracy: {:.2f}%&quot;.format(score[1]*100))</pre><p>10000/10000 [==============================] — 30s 3ms/step<br><strong>Test Loss: 0.2069<br>Test Accuracy: 92.18%</strong></p><pre>Y_pred = model.predict(X_test)<br>Y_pred_classes = np.argmax(Y_pred, axis = 1)<br>Y_true = np.argmax(Y_test, axis = 1)<br>confusionMatrix = confusion_matrix(Y_true, Y_pred_classes)</pre><pre>f,ax=plt.subplots(figsize=(10,10))<br>sns.heatmap(confusionMatrix, annot=<strong>True</strong>, linewidths=0.1, cmap = &quot;gist_yarg_r&quot;, linecolor=&quot;black&quot;, fmt=&#39;.0f&#39;, ax=ax)<br>plt.xlabel(&quot;Predicted Label&quot;)<br>plt.ylabel(&quot;True Label&quot;)<br>plt.title(&quot;Confusion Matrix&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*ZZQOBNWou5PkIlRBd97lAw.png" /></figure><pre><strong>for</strong> i <strong>in</strong> range(len(confusionMatrix)):<br>    <strong>print</strong>(&quot;Class:&quot;,str(i))<br>    <strong>print</strong>(&quot;Number of Wrong Prediction:&quot;, str(sum(confusionMatrix[i])-confusionMatrix[i][i]), &quot;out of 1000&quot;)<br>    <strong>print</strong>(&quot;Percentage of True Prediction: {:.2f}%&quot;.format(confusionMatrix[i][i] / 10))<br>    <strong>print</strong>(&quot;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&quot;)</pre><p>Class: 0<br>Number of Wrong Prediction: 122 out of 1000<br>Percentage of True Prediction: 87.80%<br>&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;<br>Class: 1<br>Number of Wrong Prediction: 11 out of 1000<br>Percentage of True Prediction: 98.90%<br>&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;<br>Class: 2<br>Number of Wrong Prediction: 185 out of 1000<br>Percentage of True Prediction: 81.50%<br>&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;<br>Class: 3<br>Number of Wrong Prediction: 47 out of 1000<br>Percentage of True Prediction: 95.30%<br>&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;<br>Class: 4<br>Number of Wrong Prediction: 115 out of 1000<br>Percentage of True Prediction: 88.50%<br>&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;<br>Class: 5<br>Number of Wrong Prediction: 16 out of 1000<br>Percentage of True Prediction: 98.40%<br>&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;<br>Class: 6<br>Number of Wrong Prediction: 198 out of 1000<br>Percentage of True Prediction: 80.20%<br>&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;<br>Class: 7<br>Number of Wrong Prediction: 29 out of 1000<br>Percentage of True Prediction: 97.10%<br>&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;<br>Class: 8<br>Number of Wrong Prediction: 13 out of 1000<br>Percentage of True Prediction: 98.70%<br>&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;<br>Class: 9<br>Number of Wrong Prediction: 46 out of 1000<br>Percentage of True Prediction: 95.40%<br>&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;</p><p>As you can see above we should focus on especially Class 2 and Class 6 to improve our score.</p><p>For the dataset we used: <a href="https://www.kaggle.com/zalando-research/fashionmnist">https://www.kaggle.com/zalando-research/fashionmnist</a></p><p>Thanks for your time!</p><p>LinkedIn: <a href="https://www.linkedin.com/in/canerdabakoglu/">https://www.linkedin.com/in/canerdabakoglu/</a></p><p>GitHub: <a href="https://github.com/cdabakoglu">https://github.com/cdabakoglu</a></p><p>Kaggle: <a href="https://www.kaggle.com/cdabakoglu">https://www.kaggle.com/cdabakoglu</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cab447ad204c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Artificial Neural Network with Keras]]></title>
            <link>https://medium.com/@cdabakoglu/artificial-neural-network-with-keras-d858f82f90c5?source=rss-3ea29de4bb5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d858f82f90c5</guid>
            <category><![CDATA[artificial-neural-network]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[fashion]]></category>
            <dc:creator><![CDATA[Caner Dabakoglu]]></dc:creator>
            <pubDate>Sun, 09 Dec 2018 10:45:13 GMT</pubDate>
            <atom:updated>2018-12-09T20:09:22.821Z</atom:updated>
            <content:encoded><![CDATA[<h3>Artificial Neural Network with Keras — An Example</h3><h3>What is Artificial Neural Network?</h3><p>Artifical Neural Networks (ANN) are one of the main tools which are used in machine learning. “Neural” part of their name is called as like that because these systems try to learn things like human brain. Replicated networks contains some kind of neurons and these neurons create a network by connecting each other. These networks have capacity of learning, storing and finding out relationships between datas like a human! <br>For example they can learn to identify images that contain cars by analyzing example images. So after learning phase is completed if you ask to algorithm ‘Is it a car?’ by giving it an image, algorithm can answer your question becuase it identified other cars images and learned how a car looks like. <br>Neural Networks has input and output layers like others but most of the cases they also have hidden layers, and usually we can say how ‘deep’ our algorithm according to number of hidden layers.</p><p>Before we start you may take a glance at article about logistic regression and other machine learning algortihm basics and how they are builded with sklearn please check the link:</p><p><a href="https://medium.com/@cdabakoglu/heart-disease-logistic-regression-machine-learning-d0ebf08e55c0">https://medium.com/@cdabakoglu/heart-disease-logistic-regression-machine-learning-d0ebf08e55c0</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/0*AGISyHaaVZoRrRe8.jpg" /></figure><p>Now we’ll try to use this algorithm with a dataset contains images of 10 different classes of fashion.</p><p>Let’s import libraries we’ll use.</p><pre>import numpy as np <br>import pandas as pd <br>import matplotlib.pyplot as plt</pre><h4>About Dataset</h4><p>Dataset consists a training set of 60,000 examples and a test set of 10,000 examples. Each example is a 28x28 grayscale image, associated with a label from 10 classes.</p><pre>- Each image is 28 pixels in height and 28 pixels in width, for a total of 784 pixels in total.<br>- Each pixel has a single pixel-value associated with it, indicating the lightness or darkness of that pixel, with higher numbers meaning darker. This pixel-value is an integer between 0 and 255.<br>- The training and test data sets have 785 columns. The first column consists of the class labels, and represents class of clothing. The rest of the columns contain the pixel-values of the associated image.</pre><p>Each training and test example is assigned to one of the following labels:</p><pre>- 0 T-shirt/top<br>- 1 Trouser<br>- 2 Pullover<br>- 3 Dress<br>- 4 Coat<br>- 5 Sandal<br>- 6 Shirt<br>- 7 Sneaker<br>- 8 Bag<br>- 9 Ankle boot</pre><p>Since we want binary classification we’ll just choose 0 (T-Shirt/top) and 1 (Trouser) for our data.</p><h4>Read Data</h4><pre>dfAll = pd.read_csv(&quot;../input/fashion-mnist_train.csv&quot;)<br>df = dfAll[((dfAll.label == 0) | (dfAll.label == 1))]</pre><pre>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*va9yuZNVuE_RBiJG26GofQ.png" /></figure><p>Data columns start from ‘label’ to ‘pixel 784&#39;. Like I mentioned above our size of images in the dataset is 28x28 that means each images consist of 784 pixels.</p><p>We will split our data as usual. 30% of our data will be test data and 70% of our data will be used to train our model.</p><pre>from sklearn.model_selection import train_test_split</pre><pre>X = df.drop([&quot;label&quot;], axis=1)<br>Y = df.label<br>x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=0.30, random_state=42)</pre><p>Let’s look some images in the dataset.</p><pre># Example Images</pre><pre>plt.figure(figsize=(8,8))<br>for i in range(4):<br>    plt.subplot(2,2,i+1)<br>    plt.axis(&#39;off&#39;)<br>    plt.imshow(x_train.head().values[i].reshape(28,28), cmap=&#39;gray&#39;, interpolation=&#39;none&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*qjWGHlgiC-UlpFb42Gcnng.png" /></figure><h4>ANN with Keras</h4><pre>x_train = x_train.values.T<br>y_train = y_train.values.reshape(8400,1).T<br>x_test = x_test.values.T<br>y_test = y_test.values.reshape(3600,1).T</pre><pre>from keras.wrappers.scikit_learn import KerasClassifier<br>from sklearn.model_selection import cross_val_score<br>from keras.models import Sequential<br>from keras.layers import Dense</pre><pre>def buildClassifier():<br>    classifier = Sequential()<br>    classifier.add(Dense(units=8, kernel_initializer=&quot;uniform&quot;, activation=&quot;relu&quot;, input_dim=x_train.shape[0])) # Hidden Layer 1 with 8 nodes<br>    classifier.add(Dense(units=6, kernel_initializer=&quot;uniform&quot;, activation=&quot;relu&quot;))  # Hidden Layer 2 with 6 nodes<br>    classifier.add(Dense(units=1, kernel_initializer=&quot;uniform&quot;, activation=&quot;sigmoid&quot;)) # Output Layer<br>    classifier.compile(optimizer = &quot;adam&quot;, loss = &quot;binary_crossentropy&quot;, metrics = [&quot;accuracy&quot;])<br>    return classifier</pre><pre>classifier = KerasClassifier(build_fn=buildClassifier, epochs = 100)<br>accuracies = cross_val_score(estimator = classifier, X = x_train.T, y = y_train.T, cv=3)<br>mean = accuracies.mean()<br>variance = accuracies.std()</pre><pre>print(&quot;Accuracy Mean is {:.2f}%&quot;.format(mean*100))<br>print(&quot;Accuracy Variance is {}&quot;.format(variance))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l9UOKl3Eiz1yFrMkdS8yVw.png" /></figure><p><strong>We can say our model works with approximately<em> 99%</em> of accuracy.</strong></p><p>For other optimizers or parameters please check the link:</p><p><a href="https://keras.io/optimizers/">https://keras.io/optimizers/</a></p><p>Thanks for your time.</p><p>LinkedIn: <a href="https://www.linkedin.com/in/canerdabakoglu/">https://www.linkedin.com/in/canerdabakoglu/</a></p><p>GitHub: <a href="https://github.com/cdabakoglu">https://github.com/cdabakoglu</a></p><p>Kaggle: <a href="https://www.kaggle.com/cdabakoglu">https://www.kaggle.com/cdabakoglu</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d858f82f90c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Wine Reviews Visualization and Natural Language Process (NLP)]]></title>
            <link>https://medium.com/@cdabakoglu/wine-reviews-visualization-and-natural-language-process-nlp-34d650365f1f?source=rss-3ea29de4bb5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/34d650365f1f</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[natural-language-process]]></category>
            <category><![CDATA[wine]]></category>
            <dc:creator><![CDATA[Caner Dabakoglu]]></dc:creator>
            <pubDate>Tue, 04 Dec 2018 15:07:09 GMT</pubDate>
            <atom:updated>2020-06-03T15:53:47.179Z</atom:updated>
            <content:encoded><![CDATA[<h3>HISTORY OF WINE</h3><p>The earliest archaeological evidence of wine grapes has been found at sites in Georgia (c. 6000 BC), Iran (c. 5000 BC), Greece (c. 4500 BC), and Sicily (c. 4000 BC) although there is earlier evidence of a wine made from fermented grapes among other fruits being consumed in China (c. 7000–5500 BC). The oldest evidence of wine production has been found in Armenia (c. 4100 BC).</p><p>The altered consciousness produced by wine has been considered religious since its origin. The ancient Greeks worshiped Dionysus or Bacchus and the Ancient Romans carried on his cult. Consumption of ritual wine was part of Jewish practice since Biblical times and, as part of the eucharist commemorating Jesus’s Last Supper, became even more essential to the Christian Church. Although Islam nominally forbade the production or consumption of wine, during its Golden Age, alchemists such as Geber pioneered wine’s distillation for medicinal and industrial purposes such as the production of perfume.</p><p>Wine production and consumption increased, burgeoning from the 15th century onwards as part of European expansion. Despite the devastating 1887 phylloxera louse infestation, modern science and technology adapted and industrial wine production and wine consumption now occur throughout the world.</p><blockquote><a href="https://en.wikipedia.org/wiki/History_of_wine">https://en.wikipedia.org/wiki/History_of_wine</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/0*C13t3LM87u5lSqiV" /></figure><p>Our dataset contains features below. We will analyze the dataset and use Natural Language Process to make a prediction.</p><p><strong>CONTENT</strong><br> 1.Import Libraries and Read Data<br> 2.Explore and Visualize Data<br> 3.Natural Language Process</p><h4>Import Libraries and Read Data</h4><pre>import numpy as np<br>import pandas as pd <br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>%matplotlib inline<br>import plotly.plotly as py<br>from plotly.offline import init_notebook_mode, iplot<br>init_notebook_mode(connected=True)<br>import plotly.graph_objs as go<br>from plotly import tools</pre><pre>df = pd.read_csv(&quot;../input/winemag-data-130k-v2.csv&quot;)</pre><pre>df.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*NRkXEZImok114LFtXRTinA.png" /></figure><pre>df.head() # First 5 rows of our dataset</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rJ5m1hWbfYHi-wjDoDjVgg.png" /></figure><p>Dataset contains;</p><p><strong>country</strong>: The country that the wine is from <br><strong>description</strong>: A few sentences from a sommelier describing the wine’s taste, smell, look, feel, etc. <br><strong>designation</strong>: The vineyard within the winery where the grapes that made the wine are from <br><strong>points</strong>: The number of points WineEnthusiast rated the wine on a scale of 1–100 (though they say they only post reviews for wines that score &gt;=80) <br><strong>price</strong>: The cost for a bottle of the wine <br><strong>province</strong>: The province or state that the wine is from <br><strong>region_1</strong>: The wine growing area in a province or state (ie Napa) <br><strong>region_2</strong>: Sometimes there are more specific regions specified within a wine growing area (ie Rutherford inside the Napa Valley), but this value can sometimes be blank <br><strong>taster_name</strong>: Name of the person who tasted and reviewed the wine <br><strong>taster_twitter_handle</strong>: Twitter handle for the person who tasted and reviewed the wine <br><strong>title</strong>: The title of the wine review, which often contains the vintage if you’re interested in extracting that feature <br><strong>variety</strong>: The type of grapes used to make the wine (ie Pinot Noir) <br><strong>winery</strong>: The winery that made the wine</p><pre># Let&#39;s delete &quot;Unnamed: 0&quot; column<br>df.drop([&quot;Unnamed: 0&quot;], axis=1, inplace=True)</pre><h3>Exploration and Visualization of Data</h3><p><strong>Number of Wine Tasted According To Countries</strong> (Top 10)</p><pre>plt.figure(figsize=(16,7))<br>sns.set(style=&quot;darkgrid&quot;)<br>sns.barplot(x=df.country.value_counts()[:10].index, y=df.country.value_counts()[:10].values)<br>plt.xlabel(&quot;Countries&quot;)<br>plt.ylabel(&quot;Number of Wine&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*msVc2Xp54z8iXHEFT1f7oA.png" /></figure><p><strong>Average Points</strong> (Top 10)</p><pre>plt.figure(figsize=(16,7))<br>g = sns.barplot(x=df.groupby(&quot;country&quot;).mean().sort_values(by=&quot;points&quot;,ascending=False).points.index[:10], y=df.groupby(&quot;country&quot;).mean().sort_values(by=&quot;points&quot;,ascending=False).points.values[:10], palette=&quot;gist_ncar&quot;)<br>plt.xlabel(&quot;Countries&quot;)<br>plt.ylabel(&quot;Average Points&quot;)<br>plt.title(&quot;Average Points Top 10&quot;)<br>ax=g<br>for p in ax.patches:<br>    ax.annotate(&quot;%.2f&quot; % p.get_height(), (p.get_x() + p.get_width() / 2., p.get_height()),<br>                 ha=&#39;center&#39;, va=&#39;center&#39;, fontsize=11, color=&#39;gray&#39;, xytext=(0, 20),<br>                 textcoords=&#39;offset points&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nIqVC1saaQsPgcepHyobPQ.png" /></figure><pre>plt.figure(figsize=(16,7))<br>g = sns.barplot(x=df.groupby(&quot;country&quot;).mean().sort_values(by=&quot;price&quot;,ascending=False).price.index[:10], y=df.groupby(&quot;country&quot;).mean().sort_values(by=&quot;price&quot;,ascending=False).price.values[:10], palette=&quot;Blues_r&quot;)<br>plt.xlabel(&quot;Countries&quot;)<br>plt.ylabel(&quot;Average Price (US Dollar)&quot;)<br>plt.title(&quot;Average Price Top 10&quot;)<br>ax=g<br>for p in ax.patches:<br>    ax.annotate(&quot;%.2f&quot; % p.get_height(), (p.get_x() + p.get_width() / 2., p.get_height()),<br>                 ha=&#39;center&#39;, va=&#39;center&#39;, fontsize=11, color=&#39;gray&#39;, xytext=(0, 20),<br>                 textcoords=&#39;offset points&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6knFUPyTUQLOMmOTMgg73Q.png" /></figure><p><strong>Points / Price Ratio</strong> (Top 10)</p><pre>df2 = df[np.isfinite(df[&quot;price&quot;])]<br>df2[&quot;points/price&quot;] = df2.points / df2.price<br>df2.groupby(&quot;country&quot;).mean().sort_values(by=&quot;points/price&quot;, ascending=False)</pre><pre>plt.figure(figsize=(16,7))<br>g = sns.barplot(x=df2.groupby(&quot;country&quot;).mean().sort_values(by=&quot;points/price&quot;, ascending=False)[&quot;points/price&quot;].index[:10], y=df2.groupby(&quot;country&quot;).mean().sort_values(by=&quot;points/price&quot;, ascending=False)[&quot;points/price&quot;].values[:10], palette=&quot;jet_r&quot;)<br>plt.xlabel(&quot;Countries&quot;)<br>plt.xticks(rotation= 45, ha=&quot;right&quot;)<br>plt.ylabel(&quot;Points / Price Ratio&quot;)<br>ax=g<br>for p in ax.patches:<br>    ax.annotate(&quot;%.2f&quot; % p.get_height(), (p.get_x() + p.get_width() / 2., p.get_height()),<br>                 ha=&#39;center&#39;, va=&#39;center&#39;, fontsize=11, color=&#39;gray&#39;, xytext=(0, 20),<br>                 textcoords=&#39;offset points&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-lNcDZuvIcCqgqtPY8_vDA.png" /></figure><pre>plt.figure(figsize=(12,6))<br>sns.boxplot(x=df.points)<br>plt.title(&quot;Points Boxplot&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*hA8z7sWMbmiL8T-fzYHt4Q.png" /></figure><p><strong>Best Wines According to Points</strong> (Top 20)</p><pre>top20Points = df.sort_values(by=&quot;points&quot;, ascending=False).head(20)</pre><pre>for i in range(20):<br>    print(&quot;{} / {} / {} / $ {}&quot;.format(top20Points.title.values[i], top20Points.country.values[i], top20Points.province.values[i], top20Points.price.values[i]))<br>    print(&quot;-----------------------------------------------------------------------------------------------------------------------&quot;)</pre><p>Quinta do Noval 2011 Nacional Vintage (Port) / Portugal / Port / $ 650.0<br> — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br>Salon 2006 Le Mesnil Blanc de Blancs Brut Chardonnay (Champagne) / France / Champagne / $ 617.0<br> — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br>Charles Smith 2006 Royal City Syrah (Columbia Valley (WA)) / US / Washington / $ 80.0<br> — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br>Biondi Santi 2010 Riserva (Brunello di Montalcino) / Italy / Tuscany / $ 550.0<br> — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br>Cayuse 2008 Bionic Frog Syrah (Walla Walla Valley (WA)) / US / Washington / $ 80.0<br> — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br>Verité 2007 La Muse Red (Sonoma County) / US / California / $ 450.0<br> — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br>Casa Ferreirinha 2008 Barca-Velha Red (Douro) / Portugal / Douro / $ 450.0<br> — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br>Château Léoville Las Cases 2010 Saint-Julien / France / Bordeaux / $ 359.0<br> — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br>Château Cheval Blanc 2010 Saint-Émilion / France / Bordeaux / $ 1500.0<br> — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br>Casanova di Neri 2007 Cerretalto (Brunello di Montalcino) / Italy / Tuscany / $ 270.0<br> — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br>Château Lafite Rothschild 2010 Pauillac / France / Bordeaux / $ 1500.0<br> — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br>Château Léoville Barton 2010 Saint-Julien / France / Bordeaux / $ 150.0<br> — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br>Chambers Rosewood Vineyards NV Rare Muscat (Rutherglen) / Australia / Victoria / $ 350.0<br> — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br>Cardinale 2006 Cabernet Sauvignon (Napa Valley) / US / California / $ 200.0<br> — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br>Krug 2002 Brut (Champagne) / France / Champagne / $ 259.0<br> — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br>Louis Roederer 2008 Cristal Vintage Brut (Champagne) / France / Champagne / $ 250.0<br> — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br>Avignonesi 1995 Occhio di Pernice (Vin Santo di Montepulciano) / Italy / Tuscany / $ 210.0<br> — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br>Château Haut-Brion 2014 Pessac-Léognan / France / Bordeaux / $ 848.0<br> — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br>Tenuta dell’Ornellaia 2007 Masseto Merlot (Toscana) / Italy / Tuscany / $ 460.0<br> — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br>Château Latour 2010 Pauillac / France / Bordeaux / $ nan<br> — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*aW_7No9g0onj9b_v.jpg" /></figure><pre>labels = top20Points.country.value_counts().index<br>values = top20Points.country.value_counts().values</pre><pre>trace = go.Pie(labels=labels, values=values)</pre><pre>iplot([trace])</pre><p>Producer of Top 20 Wines</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*CjOO5Gcvkp5Pv-e_hbnk2A.png" /></figure><p><strong>The Type of Grapes Used to Make The Wine</strong> (Top 10)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*5JnkGdZxndzkbCl0.jpg" /></figure><pre>df.variety.value_counts()</pre><pre>fig = {<br>  &quot;data&quot;: [<br>    {<br>      &quot;values&quot;: df.variety.value_counts().values[:10],<br>      &quot;labels&quot;: df.variety.value_counts().index[:10],<br>      &quot;name&quot;: &quot;Variaty&quot;,<br>      &quot;hoverinfo&quot;:&quot;label+percent+name&quot;,<br>      &quot;hole&quot;: .4,<br>      &quot;type&quot;: &quot;pie&quot;<br>    },<br>    ],<br>  &quot;layout&quot;: {<br>        &quot;title&quot;:&quot;Variaty&quot;,<br>        &quot;annotations&quot;: [<br>            {<br>                &quot;font&quot;: {<br>                    &quot;size&quot;: 20<br>                },<br>                &quot;showarrow&quot;: False,<br>                &quot;text&quot;: &quot;Grapes&quot;,<br>                &quot;x&quot;: 0.5,<br>                &quot;y&quot;: 0.5<br>            },<br>        ]<br>    }<br>}</pre><pre>iplot(fig)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*feqmvAoTz46GzzYFNp7uVA.png" /></figure><h3>Natural Language Process (NLP)</h3><p>Now we will try to predict if a wine’s point is above average or not. We’ll do that by using descriptions about wines and we’ll use NLP algorithm.</p><pre>meanPoints = df.points.mean()<br>df[&quot;Above_Average&quot;] = [1 if i &gt; meanPoints else 0 for i in df.points]</pre><pre># This process can takes long time. Because we have a lot of descriptions.</pre><pre>import re<br>import nltk<br>from nltk.corpus import stopwords<br>import nltk as nlp</pre><pre>descriptionList = list()<br>lemma = nlp.WordNetLemmatizer()</pre><pre>for description in df.description:<br>    description = re.sub(&quot;[^a-zA-Z]&quot;,&quot; &quot;,description) # We use regular expression to delete non-alphabetic characters on data.<br>    description = description.lower() # Since upper and lower characters are (e.g a - A) evaluated like they are different each other by computer we make turn whole characters into lowercase.<br>    description = nltk.word_tokenize(description) # We tokenized the statement<br>    description = [i for i in description if not i in set(stopwords.words(&quot;english&quot;))] # We will remove words like &#39;the&#39;, &#39;or&#39;, &#39;and&#39;, &#39;is&#39; etc.<br>    description = [lemma.lemmatize(i)for i in description] # e.g: loved =&gt; love<br>    description = &quot; &quot;.join(description) # Now we turn our words list into sentence again<br>    descriptionList.append(description)</pre><pre>from sklearn.feature_extraction.text import CountVectorizer</pre><pre># We try to use most common 1500 words to make a prediction.</pre><pre>max_features = 1500<br>count_vectorizer = CountVectorizer(max_features=max_features) </pre><pre>sparce_matrix = count_vectorizer.fit_transform(descriptionList)</pre><pre>sparce_matrix = sparce_matrix.toarray()</pre><pre>x = sparce_matrix<br>y = df.iloc[:,13].values</pre><pre>from sklearn.model_selection import train_test_split</pre><pre>x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.3, random_state = 42)</pre><pre>from sklearn.naive_bayes import GaussianNB<br>nb = GaussianNB()<br>nb.fit(x_train, y_train)</pre><pre># Prediction<br>y_pred = nb.predict(x_test)</pre><pre>print(&quot;Accuracy: {:.2f}%&quot;.format(nb.score(y_pred.reshape(-1,1), y_test)*100))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YcGxQ6d04WkbvgEiVBvq1Q.png" /></figure><p>Thank you !</p><p>LinkedIn: <a href="https://www.linkedin.com/in/canerdabakoglu/">https://www.linkedin.com/in/canerdabakoglu/</a></p><p>GitHub: <a href="https://github.com/cdabakoglu">https://github.com/cdabakoglu</a></p><p>Kaggle: <a href="https://www.kaggle.com/cdabakoglu">https://www.kaggle.com/cdabakoglu</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34d650365f1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Last Words of Death Row Inmates — NLP (Natural Language Process)]]></title>
            <link>https://medium.com/@cdabakoglu/last-words-of-death-row-inmates-nlp-natural-language-process-b34f5d3a74c?source=rss-3ea29de4bb5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b34f5d3a74c</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[natural-language-process]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Caner Dabakoglu]]></dc:creator>
            <pubDate>Wed, 28 Nov 2018 13:53:23 GMT</pubDate>
            <atom:updated>2018-11-28T13:53:23.571Z</atom:updated>
            <content:encoded><![CDATA[<h3>Last Words of Death Row Inmates — NLP (Natural Language Process)</h3><h3>INTRODUCTION</h3><p>Death penalty is a government-sanctioned practice whereby a person is killed by the state as a punishment for a crime. Capital punishment is a matter of active controversy in several countries and states, and positions can vary within a single political ideology or cultural region. The Council of Europe, which has 47 member states, has sought to abolish the use of the death penalty by its members absolutely, through Protocol 13 of the European Convention on Human Rights. However, this only affects those member states which have signed and ratified it, and they do not include Armenia, Russia, and Azerbaijan. Although most nations have abolished capital punishment, over 60% of the world’s population live in countries where the death penalty is retained, such as China, India, the United States, Indonesia, Pakistan, Bangladesh, Nigeria, Egypt, Iran, among all mostly Islamic countries, as is maintained in Japan and Sri Lanka. <a href="https://en.wikipedia.org/wiki/Capital_punishment">https://en.wikipedia.org/wiki/Capital_punishment</a></p><p>This dataset includes information on criminals executed by Texas Department of Criminal Justice from 1982 to November 8th, 2017</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*oe7WjWyFWLbID7L2f0HU9A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*29ux4sZpw90xmU_4" /></figure><p><strong>We will try to predict if an offender is male or female by using his/her last statement and age.</strong></p><h4>Reading and Cleaning Data</h4><pre># import libraries</pre><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns</pre><pre>df = pd.read_csv(&quot;../input/Texas Last Statement - CSV.csv&quot;, encoding=&quot;latin1&quot;)</pre><pre>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dsZQy_58txzRj7Gq02UJDA.png" /></figure><pre>df[&quot;Gender&quot;] = 0<br>genderList = [1 if i == 1.0 else 0 for i in df.MaleVictim]<br>df.Gender = genderList</pre><pre>df.drop([&quot;Execution&quot;,&quot;TDCJNumber&quot;,&quot;PreviousCrime&quot;,&quot;Codefendants&quot;,&quot;NumberVictim&quot;,&quot;WhiteVictim&quot;,&quot;HispanicVictim&quot;,&quot;BlackVictim&quot;,&quot;VictimOther Races&quot;,],axis=1, inplace=True)</pre><pre>df.drop([&quot;FemaleVictim&quot;,&quot;MaleVictim&quot;],axis=1,inplace=True)</pre><pre>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sL_smnHcg1TGiCSG51fF_w.png" /></figure><pre>df.dropna(inplace=True)</pre><pre>df.AgeWhenReceived = df.AgeWhenReceived.astype(int)<br>df.EducationLevel = df.EducationLevel.astype(int)<br>df.head()</pre><h4>Explore Data</h4><p>Ages</p><pre>plt.figure(figsize=(12,7))<br>sns.boxplot(y=df.Age)<br>plt.show()</pre><pre>print(&quot;Minimum Age is {}&quot;.format(df.Age.min()))<br>print(&quot;Maximum Age is {}&quot;.format(df.Age.max()))<br>print(&quot;Average Age is {:.1f}&quot;.format(df.Age.mean()))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*Jnnko_eP-sDkHSYtao4Y2w.png" /></figure><p>Minimum Age is 24<br>Maximum Age is 67<br>Average Age is 39.5</p><pre>df.corr()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*5d-NkqLRpsuG9sJfyQrWow.png" /></figure><pre>plt.figure(figsize=(12,8))<br>sns.heatmap(df.corr(), linewidths=2, annot=True)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*MzJkj9v35BLPa4EYS9i4XA.png" /></figure><p>Not suprisingly Age and AgeWhenReceived correlated with each other. But other features not saying much. Let’s continue.</p><pre>educationList= sorted(list(zip(df.EducationLevel.value_counts().index, df.EducationLevel.value_counts().values)))<br>eduYear, eduCount = zip(*educationList)<br>eduYear, eduCount = list(eduYear), list(eduCount)</pre><pre>plt.figure(figsize=(16,10))<br>plt.xlabel(&quot;Education Level&quot;)<br>plt.ylabel(&quot;Number of Offender&quot;)<br>plt.title(&quot;Number of Offender According To Their Education Level&quot;)<br>sns.barplot(x=eduYear,y=eduCount)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*70nEPeHMGwGlq6NlOLB-tQ.png" /></figure><p>We can see that most of the offenders were graduated from high school or they were high school drop out.</p><pre>plt.figure(figsize=(16,10))<br>plt.xlabel(&quot;Last Name&quot;)<br>plt.ylabel(&quot;Frequency&quot;)<br>plt.title(&quot;Most 10 Frequent Last Names&quot;)<br>sns.barplot(x=df.LastName.value_counts()[:11].index,y=df.LastName.value_counts()[:11].values, palette=&quot;cubehelix&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tDhHy5MvZh9l-G0GmOLpWQ.png" /></figure><pre>plt.figure(figsize=(16,10))<br>plt.xlabel(&quot;First Name&quot;)<br>plt.ylabel(&quot;Frequency&quot;)<br>plt.title(&quot;Most 10 Frequent First Names&quot;)<br>sns.barplot(x=df.FirstName.value_counts()[:11].index,y=df.FirstName.value_counts()[:11].values, palette=&quot;gist_ncar_r&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IcuI6OdxkzicIyKWLO2gjw.png" /></figure><pre>import squarify</pre><pre>plt.figure(figsize=(15,8))<br>squarify.plot(sizes=df.Race.value_counts().values, label=df.Race.value_counts().index, color=[&quot;#17A096&quot;,&quot;#CBC015&quot;,&quot;#E4595D&quot;, &quot;#979797&quot;], alpha=.8 )<br>plt.axis(&#39;off&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IFjhf-5NL_Z-qd35S-gBaw.png" /></figure><p>White 220<br>Black 188<br>Hispanic 90<br>Other 2</p><p>Majority of offenders were White with 220 persons. 188 of offenders were Black and 90 of them were Hispanic.</p><h3>Natural Language Process</h3><p>Now we have to do some operations to prepare data but before applying that operations whole statements I will show you what actually we will do with one example step by step.</p><pre># We use regular expression to delete non-alphabetic characters on data.</pre><pre>import re</pre><pre>first_lastStatement = df.LastStatement[0]<br>lastStatement = re.sub(&quot;[^a-zA-Z]&quot;,&quot; &quot;,first_lastStatement)</pre><pre>print(lastStatement)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KMP3PcAPlBI95Nc0YSqNMw.png" /></figure><pre># Since upper and lower characters are (e.g a - A) evaluated like they are different each other by computer we make turn whole characters into lowercase.</pre><pre>lastStatement = lastStatement.lower()<br>print(lastStatement)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qvd_biR35PeWqH9d9Dqziw.png" /></figure><pre>import nltk  # Natural Language Tool Kit</pre><pre>nltk.download(&quot;stopwords&quot;)  # If you dont&#39;t have that module this line will download it.<br>nltk.download(&#39;punkt&#39;) # It&#39;s necessary to import the module</pre><pre>from nltk.corpus import stopwords # We are importing &#39;stopwords&#39;</pre><pre>lastStatement = nltk.word_tokenize(lastStatement) # We tokenized the statement</pre><pre>print(lastStatement)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ca5wDCalenpNQjjfb1oKSQ.png" /></figure><pre># We will remove words like &#39;the&#39;, &#39;or&#39;, &#39;and&#39;, &#39;is&#39; etc.</pre><pre>lastStatement = [i for i in lastStatement if not i in set(stopwords.words(&quot;english&quot;))]<br>print(lastStatement)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AVUghExhOHAjC_m5MwmHDg.png" /></figure><h4>Lematization</h4><pre># e.g: loved =&gt; love</pre><pre>nltk.download(&#39;wordnet&#39;) # It can be necessary<br>import nltk as nlp</pre><pre>lemmatization = nlp.WordNetLemmatizer()<br>lastStatement = [lemmatization.lemmatize(i) for i in lastStatement]</pre><pre>print(lastStatement)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SNp7gUYUbP2kLJkNfr3l7A.png" /></figure><pre># Now we turn our lastStatement list into sentence again</pre><pre>lastStatement = &quot; &quot;.join(lastStatement)</pre><pre>print(lastStatement)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QYZwmZPuhvlFlg9hA-2e1g.png" /></figure><h4>Preparing Entire Data</h4><pre>statementList = list()</pre><pre>for statement in df.LastStatement:<br>    statement = re.sub(&quot;[^a-zA-Z]&quot;,&quot; &quot;,statement)<br>    statement = statement.lower()<br>    statement = nltk.word_tokenize(statement)<br>    statement = [i for i in statement if not i in set(stopwords.words(&quot;english&quot;))]<br>    statement = [lemmatization.lemmatize(i)for i in statement]<br>    statement = &quot; &quot;.join(statement)<br>    statementList.append(statement)</pre><h4>Bag of Words</h4><pre>from sklearn.feature_extraction.text import CountVectorizer</pre><pre>max_features = 600<br>count_vectorizer = CountVectorizer(max_features=max_features) <br>sparce_matrix = count_vectorizer.fit_transform(statementList)<br>sparce_matrix = sparce_matrix.toarray()</pre><pre>print(&quot;Most Frequent {} Words: {}&quot;.format(max_features, count_vectorizer.get_feature_names()))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_zy0-uIip6Vaqa2QLwtkog.png" /></figure><pre>y = df.iloc[:,9].values # gender column<br>x = sparce_matrix</pre><pre>from sklearn.model_selection import train_test_split</pre><pre>x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.05, random_state = 42)</pre><pre>from sklearn.naive_bayes import GaussianNB</pre><pre>nb = GaussianNB()<br>nb.fit(x_train, y_train)</pre><pre># Prediction<br>y_pred = nb.predict(x_test)</pre><pre>print(&quot;Accuracy: {:.2f}%&quot;.format(nb.score(y_pred.reshape(-1,1), y_test)*100))</pre><p>Accuracy: 60.00%</p><p>Let’s try this algorithm by adding age feature beside last statement.</p><pre>df2 = pd.DataFrame(sparce_matrix)<br>df2[&quot;Age&quot;] = df.Age<br>df2[&quot;Age&quot;].fillna((df2[&quot;Age&quot;].mean()),inplace=True)</pre><pre># Normalization<br>x2 = (df2 - np.min(df2)) / (np.max(df2) - np.min(df2)).values</pre><pre>x_train2, x_test2, y_train2, y_test2 = train_test_split(x2, y, test_size = 0.05, random_state = 42)</pre><pre>from sklearn.naive_bayes import GaussianNB</pre><pre>nb = GaussianNB()<br>nb.fit(x_train2, y_train2)</pre><pre># Prediction<br>y_pred2= nb.predict(x_test2)</pre><pre>print(&quot;Accuracy: {:.2f}%&quot;.format(nb.score(y_pred2.reshape(-1,1), y_test2)*100))</pre><p>Accuracy: 64.00%</p><p>Our model works with 64% accuracy which is okay.</p><p>Thank you !</p><p>LinkedIn: <a href="https://www.linkedin.com/in/canerdabakoglu/">https://www.linkedin.com/in/canerdabakoglu/</a></p><p>GitHub: <a href="https://github.com/cdabakoglu">https://github.com/cdabakoglu</a></p><p>Kaggle: <a href="https://www.kaggle.com/cdabakoglu">https://www.kaggle.com/cdabakoglu</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b34f5d3a74c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clustering Mall Customers — K-Means (Machine Learning)]]></title>
            <link>https://medium.com/@cdabakoglu/clustering-mall-customers-k-means-machine-learning-5c12d5cacbe?source=rss-3ea29de4bb5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c12d5cacbe</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[k-means]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Caner Dabakoglu]]></dc:creator>
            <pubDate>Sun, 25 Nov 2018 09:51:51 GMT</pubDate>
            <atom:updated>2019-01-06T17:38:48.065Z</atom:updated>
            <content:encoded><![CDATA[<h3>Clustering Mall Customers — K-Means (Machine Learning)</h3><p>We have some basic data about customers like Customer ID, age, gender, annual income and spending score. Spending Score is assigned to the customer based on some parameters like customer behavior and purchasing data. We will try to cluster this data according to these features.</p><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns</pre><pre># Read data<br>df = pd.read_csv(&quot;../input/Mall_Customers.csv&quot;)</pre><pre># Info<br>df.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bUjC0ZoOlijjvIfQEWe_Nw.png" /></figure><pre>df.columns</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SE1rxF6YLFHIf8JbfiF--A.png" /></figure><pre># First 5 rows of our data<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*eBNthmsiQjLuyhsFQ3UVrg.png" /></figure><p>I will drop CustomerID column because in this case it is unnecessary.</p><pre>df.drop([&quot;CustomerID&quot;], axis = 1, inplace=True)</pre><pre>plt.figure(figsize=(10,6))<br>plt.title(&quot;Ages Frequency&quot;)<br>sns.axes_style(&quot;dark&quot;)<br>sns.violinplot(y=df[&quot;Age&quot;])<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*DLWBYWMrdJ4vTV8o0zksZw.png" /></figure><pre>plt.figure(figsize=(15,6))<br>plt.subplot(1,2,1)<br>sns.boxplot(y=df[&quot;Spending Score (1-100)&quot;], color=&quot;red&quot;)<br>plt.subplot(1,2,2)<br>sns.boxplot(y=df[&quot;Annual Income (k$)&quot;])<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*emk7dBh7pEzD59i18tJxcQ.png" /></figure><pre>genders = df.Gender.value_counts()<br>sns.set_style(&quot;darkgrid&quot;)<br>plt.figure(figsize=(10,4))<br>sns.barplot(x=genders.index, y=genders.values)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*Ati5zLJ4BwCgPJjHFyzZRA.png" /></figure><pre>age18_25 = df.Age[(df.Age &lt;= 25) &amp; (df.Age &gt;= 18)]<br>age26_35 = df.Age[(df.Age &lt;= 35) &amp; (df.Age &gt;= 26)]<br>age36_45 = df.Age[(df.Age &lt;= 45) &amp; (df.Age &gt;= 36)]<br>age46_55 = df.Age[(df.Age &lt;= 55) &amp; (df.Age &gt;= 46)]<br>age55above = df.Age[df.Age &gt;= 56]</pre><pre>x = [&quot;18-25&quot;,&quot;26-35&quot;,&quot;36-45&quot;,&quot;46-55&quot;,&quot;55+&quot;]<br>y = [len(age18_25.values),len(age26_35.values),len(age36_45.values),len(age46_55.values),len(age55above.values)]</pre><pre>plt.figure(figsize=(15,6))<br>sns.barplot(x=x, y=y, palette=&quot;rocket&quot;)<br>plt.title(&quot;Number of Customer and Ages&quot;)<br>plt.xlabel(&quot;Age&quot;)<br>plt.ylabel(&quot;Number of Customer&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*iE-ioL6usizjaK1r68-yIA.png" /></figure><pre>ss1_20 = df[&quot;Spending Score (1-100)&quot;][(df[&quot;Spending Score (1-100)&quot;] &gt;= 1) &amp; (df[&quot;Spending Score (1-100)&quot;] &lt;= 20)]<br>ss21_40 = df[&quot;Spending Score (1-100)&quot;][(df[&quot;Spending Score (1-100)&quot;] &gt;= 21) &amp; (df[&quot;Spending Score (1-100)&quot;] &lt;= 40)]<br>ss41_60 = df[&quot;Spending Score (1-100)&quot;][(df[&quot;Spending Score (1-100)&quot;] &gt;= 41) &amp; (df[&quot;Spending Score (1-100)&quot;] &lt;= 60)]<br>ss61_80 = df[&quot;Spending Score (1-100)&quot;][(df[&quot;Spending Score (1-100)&quot;] &gt;= 61) &amp; (df[&quot;Spending Score (1-100)&quot;] &lt;= 80)]<br>ss81_100 = df[&quot;Spending Score (1-100)&quot;][(df[&quot;Spending Score (1-100)&quot;] &gt;= 81) &amp; (df[&quot;Spending Score (1-100)&quot;] &lt;= 100)]</pre><pre>ssx = [&quot;1-20&quot;, &quot;21-40&quot;, &quot;41-60&quot;, &quot;61-80&quot;, &quot;81-100&quot;]<br>ssy = [len(ss1_20.values), len(ss21_40.values), len(ss41_60.values), len(ss61_80.values), len(ss81_100.values)]</pre><pre>plt.figure(figsize=(15,6))<br>sns.barplot(x=ssx, y=ssy, palette=&quot;nipy_spectral_r&quot;)<br>plt.title(&quot;Spending Scores&quot;)<br>plt.xlabel(&quot;Score&quot;)<br>plt.ylabel(&quot;Number of Customer Having the Score&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aiGSmXu8_lne_o58EhCaEQ.png" /></figure><pre>ai0_30 = df[&quot;Annual Income (k$)&quot;][(df[&quot;Annual Income (k$)&quot;] &gt;= 0) &amp; (df[&quot;Annual Income (k$)&quot;] &lt;= 30)]<br>ai31_60 = df[&quot;Annual Income (k$)&quot;][(df[&quot;Annual Income (k$)&quot;] &gt;= 31) &amp; (df[&quot;Annual Income (k$)&quot;] &lt;= 60)]<br>ai61_90 = df[&quot;Annual Income (k$)&quot;][(df[&quot;Annual Income (k$)&quot;] &gt;= 61) &amp; (df[&quot;Annual Income (k$)&quot;] &lt;= 90)]<br>ai91_120 = df[&quot;Annual Income (k$)&quot;][(df[&quot;Annual Income (k$)&quot;] &gt;= 91) &amp; (df[&quot;Annual Income (k$)&quot;] &lt;= 120)]<br>ai121_150 = df[&quot;Annual Income (k$)&quot;][(df[&quot;Annual Income (k$)&quot;] &gt;= 121) &amp; (df[&quot;Annual Income (k$)&quot;] &lt;= 150)]</pre><pre>aix = [&quot;$ 0 - 30,000&quot;, &quot;$ 30,001 - 60,000&quot;, &quot;$ 60,001 - 90,000&quot;, &quot;$ 90,001 - 120,000&quot;, &quot;$ 120,001 - 150,000&quot;]<br>aiy = [len(ai0_30.values), len(ai31_60.values), len(ai61_90.values), len(ai91_120.values), len(ai121_150.values)]</pre><pre>plt.figure(figsize=(15,6))<br>sns.barplot(x=aix, y=aiy, palette=&quot;Set2&quot;)<br>plt.title(&quot;Annual Incomes&quot;)<br>plt.xlabel(&quot;Income&quot;)<br>plt.ylabel(&quot;Number of Customer&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xTwBmjHGLEawLrg7Jvbkyg.png" /></figure><h3>K — MEANS</h3><p>K-means clustering is a type of unsupervised learning which is used when you have unlabeled data. By using this algorithm you will try to find groups in the data. “k” value represent number of groups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*tWaaZX75oumVwBMcKN-eHA.png" /></figure><p>We will use Age, Annual Income and Spending Score for clustering customers. Let’s look how our plot is seen without clustering.</p><pre>from mpl_toolkits.mplot3d import Axes3D</pre><pre>sns.set_style(&quot;white&quot;)<br>fig = plt.figure(figsize=(20,10))<br>ax = fig.add_subplot(111, projection=&#39;3d&#39;)<br>ax.scatter(df.Age, df[&quot;Annual Income (k$)&quot;], df[&quot;Spending Score (1-100)&quot;], c=&#39;blue&#39;, s=60)<br>ax.view_init(30, 185)<br>plt.xlabel(&quot;Age&quot;)<br>plt.ylabel(&quot;Annual Income (k$)&quot;)<br>ax.set_zlabel(&#39;Spending Score (1-100)&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I_l7P3xTVf4cTnlHxYNxeg.png" /></figure><p>Now we will try to find what “k” value we should use. We will find it out with “elbow method”.</p><p><strong>Elbow Method:</strong> <a href="https://en.wikipedia.org/wiki/Elbow_method_(clustering)">https://en.wikipedia.org/wiki/Elbow_method_(clustering)</a></p><pre>from sklearn.cluster import KMeans</pre><pre>wcss = []<br>for k in range(1,11):<br>    kmeans = KMeans(n_clusters=k, init=&quot;k-means++&quot;)<br>    kmeans.fit(df.iloc[:,1:])<br>    wcss.append(kmeans.inertia_)<br>plt.figure(figsize=(12,6))    <br>plt.grid()<br>plt.plot(range(1,11),wcss, linewidth=2, color=&quot;red&quot;, marker =&quot;8&quot;)<br>plt.xlabel(&quot;K Value&quot;)<br>plt.xticks(np.arange(1,11,1))<br>plt.ylabel(&quot;WCSS&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*WvzwPH8KUvizecT7JPsj6w.png" /></figure><p>We used elbow method in the above and we may say 5 will be our number of cluster. Let’s use K-Means and see how our plot will look like.</p><pre>km = KMeans(n_clusters=5)<br>clusters = km.fit_predict(df.iloc[:,1:])</pre><pre>df[&quot;label&quot;] = clusters</pre><pre>from mpl_toolkits.mplot3d import Axes3D<br>import matplotlib.pyplot as plt<br>import numpy as np<br>import pandas as pd</pre><pre>fig = plt.figure(figsize=(20,10))<br>ax = fig.add_subplot(111, projection=&#39;3d&#39;)<br>ax.scatter(df.Age[df.label == 0], df[&quot;Annual Income (k$)&quot;][df.label == 0], df[&quot;Spending Score (1-100)&quot;][df.label == 0], c=&#39;blue&#39;, s=60)<br>ax.scatter(df.Age[df.label == 1], df[&quot;Annual Income (k$)&quot;][df.label == 1], df[&quot;Spending Score (1-100)&quot;][df.label == 1], c=&#39;red&#39;, s=60)<br>ax.scatter(df.Age[df.label == 2], df[&quot;Annual Income (k$)&quot;][df.label == 2], df[&quot;Spending Score (1-100)&quot;][df.label == 2], c=&#39;green&#39;, s=60)<br>ax.scatter(df.Age[df.label == 3], df[&quot;Annual Income (k$)&quot;][df.label == 3], df[&quot;Spending Score (1-100)&quot;][df.label == 3], c=&#39;orange&#39;, s=60)<br>ax.scatter(df.Age[df.label == 4], df[&quot;Annual Income (k$)&quot;][df.label == 4], df[&quot;Spending Score (1-100)&quot;][df.label == 4], c=&#39;purple&#39;, s=60)<br>ax.view_init(30, 185)<br>plt.xlabel(&quot;Age&quot;)<br>plt.ylabel(&quot;Annual Income (k$)&quot;)<br>ax.set_zlabel(&#39;Spending Score (1-100)&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rWnvx3shcFCVNF0g0nIbKw.png" /></figure><p>We have 5 type of customer and we grouped them as you can see above.</p><p>Thank you!</p><p>LinkedIn: <a href="https://www.linkedin.com/in/canerdabakoglu/">https://www.linkedin.com/in/canerdabakoglu/</a></p><p>GitHub: <a href="https://github.com/cdabakoglu">https://github.com/cdabakoglu</a></p><p>Kaggle: <a href="https://www.kaggle.com/cdabakoglu">https://www.kaggle.com/cdabakoglu</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c12d5cacbe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Heart Disease — Logistic Regression (Machine Learning)]]></title>
            <link>https://medium.com/@cdabakoglu/heart-disease-logistic-regression-machine-learning-d0ebf08e55c0?source=rss-3ea29de4bb5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0ebf08e55c0</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Caner Dabakoglu]]></dc:creator>
            <pubDate>Sun, 18 Nov 2018 19:34:13 GMT</pubDate>
            <atom:updated>2019-03-02T07:39:17.036Z</atom:updated>
            <content:encoded><![CDATA[<h3>Heart Disease — Logistic Regression and Other Classifications (Machine Learning)</h3><h3>INTRODUCTION</h3><p>We have a data which classified if patients have heart disease or not according to features in it. We will try to use this data to create a model which tries predict if a patient has this disease or not. We will use logistic regression (classification) algorithm.</p><pre># Let&#39;s import libraries we will use<br>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.model_selection import train_test_split</pre><h3>Read Data</h3><pre># We are reading our data<br>df = pd.read_csv(&quot;../input/heart.csv&quot;)</pre><pre># First 5 rows of our data<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*V6xkWJVjtpI73JsTQAbj6A.png" /></figure><p>Data contains;</p><p>*age — age in years<br>* sex — (1 = male; 0 = female) <br>* cp — chest pain type <br>* trestbps — resting blood pressure (in mm Hg on admission to the hospital) <br>* chol — serum cholestoral in mg/dl <br>* fbs — (fasting blood sugar &gt; 120 mg/dl) (1 = true; 0 = false) <br>* restecg — resting electrocardiographic results <br>* thalach — maximum heart rate achieved <br>* exang — exercise induced angina (1 = yes; 0 = no) <br>* oldpeak — ST depression induced by exercise relative to rest <br>* slope — the slope of the peak exercise ST segment<br>* ca — number of major vessels (0–3) colored by flourosopy <br>* thal — 3 = normal; 6 = fixed defect; 7 = reversable defect <br>* target — have disease or not (1=yes, 0=no)</p><h3>DATA EXPLORATION</h3><pre>df.target.value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*7aCyPxnarYqTCz7yIW2Sxg.png" /></figure><pre>sns.countplot(x=&quot;target&quot;, data=df, palette=&quot;bwr&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*3qyGEgOXW-JDbJNV3R8AXA.png" /></figure><pre>countNoDisease = len(df[df.target == 0])<br>countHaveDisease = len(df[df.target == 1])<br>print(&quot;Percentage of Patients Haven&#39;t Heart Disease: {:.2f}%&quot;.format((countNoDisease / (len(df.target))*100)))<br>print(&quot;Percentage of Patients Have Heart Disease: {:.2f}%&quot;.format((countHaveDisease / (len(df.target))*100)))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*B614SmU9iAaNYhx_FFzGLQ.png" /></figure><pre>sns.countplot(x=&#39;sex&#39;, data=df, palette=&quot;mako_r&quot;)<br>plt.xlabel(&quot;Sex (0 = female, 1= male)&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*DlCPBcVQcRS1-daJY1PSwA.png" /></figure><pre>countFemale = len(df[df.sex == 0])<br>countMale = len(df[df.sex == 1])<br>print(&quot;Percentage of Female Patients: {:.2f}%&quot;.format((countFemale / (len(df.sex))*100)))<br>print(&quot;Percentage of Male Patients: {:.2f}%&quot;.format((countMale / (len(df.sex))*100)))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*ljzLXDtiSK6AaowMtyFs3g.png" /></figure><pre>df.groupby(&#39;target&#39;).mean()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ewOJdpuH-PKp9PoDujOAEg.png" /></figure><pre>pd.crosstab(df.age,df.target).plot(kind=&quot;bar&quot;,figsize=(20,6))<br>plt.title(&#39;Heart Disease Frequency for Ages&#39;)<br>plt.xlabel(&#39;Age&#39;)<br>plt.ylabel(&#39;Frequency&#39;)<br>plt.savefig(&#39;heartDiseaseAndAges.png&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3kgnU-h9aOL6_oIcVKMAqw.png" /></figure><pre>pd.crosstab(df.sex,df.target).plot(kind=&quot;bar&quot;,figsize=(15,6),color=[&#39;#1CA53B&#39;,&#39;#AA1111&#39; ])<br>plt.title(&#39;Heart Disease Frequency for Sex&#39;)<br>plt.xlabel(&#39;Sex (0 = Female, 1 = Male)&#39;)<br>plt.xticks(rotation=0)<br>plt.legend([&quot;Haven&#39;t Disease&quot;, &quot;Have Disease&quot;])<br>plt.ylabel(&#39;Frequency&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*e9tO4fNkLC6Jxo_NwoadvQ.png" /></figure><pre>plt.scatter(x=df.age[df.target==1], y=df.thalach[(df.target==1)], c=&quot;red&quot;)<br>plt.scatter(x=df.age[df.target==0], y=df.thalach[(df.target==0)])<br>plt.legend([&quot;Disease&quot;, &quot;Not Disease&quot;])<br>plt.xlabel(&quot;Age&quot;)<br>plt.ylabel(&quot;Maximum Heart Rate&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*gkWxR_hv8plbo7dx6ivmgA.png" /></figure><pre>pd.crosstab(df.slope,df.target).plot(kind=&quot;bar&quot;,figsize=(15,6),color=[&#39;#DAF7A6&#39;,&#39;#FF5733&#39; ])<br>plt.title(&#39;Heart Disease Frequency for Slope&#39;)<br>plt.xlabel(&#39;The Slope of The Peak Exercise ST Segment &#39;)<br>plt.xticks(rotation = 0)<br>plt.ylabel(&#39;Frequency&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*3iZSkXq-s9pcF4_hRLswrA.png" /></figure><pre>pd.crosstab(df.fbs,df.target).plot(kind=&quot;bar&quot;,figsize=(15,6),color=[&#39;#FFC300&#39;,&#39;#581845&#39; ])<br>plt.title(&#39;Heart Disease Frequency According To FBS&#39;)<br>plt.xlabel(&#39;FBS - (Fasting Blood Sugar &gt; 120 mg/dl) (1 = true; 0 = false)&#39;)<br>plt.xticks(rotation = 0)<br>plt.legend([&quot;Haven&#39;t Disease&quot;, &quot;Have Disease&quot;])<br>plt.ylabel(&#39;Frequency of Disease or Not&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*G4Iw_RQqpMVr9tQpV-cOQQ.png" /></figure><pre>pd.crosstab(df.cp,df.target).plot(kind=&quot;bar&quot;,figsize=(15,6),color=[&#39;#11A5AA&#39;,&#39;#AA1190&#39; ])<br>plt.title(&#39;Heart Disease Frequency According To Chest Pain Type&#39;)<br>plt.xlabel(&#39;Chest Pain Type&#39;)<br>plt.xticks(rotation = 0)<br>plt.ylabel(&#39;Frequency of Disease or Not&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*7UVqzoHUdBIbIoul2jLPNA.png" /></figure><h3>Creating Dummy Variables</h3><p>Since ‘cp’, ‘thal’ and ‘slope’ are categorical variables we’ll turn them into dummy variables.</p><pre>a = pd.get_dummies(df[&#39;cp&#39;], prefix = &quot;cp&quot;)<br>b = pd.get_dummies(df[&#39;thal&#39;], prefix = &quot;thal&quot;)<br>c = pd.get_dummies(df[&#39;slope&#39;], prefix = &quot;slope&quot;)</pre><pre>frames = [df, a, b, c]<br>df = pd.concat(frames, axis = 1)<br>df = df.drop(columns = [&#39;cp&#39;, &#39;thal&#39;, &#39;slope&#39;])</pre><h3>CREATING MODEL FOR LOGISTIC REGRESSION</h3><p>We can use sklearn library or we can write functions ourselves. Let’s them both. Firstly we will write our functions after that we’ll use sklearn library to calculate score.</p><pre>y = df.target.values<br>x_data = df.drop([&#39;target&#39;], axis = 1)</pre><p>Normalize Data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/0*muGt9UcbIkmCqQH2" /></figure><pre># Normalize<br>x = (x_data - np.min(x_data)) / (np.max(x_data) - np.min(x_data)).values</pre><p>We will split our data. 80% of our data will be train data and 20% of it will be test data.</p><pre>x_train, x_test, y_train, y_test = train_test_split(x,y,test_size = 0.2,random_state=0)</pre><pre>#transpose matrices<br>x_train = x_train.T<br>y_train = y_train.T<br>x_test = x_test.T<br>y_test = y_test.T</pre><p>Let’s say weight = 0.01 and bias = 0.0</p><pre>#initialize<br>def initialize(dimension):<br>    <br>    weight = np.full((dimension,1),0.01)<br>    bias = 0.0<br>    return weight,bias</pre><p>Sigmoid Function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*YOdUfTvvdCTLLeZh" /></figure><pre>def sigmoid(z):<br>    <br>    y_head = 1/(1+ np.exp(-z))<br>    return y_head</pre><p>Forward and Backward Propagation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/0*IrZ_GwzsmhrWNTnE" /></figure><p>Cost Function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/0*U1hJDcaeIt6Ux0Fi.png" /></figure><p>Gradient</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/0*mrHPjtUxwfO0lprj.png" /></figure><p>By the way in formulas;</p><ul><li>h0(x^i)= y_head<br>* y^i = y_train<br>* x^i = x_train</li></ul><pre>def forwardBackward(weight,bias,x_train,y_train):<br>    # Forward<br>    <br>    y_head = sigmoid(np.dot(weight.T,x_train) + bias)<br>    loss = -(y_train*np.log(y_head) + (1-y_train)*np.log(1-y_head))<br>    cost = np.sum(loss) / x_train.shape[1]<br>    <br>    # Backward<br>    derivative_weight = np.dot(x_train,((y_head-y_train).T))/x_train.shape[1]<br>    derivative_bias = np.sum(y_head-y_train)/x_train.shape[1]<br>    gradients = {&quot;Derivative Weight&quot; : derivative_weight, &quot;Derivative Bias&quot; : derivative_bias}<br>    <br>    return cost,gradients</pre><pre>def update(weight,bias,x_train,y_train,learningRate,iteration):<br>    costList = []<br>    index = []<br>    <br>    #for each iteration, update weight and bias values<br>    for i in range(iteration):<br>        cost,gradients = forwardBackward(weight,bias,x_train,y_train)<br>        weight = weight - learningRate * gradients[&quot;Derivative Weight&quot;]<br>        bias = bias - learningRate * gradients[&quot;Derivative Bias&quot;]<br>        <br>        costList.append(cost)<br>        index.append(i)</pre><pre>parameters = {&quot;weight&quot;: weight,&quot;bias&quot;: bias}<br>    <br>    print(&quot;iteration:&quot;,iteration)<br>    print(&quot;cost:&quot;,cost)</pre><pre>plt.plot(index,costList)<br>    plt.xlabel(&quot;Number of Iteration&quot;)<br>    plt.ylabel(&quot;Cost&quot;)<br>    plt.show()</pre><pre>return parameters, gradients</pre><pre>def predict(weight,bias,x_test):<br>    z = np.dot(weight.T,x_test) + bias<br>    y_head = sigmoid(z)</pre><pre>y_prediction = np.zeros((1,x_test.shape[1]))<br>    <br>    for i in range(y_head.shape[1]):<br>        if y_head[0,i] &lt;= 0.5:<br>            y_prediction[0,i] = 0<br>        else:<br>            y_prediction[0,i] = 1<br>    return y_prediction</pre><pre>def logistic_regression(x_train,y_train,x_test,y_test,learningRate,iteration):<br>    dimension = x_train.shape[0]<br>    weight,bias = initialize(dimension)<br>    <br>    parameters, gradients = update(weight,bias,x_train,y_train,learningRate,iteration)</pre><pre>y_prediction = predict(parameters[&quot;weight&quot;],parameters[&quot;bias&quot;],x_test)</pre><pre>print(&quot;Manuel Test Accuracy: {:.2f}%&quot;.format((100 - np.mean(np.abs(y_prediction - y_test))*100)/100*100))</pre><pre>logistic_regression(x_train,y_train,x_test,y_test,1,100)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/0*VEJ3fIyRZHv1z2xE.png" /></figure><p>Manuel Test Accuracy: 86.89%</p><p>Let’s find out sklearn’s score.</p><h3>SKLEARN LOGISTIC REGRESSION</h3><pre>lr = LogisticRegression()<br>lr.fit(x_train.T,y_train.T)<br>print(&quot;Test Accuracy {:.2f}%&quot;.format(lr.score(x_test.T,y_test.T)*100))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*sVbxKJIvTRS2OYmcDObhFA.png" /></figure><h3>K-Nearest Neighbour (KNN) Classification</h3><p>Let’s see what will be score if we use KNN algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/0*GM96mvX4qq4GHtFl.png" /></figure><pre># KNN Model<br>from sklearn.neighbors import KNeighborsClassifier<br>knn = KNeighborsClassifier(n_neighbors = 2)  # n_neighbors means k<br>knn.fit(x_train.T, y_train.T)<br>prediction = knn.predict(x_test.T)</pre><pre>print(&quot;{} NN Score: {:.2f}%&quot;.format(2, knn.score(x_test.T, y_test.T)*100))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*NFPm8urxodWYLCvkfWpqmA.png" /></figure><pre># try ro find best k value<br>scoreList = []<br>for i in range(1,20):<br>    knn2 = KNeighborsClassifier(n_neighbors = i)  # n_neighbors means k<br>    knn2.fit(x_train.T, y_train.T)<br>    scoreList.append(knn2.score(x_test.T, y_test.T))<br>    <br>plt.plot(range(1,20), scoreList)<br>plt.xticks(np.arange(1,20,1))<br>plt.xlabel(&quot;K value&quot;)<br>plt.ylabel(&quot;Score&quot;)<br>plt.show()</pre><pre>print(&quot;Maximum KNN Score is {:.2f}%&quot;.format((max(scoreList))*100))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*XLtsU6zybZCICLEZgcGidg.png" /></figure><h3>Support Vector Machine (SVM) Algorithm</h3><p>Now we’ll use SVM algorithm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*TudH6YvvH7-h5ZyF2dJV2w.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*j8z8manFiUOFJ9im.jpg" /></figure><pre>from sklearn.svm import SVC</pre><pre>svm = SVC(random_state = 1)<br>svm.fit(x_train.T, y_train.T)</pre><pre>print(&quot;Test Accuracy of SVM Algorithm: {:.2f}%&quot;.format(svm.score(x_test.T,y_test.T)*100))<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/837/1*ZnZQbUBxIBpE3W7SURboxw.png" /></figure><h3>Naive Bayes Algorithm</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/0*bIwtY_1QKH090Lil.png" /></figure><pre>from sklearn.naive_bayes import GaussianNB<br>nb = GaussianNB()<br>nb.fit(x_train.T, y_train.T)<br>print(&quot;Accuracy of Naive Bayes: {:.2f}%&quot;.format(nb.score(x_test.T,y_test.T)*100))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*Ec_dY-zlumKU-taKMh9e3g.png" /></figure><h3>Decision Tree Algorithm</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/0*qEnFznBCBdVnS_9u" /></figure><pre>from sklearn.tree import DecisionTreeClassifier<br>dtc = DecisionTreeClassifier()<br>dtc.fit(x_train.T, y_train.T)<br>print(&quot;Decision Tree Test Accuracy {:.2f}%&quot;.format(dtc.score(x_test.T, y_test.T)*100))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*ShmTWav-roZF1rPNfJcoQw.png" /></figure><h3>Random Forest Classifications</h3><pre># Random Forest Classification<br>from sklearn.ensemble import RandomForestClassifier<br>rf = RandomForestClassifier(n_estimators = 1000, random_state = 1)<br>rf.fit(x_train.T, y_train.T)<br>print(&quot;Random Forest Algorithm Accuracy Score : {:.2f}%&quot;.format(rf.score(x_test.T,y_test.T)*100))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*d3jO5DFjsZK9L4MVaFivZA.png" /></figure><h3>Comparing Models</h3><pre>methods = [&quot;Logistic Regression&quot;, &quot;KNN&quot;, &quot;SVM&quot;, &quot;Naive Bayes&quot;, &quot;Decision Tree&quot;, &quot;Random Forest&quot;]<br>accuracy = [85.25, 90.16, 81.97, 85.25, 75.41, 85.25]<br>colors = [&quot;purple&quot;, &quot;green&quot;, &quot;orange&quot;, &quot;magenta&quot;,&quot;#CFC60E&quot;,&quot;#0FBBAE&quot;]</pre><pre>sns.set_style(&quot;whitegrid&quot;)<br>plt.figure(figsize=(16,5))<br>plt.yticks(np.arange(0,100,10))<br>plt.ylabel(&quot;Accuracy %&quot;)<br>plt.xlabel(&quot;Algorithms&quot;)<br>sns.barplot(x=methods, y=accuracy, palette=colors)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/0*hawWINBcG4-HvhIX.png" /></figure><p>Our models work fine but best of them are KNN and Random Forest with 88.52% of accuracy. Let’s look their confusion matrixes.</p><h3>Confusion Matrix</h3><pre># Predicted values<br>y_head_lr = lr.predict(x_test.T)<br>knn3 = KNeighborsClassifier(n_neighbors = 3)<br>knn3.fit(x_train.T, y_train.T)<br>y_head_knn = knn3.predict(x_test.T)<br>y_head_svm = svm.predict(x_test.T)<br>y_head_nb = nb.predict(x_test.T)<br>y_head_dtc = dtc.predict(x_test.T)<br>y_head_rf = rf.predict(x_test.T)</pre><pre>from sklearn.metrics import confusion_matrix</pre><pre>cm_lr = confusion_matrix(y_test,y_head_lr)<br>cm_knn = confusion_matrix(y_test,y_head_knn)<br>cm_svm = confusion_matrix(y_test,y_head_svm)<br>cm_nb = confusion_matrix(y_test,y_head_nb)<br>cm_dtc = confusion_matrix(y_test,y_head_dtc)<br>cm_rf = confusion_matrix(y_test,y_head_rf)</pre><pre>plt.figure(figsize=(24,12))</pre><pre>plt.suptitle(&quot;Confusion Matrixes&quot;,fontsize=24)<br>plt.subplots_adjust(wspace = 0.4, hspace= 0.4)</pre><pre>plt.subplot(2,3,1)<br>plt.title(&quot;Logistic Regression Confusion Matrix&quot;)<br>sns.heatmap(cm_lr,annot=True,cmap=&quot;Blues&quot;,fmt=&quot;d&quot;,cbar=False)</pre><pre>plt.subplot(2,3,2)<br>plt.title(&quot;K Nearest Neighbors Confusion Matrix&quot;)<br>sns.heatmap(cm_knn,annot=True,cmap=&quot;Blues&quot;,fmt=&quot;d&quot;,cbar=False)</pre><pre>plt.subplot(2,3,3)<br>plt.title(&quot;Support Vector Machine Confusion Matrix&quot;)<br>sns.heatmap(cm_svm,annot=True,cmap=&quot;Blues&quot;,fmt=&quot;d&quot;,cbar=False)</pre><pre>plt.subplot(2,3,4)<br>plt.title(&quot;Naive Bayes Confusion Matrix&quot;)<br>sns.heatmap(cm_nb,annot=True,cmap=&quot;Blues&quot;,fmt=&quot;d&quot;,cbar=False)</pre><pre>plt.subplot(2,3,5)<br>plt.title(&quot;Decision Tree Classifier Confusion Matrix&quot;)<br>sns.heatmap(cm_dtc,annot=True,cmap=&quot;Blues&quot;,fmt=&quot;d&quot;,cbar=False)</pre><pre>plt.subplot(2,3,6)<br>plt.title(&quot;Random Forest Confusion Matrix&quot;)<br>sns.heatmap(cm_rf,annot=True,cmap=&quot;Blues&quot;,fmt=&quot;d&quot;,cbar=False)</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aedwZEaf0c3SJrgu.png" /></figure><p>Thanks for your time!</p><p>LinkedIn: <a href="https://www.linkedin.com/in/canerdabakoglu/">https://www.linkedin.com/in/canerdabakoglu/</a></p><p>GitHub: <a href="https://github.com/cdabakoglu">https://github.com/cdabakoglu</a></p><p>Kaggle: <a href="https://www.kaggle.com/cdabakoglu">https://www.kaggle.com/cdabakoglu</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0ebf08e55c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[History of Olympics — Who are the most successful? — EDA]]></title>
            <link>https://medium.com/@cdabakoglu/history-of-olympics-who-are-the-most-successful-eda-c3ed28ef1ba2?source=rss-3ea29de4bb5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3ed28ef1ba2</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[olympics]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Caner Dabakoglu]]></dc:creator>
            <pubDate>Wed, 14 Nov 2018 20:55:33 GMT</pubDate>
            <atom:updated>2018-11-23T13:32:42.664Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://www.kaggle.com/cdabakoglu/history-of-olympics-who-are-the-most-successful">History of Olympics — Who are the most successful?</a> — EDA</h3><h3>OLYMPIC GAMES</h3><p>The Olympic Games is an international sports festival that began in ancient Greece. The first of the ancient Olympic Games date to 776 B.C. It was a religious festival honoring Zeus. Games were staged every fourth year for several hundred years, until it had banned by Roman emperor Theodosius because of they had pagan connotations in A.D. 394. However in 1896 the games were revived in Athens and in 1924 The Winter Olympics were introduced. Today Oympic Games are considered one of the bigger sports event with participants from more than 200 countries.</p><p>Let’s visualize data and see who are the most successful.</p><p>You can find codes on my GitHub: <a href="https://github.com/cdabakoglu">https://github.com/cdabakoglu</a></p><p>To show kernel in Kaggle : <a href="https://www.kaggle.com/cdabakoglu/terrorism-in-the-world-and-turkey-my-first-kernel">https://www.kaggle.com/cdabakoglu</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*2g_uOUQmzmj_02Uh71hYtQ.png" /></figure><p>Contents:</p><ol><li>Top 30 Countries</li><li>Athletics</li><li>Swimming</li><li>Shooting</li><li>Cycling</li><li>Wrestling</li><li>Football</li><li>Basketball</li><li>Sailing</li><li>Rowing</li><li>Fencing</li><li>Boxing</li><li>Weightlifting</li><li>Archery</li><li>Relations Between Age and Success</li><li>Women in Olympics</li><li>Most Successful Sporters</li></ol><h3>TOP 30 COUNTRIES</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*ZTu6cxmeBjpcanR9xmeNsg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*bDFk8CmGaf2JsvB4UY0YHA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*1lvtD_8kzRM6MGC_bs-JMQ.png" /></figure><p>Apparently United States of America is the most successful team in Olympics. Soviet Union and Germany follows USA respectively. Well, is USA most successful team in all sports? Let’s find out.</p><p>Let’s look some major sports;</p><pre>- Athletics<br>- Gymnastics<br>- Swimming<br>- Shooting<br>- Cycling<br>- Wrestling<br>- Football<br>- Basketball<br>- Sailing<br>- Rowing<br>- Fencing<br>- Boxing<br>- Weightlifting<br>- Archery</pre><h3>ATHLETICS</h3><p>Athletics is a collection of sporting events that involve competitive running, jumping, throwing, and walking. The most common types of athletics competitions are track and field, road running, cross country running, and race walking. <br>(Wikipedia)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*jmCNJ6C6a4mRz4mL" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z4l6-X1yx9ZYDVXI.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lhSu17KXLrYU5wOU.png" /></figure><p>Well, it seems Team USA is really fast!</p><h3>GYMNASTICS</h3><p>Gymnastics is a sport that requires balance, strength, flexibility, agility, coordination and endurance. The movements involved in gymnastics contribute to the development of the arms, legs, shoulders, back, chest and abdominal muscle groups. Alertness, precision, daring, self-confidence and self-discipline are mental traits that can also be developed through gymnastics. Gymnastics evolved from exercises used by the ancient Greeks that included skills for mounting and dismounting a horse, and from circus performance skills. (Wikipedia)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4L8RtOBsRYW1N5vo" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qNB9imwwj-eyPV_D.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_ImCghN-ZIgcx3kc.png" /></figure><p>Not suprisingly Soviet Union were dominating Gymnastics. Especially during Cold War USSR concentrate on create cultural dominance in Eastern Bloc. They invest to gymnastics and they had talented gymnasts and coach as well. Then gymnasitics had been popular.</p><p>An excerpt from a 2014 Yana Kudryavtseva (rythmic gymnast from Russia) interview:</p><p><strong>Q:</strong> “I have another question about the Russian team. Why do you think it is so dominant?”</p><p><strong>Kudryavtseva:</strong> “We have excellent coaches, choreographers and facilities in Novogorsk to help us prepare for competitions. The training facility is great and it’s staffed with doctors and masseuses. It would have been embarrassing if we didn’t win given the resources that we have. I don’t think any other country has such coaches or facilities.</p><h3>SWIMMING</h3><p>Swimming is an individual or team sport that requires the use of one’s arms and legs to move the body through water. The sport takes place in pools or open water (e.g., in a sea or lake). Competitive swimming is one of the most popular Olympic sports with varied distance events in butterfly, backstroke, breaststroke, freestyle, and individual medley. In addition to these individual events, four swimmers can take part in either a freestyle or medley relay. <br>(Wikipedia)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/0*mdq8m0Yaq1lh1H1G.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*R1d9yqNmWQUXGK1p.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*L8tw3iiuh2iNJxlf.png" /></figure><p>Americans know how they swim! <br>Swimming is very popular in the US and there are 10.4 million residential and 309,000 public swimming pools in the United States, according to the Association of Pool &amp; Spa Professionals (APSP).</p><h3>SHOOTING</h3><p>Shooting is the act or process of discharging a projectile from a ranged weapon. Shooting has inspired competition, and in several countries rifle clubs started to form in the 19th century. Soon international shooting events evolved, including shooting at the Summer and Winter Olympics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*LmCVJ_VjR7FR9GKk" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Corl3CcxmepgXEo2.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qnGiCposh3ONJziF.png" /></figure><h3>CYCLING</h3><p>Cycling has been contested at every Summer Olympic Games since the birth of the modern Olympic movement at the 1896 Summer Olympics, at which a road race and five track events were held. Mountain bike racing entered the Olympic programme at the Atlanta Olympics, followed by BMX racing in 2008. <br>(Wikipedia)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/0*2oX1U4cDPQ9WK_x3.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fmKtNSQbtTQ9FJ85.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cZxO4tU7UYyKR5UD.png" /></figure><p>We can see USA is not one of the major player in cycling. UK, France and Italy show themselves. Altought UK has most of the medals Italy has most of the gold medals with 70 and France has second place with 69 gold medals. Also Great Britain has 59 gold medals.</p><h3>WRESTLING</h3><p>Wrestling is a combat sport involving grappling type techniques such as clinch fighting, throws and takedowns, joint locks, pins and other grappling holds. The sport can either be theatrical for entertainment or genuinely competitive. Wrestling had been contested at the Summer Olympic Games since the sport was introduced in the ancient Olympic Games in 708 BC. When the modern Olympic Games resumed in Athens in 1896, wrestling (in the form of Greco-Roman wrestling) became a focus of the Games, with the exception of the 1900 Summer Olympics when wrestling did not appear on the program. Freestyle wrestling and weight classes both made their first appearance in 1904. The women’s competition was introduced in 2004.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*p0MbaIlxZTKIZPb4.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O3VrwILxgO0EoqCs.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kMpdv0xxMso6pQXS.png" /></figure><p>In the total the US has 128 and USSR(Russia is not include) has 116 medals. But USSR(Russia is not include) has 62 and USA has 52 gold medals. Also Japan has 32, Turkey and Russia both have 29 gold medals in wrestling.</p><h3>FOOTBALL</h3><p>Association football has been included in every Summer Olympic Games as a men’s competition sport, except 1896 and 1932. Women’s football was added to the official program in 1996.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/0*I7Y_018xZTXBH_dO.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0UTNz2u8nRp9LHQD.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LlNeBOnlna423jfQ.png" /></figure><p>As we can see Brazil has most of the medals. OK, is not surprise but when we can see graph of gold medals we can not see Brazil! Because Brazil has 136 medals in total and only 17 of them are gold, they have 89 silver 34 bronze medals. And we can see USA has most of the gold medals with 66, again!</p><h3>BASKETBALL</h3><p>Basketball at the Summer Olympics. Basketball at the Summer Olympics has been a sport for men consistently since 1936. Prior to its inclusion as a medal sport, basketball was held as a demonstration event in 1904. Women’s basketball made its debut in the Summer Olympics in 1976.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*64_KVColtkCn-xJT" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wfV21l7EcsMvqLLU.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XHsjYPCI37ANE5b3.png" /></figure><p>USA and NBA. There is no need to say anything.</p><h3>SAILING</h3><p>Sailing (also known as yachting until 2000) has been one of the Olympic sports since the Games of the I Olympiad, held in Athens, Greece, in 1896. Despite being scheduled in the first Olympic program, the races were canceled due to severe weather conditions. Apart from the 1904 Summer Olympics, sailing has been present in every edition of the Olympic Games. <br>(Wikipedia)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*4AGJ0BW7_oVNWyCR.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t0prejsWQyEdSv_t.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nZWoWP2EWRnxdcuU.png" /></figure><h3>ROWING</h3><p>Rowing is a sport whose origins reach back to Ancient Egyptian times. It involves propelling a boat (racing shell) on water using oars. By pushing against the water with an oar, a force is generated to move the boat. <br>Rowing has been part of the competition since its debut in the 1900 Summer Olympics. Rowing was on the program at the 1896 Summer Olympics but was cancelled due to bad weather. Only men were allowed to compete until the women’s events were introduced at the 1976 Summer Olympics in Montreal which gave national federations the incentive to support women’s events and catalysed growth in women’s rowing. <br>(Wikipedia)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/0*Sj8S-YYmcn5A1E3k" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UFPLWHN2l3HbyORZ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5xqHtid-WfrTdNuz.png" /></figure><p>USA seems have most gold medals in rowing with 160 but when we combine Germany, that has 95 gold medals and East Germany, has 139 gold medals. We can say Germany has more gold medals than USA with 234 gold medals.</p><h3>FENCING</h3><p>Fencing is a group of three related combat sports. The three disciplines in modern fencing are the foil, the épée, and the sabre; winning points are made through the contact with an opponent. A fourth discipline, singlestick, appeared in the 1904 Olympics but was dropped after that, and is not a part of modern fencing. Fencing was one of the first sports to be played in the Olympics. Based on the traditional skills of swordsmanship, the modern sport arose at the end of the 19th century, with the Italian school having modified the historical European martial art of classical fencing, and the French school later refining the Italian system. There are three forms of modern fencing, each of which uses a different kind of weapon and has different rules; thus the sport itself is divided into three competitive scenes: foil, épée, and sabre. Most competitive fencers choose to specialize in one weapon only. Fencing has been contested at every Summer Olympic Games since the birth of the modern Olympic movement at the 1896 Summer Olympics in Athens. Women’s foil made its Olympic debut in Paris, during the 1924 Olympic Games.</p><p>Foil — a light thrusting weapon; the valid target is restricted to the torso; double touches are not allowed. <br>Épée — a heavy thrusting weapon; the valid target area covers the entire body; double touches are allowed. <br>Sabre — a light cutting and thrusting weapon; the valid target area includes almost everything above the waist (excluding the back of the head and the hands); double touches are not allowed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/0*Ur0RT9WCfI6GBxbP.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oSE1nj2YMWvqeGMB.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jKR7sxeZOG2bGKTu.png" /></figure><p>Italy and France are still leader in fencing. They invented and evaluated it and it is not surprise to see them on the top.</p><h3>BOXING</h3><p>Boxing is a combat sport in which two people, usually wearing protective gloves, throw punches at each other for a predetermined amount of time in a boxing ring. Boxing has been contested at every Summer Olympic Games since its introduction to the program at the 1904 Summer Olympics, except for the 1912 Summer Olympics in Stockholm, because Swedish law banned the sport at the time. The 2008 Summer Olympics were the final games with boxing as a male only event. Since the 2012 Summer Olympics, women’s boxing is part of the program.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/0*5MNOfU7WaXQ8RtEL.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JfEv08nGCTp4Zwzg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QeG5sBxRqnrR3Pon.png" /></figure><p>United States has 113 Medals with 50 gold and Cuba follow USA with 37 gold medals and 73 Medals in total.</p><h3>WEIGHTLIFTING</h3><p>Weightlifting, is an athletic discipline in the modern Olympic programme in which the athlete attempts a maximum-weight single lift of a barbell loaded with weight plates. The two competition lifts in order are the snatch and the clean and jerk. The snatch is a wide grip one move lift. The Clean and Jerk is a close grip two move lift. Each weightlifter receives three attempts in each, and the combined total of the highest two successful lifts determines the overall result within a bodyweight category. Bodyweight categories are different for male and female competitors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*oFXO2d72bSGln7_j" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GIQj66uyHRis8p4z.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xbVH1NKYjf0bKWFw.png" /></figure><p>Russia (include Soviet Union) has 88 medals and 42 of them are gold. Chine follows Russia with 34 gold medals and 57 medals in total. USA has third place with 42 medals.</p><h3>ARCHERY</h3><p>Archery is the art, sport, practice or skill of using a bow to shoot arrows. The word comes from the Latin arcus. Historically, archery has been used for hunting and combat. In modern times, it is mainly a competitive sport and recreational activity. A person who participates in archery is typically called an archer or a bowman, and a person who is fond of or an expert at archery is sometimes called a toxophilite. <br>(Wikipedia)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/0*SurcuWBw9Y5EG6kn.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iLdgRuRBwUqgp0Eg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xh66Wt7ucC3X5JU8.png" /></figure><p>South Korea is most successful country in archery. They have 69 medals and 49 of them are gold. Belgium has 35 gold medals and USA follows it with 22 gold medals.</p><h3>RELATIONS BETWEEN AGE AND SUCCESS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*lquLaR_9My5bdz3J8SD3oA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bD6vjPP6v2p0JA84.png" /></figure><p>Obviously people between 18 and 35 years old are more successful. Most of medals were won by people ages between 20 and 28.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*IpEiS4CT_7aSLsIO7aeBBA.png" /></figure><h3>WOMEN IN OLYMPICS</h3><p>Even in the early years of the modern Olympics, women were not well represented. Women participated for the first time at the 1900 Paris Games with the inclusion of women’s events in lawn tennis and golf. Women’s athletics and gymnastics debuted at the 1928 Olympics. <br>(Wikipedia)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/0*joYIn5uhOWV6SxPB.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oIrpleilxTpXyPFw.png" /></figure><p>We are seeing USA on the top again. USA is the most successful country in Women Olypmics.</p><h3>MOST SUCCESSFUL SPORTERS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*b7IOZshJ29fVxwvc" /></figure><pre>Aeronautics<br>----------------------------<br>[Male] Hermann Schreiber : 1 Medals  -  SUI<br>*************************************************************************************************<br>Alpine Skiing<br>----------------------------<br>[Male] Kjetil Andr Aamodt : 8 Medals  -  NOR<br>[Female] Anja Sofia Tess Prson : 6 Medals  -  SWE<br>*************************************************************************************************<br>Alpinism<br>----------------------------<br>[Male] Tom George Longstaff : 1 Medals  -  GBR<br>[Female] Harriet Pauline &quot;Hettie&quot; Dyhrenfurth (Heyman-) : 1 Medals  -  SUI<br>*************************************************************************************************<br>Archery<br>----------------------------<br>[Male] Gerard Theodor Hubert Van Innis : 10 Medals  -  BEL<br>[Female] Kim Su-Nyeong : 6 Medals  -  KOR<br>*************************************************************************************************<br>Art Competitions<br>----------------------------<br>[Male] Alex Walter Diggelmann : 3 Medals  -  SUI<br>[Female] va Fldes : 1 Medals  -  HUN<br>*************************************************************************************************<br>Athletics<br>----------------------------<br>[Male] Paavo Johannes Nurmi : 12 Medals  -  FIN<br>[Female] Merlene Joyce Ottey-Page : 9 Medals  -  JAM<br>*************************************************************************************************<br>Badminton<br>----------------------------<br>[Male] Zhang Nan : 3 Medals  -  CHN<br>[Female] Gao Ling : 4 Medals  -  CHN<br>*************************************************************************************************<br>Baseball<br>----------------------------<br>[Male] Pedro Luis Lazo Iglesias : 4 Medals  -  CUB<br>*************************************************************************************************<br>Basketball<br>----------------------------<br>[Male] Carmelo Kyan Anthony : 4 Medals  -  USA<br>[Female] Teresa Edwards : 5 Medals  -  USA<br>*************************************************************************************************<br>Basque Pelota<br>----------------------------<br>[Male] Jos de Amzola y Aspiza : 1 Medals  -  ESP<br>*************************************************************************************************<br>Beach Volleyball<br>----------------------------<br>[Male] Ricardo Alex Costa Santos : 3 Medals  -  BRA<br>[Female] Kerri Lee Walsh Jennings : 4 Medals  -  USA<br>*************************************************************************************************<br>Biathlon<br>----------------------------<br>[Male] Ole Einar Bjrndalen : 13 Medals  -  NOR<br>[Female] Ursula &quot;Uschi&quot; Disl : 9 Medals  -  GER<br>*************************************************************************************************<br>Bobsleigh<br>----------------------------<br>[Male] Bogdan Musiol : 7 Medals  -  GDR<br>[Female] Elana Alessandra Meyers (-Taylor) : 2 Medals  -  USA<br>*************************************************************************************************<br>Boxing<br>----------------------------<br>[Male] Arnold Petrus Maria Vanderlijde : 3 Medals  -  NED<br>[Female] Ren Cancan : 2 Medals  -  CHN<br>*************************************************************************************************<br>Canoeing<br>----------------------------<br>[Male] Gert Fridolf Fredriksson : 8 Medals  -  SWE<br>[Female] Birgit Fischer-Schmidt : 12 Medals  -  GDR<br>*************************************************************************************************<br>Cricket<br>----------------------------<br>[Male] William Wallace Anderson : 1 Medals  -  GBR<br>*************************************************************************************************<br>Croquet<br>----------------------------<br>[Male] Georges douard Johin : 2 Medals  -  FRA<br>*************************************************************************************************<br>Cross Country Skiing<br>----------------------------<br>[Male] Edy Sixten Jernberg : 9 Medals  -  SWE<br>[Female] Raisa Petrovna Smetanina : 10 Medals  -  URS<br>*************************************************************************************************<br>Curling<br>----------------------------<br>[Male] Torger Nergrd : 2 Medals  -  NOR<br>[Female] Eva Maria Lund (-Eriksson) : 2 Medals  -  SWE<br>*************************************************************************************************<br>Cycling<br>----------------------------<br>[Male] Bradley Marc Wiggins : 8 Medals  -  GBR<br>[Female] Leontine Martha Henrica Petronella &quot;Leontien&quot; Zijlaard-van Moorsel : 6 Medals  -  NED<br>*************************************************************************************************<br>Diving<br>----------------------------<br>[Male] Dmitry Ivanovich Sautin : 8 Medals  -  EUN<br>[Female] Wu Minxia : 7 Medals  -  CHN<br>*************************************************************************************************<br>Equestrianism<br>----------------------------<br>[Male] Reiner Klimke : 8 Medals  -  GER<br>[Female] Isabelle Regina Werth : 10 Medals  -  GER<br>*************************************************************************************************<br>Fencing<br>----------------------------<br>[Male] Edoardo Mangiarotti : 13 Medals  -  ITA<br>[Female] Maria Valentina Vezzali : 9 Medals  -  ITA<br>*************************************************************************************************<br>Figure Skating<br>----------------------------<br>[Male] Gillis Emanuel Grafstrm : 4 Medals  -  SWE<br>[Female] Beatrix Suzetta Loughran (-Harvey) : 3 Medals  -  USA<br>*************************************************************************************************<br>Football<br>----------------------------<br>[Male] Dezs Novk : 3 Medals  -  HUN<br>[Female] Christie Patricia Pearce-Rampone : 4 Medals  -  USA<br>*************************************************************************************************<br>Freestyle Skiing<br>----------------------------<br>[Male] Dale Begg-Smith : 2 Medals  -  AUS<br>[Female] Kari Traa : 3 Medals  -  NOR<br>*************************************************************************************************<br>Golf<br>----------------------------<br>[Male] Henry Chandler Egan : 2 Medals  -  USA<br>[Female] Pauline &quot;Polly&quot; Whittier (-Iselin) : 1 Medals  -  USA<br>*************************************************************************************************<br>Gymnastics<br>----------------------------<br>[Male] Nikolay Yefimovich Andrianov : 15 Medals  -  URS<br>[Female] Larysa Semenivna Latynina (Diriy-) : 18 Medals  -  URS<br>*************************************************************************************************<br>Handball<br>----------------------------<br>[Male] Andrey Ivanovich Lavrov : 4 Medals  -  URS<br>[Female] Oh Seong-Ok : 4 Medals  -  KOR<br>*************************************************************************************************<br>Hockey<br>----------------------------<br>[Male] Udham Singh Kular : 4 Medals  -  IND<br>[Female] Luciana Paula &quot;Lucha&quot; Aymar : 4 Medals  -  ARG<br>*************************************************************************************************<br>Ice Hockey<br>----------------------------<br>[Male] Ji Holk : 4 Medals  -  TCH<br>[Female] Jayna Hefford : 5 Medals  -  CAN<br>*************************************************************************************************<br>Jeu De Paume<br>----------------------------<br>[Male] Neville Stephen Bulwer-Lytton : 1 Medals  -  GBR<br>*************************************************************************************************<br>Judo<br>----------------------------<br>[Male] Angelo Parisi : 4 Medals  -  GBR<br>[Female] Ryoko Tamura-Tani : 5 Medals  -  JPN<br>*************************************************************************************************<br>Lacrosse<br>----------------------------<br>[Male] William Thomas Passmore : 1 Medals  -  USA<br>*************************************************************************************************<br>Luge<br>----------------------------<br>[Male] Armin Zggeler : 6 Medals  -  ITA<br>[Female] Tatjana Hfner : 3 Medals  -  GER<br>*************************************************************************************************<br>Military Ski Patrol<br>----------------------------<br>[Male] Vin Elias Bremer : 1 Medals  -  FIN<br>*************************************************************************************************<br>Modern Pentathlon<br>----------------------------<br>[Male] Pavel Serafimovich Lednyov : 7 Medals  -  URS<br>[Female] lodie Pascaline Clouvel : 1 Medals  -  FRA<br>*************************************************************************************************<br>Motorboating<br>----------------------------<br>[Male] John Charles Field-Richards : 2 Medals  -  GBR<br>*************************************************************************************************<br>Nordic Combined<br>----------------------------<br>[Male] Felix Gottwald : 7 Medals  -  AUT<br>*************************************************************************************************<br>Polo<br>----------------------------<br>[Male] John &quot;Jack&quot; Wodehouse : 2 Medals  -  GBR<br>*************************************************************************************************<br>Racquets<br>----------------------------<br>[Male] John Jacob Astor : 2 Medals  -  GBR<br>*************************************************************************************************<br>Rhythmic Gymnastics<br>----------------------------<br>*************************************************************************************************<br>Roque<br>----------------------------<br>[Male] Smith O. Streeter : 1 Medals  -  USA<br>*************************************************************************************************<br>Rowing<br>----------------------------<br>[Male] Stephen Geoffrey &quot;Steven&quot; Redgrave : 6 Medals  -  GBR<br>[Female] Elisabeta Oleniuc-Lip : 8 Medals  -  ROU<br>*************************************************************************************************<br>Rugby<br>----------------------------<br>[Male] Daniel Brendon &quot;Dan&quot; Carroll : 2 Medals  -  ANZ<br>*************************************************************************************************<br>Rugby Sevens<br>----------------------------<br>[Male] Werner Kok : 1 Medals  -  RSA<br>[Female] Tyla Nathan-Wong : 1 Medals  -  NZL<br>*************************************************************************************************<br>Sailing<br>----------------------------<br>[Male] Charles Benedict &quot;Ben&quot; Ainslie : 5 Medals  -  GBR<br>[Female] Alessandra Sensini : 4 Medals  -  ITA<br>*************************************************************************************************<br>Shooting<br>----------------------------<br>[Male] Carl Townsend Osburn : 11 Medals  -  USA<br>[Female] Kimberly Susan &quot;Kim&quot; Rhode (-Harryman) : 6 Medals  -  USA<br>*************************************************************************************************<br>Short Track Speed Skating<br>----------------------------<br>[Male] Apolo Anton Ohno : 8 Medals  -  USA<br>[Female] Yang Yang : 10 Medals  -  CHN<br>*************************************************************************************************<br>Skeleton<br>----------------------------<br>[Male] Martins Dukurs : 2 Medals  -  LAT<br>[Female] Yelena Valeryevna Nikitina : 1 Medals  -  RUS<br>*************************************************************************************************<br>Ski Jumping<br>----------------------------<br>[Male] Matti Ensio Nyknen (-Paanala) : 5 Medals  -  FIN<br>[Female] Daniela Iraschko-Stolz : 1 Medals  -  AUT<br>*************************************************************************************************<br>Snowboarding<br>----------------------------<br>[Male] an Koir : 2 Medals  -  SLO<br>[Female] Kelly Clark : 3 Medals  -  USA<br>*************************************************************************************************<br>Softball<br>----------------------------<br>*************************************************************************************************<br>Speed Skating<br>----------------------------<br>[Male] Arnold Clas Robert Thunberg : 7 Medals  -  FIN<br>[Female] Claudia Pechstein : 9 Medals  -  GER<br>*************************************************************************************************<br>Swimming<br>----------------------------<br>[Male] Michael Fred Phelps, II : 28 Medals  -  USA<br>[Female] Dara Grace Torres (-Hoffman, -Minas) : 12 Medals  -  USA<br>*************************************************************************************************<br>Synchronized Swimming<br>----------------------------<br>*************************************************************************************************<br>Table Tennis<br>----------------------------<br>[Male] Wang Hao : 5 Medals  -  CHN<br>[Female] Wang Nan : 5 Medals  -  CHN<br>*************************************************************************************************<br>Taekwondo<br>----------------------------<br>[Male] Steven Lopez : 3 Medals  -  USA<br>[Female] Hwang Gyeong-Seon : 3 Medals  -  KOR<br>*************************************************************************************************<br>Tennis<br>----------------------------<br>[Male] Maxime Omer Mathieu &quot;Max&quot; Omer-Dcugis : 6 Medals  -  FRA<br>[Female] Kathleen &quot;Kitty&quot; McKane (-Godfree) : 5 Medals  -  GBR<br>*************************************************************************************************<br>Trampolining<br>----------------------------<br>[Male] Dong Dong : 3 Medals  -  CHN<br>[Female] Karen Cockburn (-Turgeon) : 3 Medals  -  CAN<br>*************************************************************************************************<br>Triathlon<br>----------------------------<br>[Male] Simon St. Quentin Whitfield : 2 Medals  -  CAN<br>[Female] Nicola Spirig Hug : 2 Medals  -  SUI<br>*************************************************************************************************<br>Tug-Of-War<br>----------------------------<br>[Male] John James Shepherd : 3 Medals  -  GBR<br>*************************************************************************************************<br>Volleyball<br>----------------------------<br>[Male] Srgio &quot;Escadinha&quot; Dutra dos Santos : 4 Medals  -  BRA<br>[Female] Inna Valeryevna Ryskal : 4 Medals  -  URS<br>*************************************************************************************************<br>Water Polo<br>----------------------------<br>[Male] Dezs Gyarmati : 5 Medals  -  HUN<br>[Female] Heather Petri : 4 Medals  -  USA<br>*************************************************************************************************<br>Weightlifting<br>----------------------------<br>[Male] Norbert &quot;Norb&quot; Schemansky : 4 Medals  -  USA<br>[Female] Agata Ewa Wrbel : 2 Medals  -  POL<br>*************************************************************************************************<br>Wrestling<br>----------------------------<br>[Male] Wilfried Dietrich : 5 Medals  -  GER<br>[Female] Saori Yoshida : 4 Medals  -  JPN<br>*************************************************************************************************</pre><p>LinkedIn: <a href="https://www.linkedin.com/in/canerdabakoglu/">https://www.linkedin.com/in/canerdabakoglu/</a></p><p>GitHub: <a href="https://github.com/cdabakoglu">https://github.com/cdabakoglu</a></p><p>Kaggle: <a href="https://www.kaggle.com/cdabakoglu">https://www.kaggle.com/cdabakoglu</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3ed28ef1ba2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>