<?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 Boyang Chen on Medium]]></title>
        <description><![CDATA[Stories by Boyang Chen on Medium]]></description>
        <link>https://medium.com/@boyangchen02?source=rss-4442f75e1292------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*slWLYQjh3vJ1G3YhU5E8wQ.jpeg</url>
            <title>Stories by Boyang Chen on Medium</title>
            <link>https://medium.com/@boyangchen02?source=rss-4442f75e1292------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 01:04:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@boyangchen02/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 Survival Analysis: Implementation in Python]]></title>
            <link>https://medium.com/@boyangchen02/time-series-survival-analysis-implementation-in-python-f31c43b3099d?source=rss-4442f75e1292------2</link>
            <guid isPermaLink="false">https://medium.com/p/f31c43b3099d</guid>
            <category><![CDATA[survival-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Boyang Chen]]></dc:creator>
            <pubDate>Mon, 23 May 2022 19:37:45 GMT</pubDate>
            <atom:updated>2022-05-24T11:44:27.195Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*nhvUAn_CkAteMYju7eHqvw.png" /></figure><p>Survival Analysis is a branch of statistical modelling that is optimal for working with censored, time-to-event data. Which can be used to address questions such as ‘how long would it be, before a particular event occurs’.</p><p>Such data-sets are common in medical studies. Given a <strong>cohort of patients</strong> and an <strong>observation window</strong>, we would observe the <strong>event </strong>(such as death, commencement/recovery of/from disease etc) for some of the patients, whereas other patients would be <strong>censored</strong>, either because the observation period ended or because they dropped out from the study prematurely.</p><p>This analysis can be further applied to not just medical events, but to many different types of events of interest in different business domains such as customer analytics, failure-time analysis, marketing analytics and actuaries.</p><h3><strong>Objectives</strong></h3><p><strong>Most survival analysis studies uses the following methods:</strong></p><p>1. Kaplan-Meier plots to visualize survival curves.</p><p>2. Cox proportional hazards regression to find out the effect of different variables like age, sex, weight on survival.</p><p><strong>Section 1: Import and Explore Relevant Data</strong></p><p>For our analysis, we will use the <em>lifelines</em> library in Python. Our first step will be to install and import the library, along with some of the classics.</p><pre><em>import</em> pandas <em>as</em> pd<br><em>import</em> numpy <em>as</em> np<br><em>import</em> matplotlib.pyplot <em>as</em> plt<br><em>import</em> seaborn <em>as</em> sns<br><em>from</em> lifelines <em>import</em> KaplanMeierFitter, CoxPHFitter<br><em>from</em> lifelines.plotting <em>import</em> plot_lifetimes<br>%matplotlib inline</pre><p>Next, we will import the data and perform some basic cleaning.</p><pre>data = pd.read_csv(&quot;/kaggle/input/heart-failure-clinical-data/heart_failure_clinical_records_dataset.csv&quot;</pre><pre># check datatype and column dtypes, non-null values.<br>data.info()</pre><pre># check for missing values <br>data.isnull().sum()</pre><p>Seems like there is no missing values.</p><p><strong>Correlation heatmap</strong></p><pre><em>import</em> seaborn <em>as</em> sns</pre><pre>corr = data.corr().sort_values(<em>ascending</em>=False, <em>key</em>=lambda <em>x</em>: abs(<em>x</em>), <em>by</em>=&quot;DEATH_EVENT&quot;)</pre><pre>ax = sns.heatmap(corr, <em>vmin</em>=-1, <em>vmax</em>=1, <em>center</em>=0, <em>cmap</em>=sns.diverging_palette(20, 220, <em>n</em>=200), <em>square</em>=True,)</pre><pre>ax.set_xticklabels(ax.get_xticklabels(), <em>rotation</em>=45, <em>horizontalalignment</em>=&#39;right&#39;)</pre><pre>ax.set_title(&quot;Heart Failure Survival Heatmap&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*hahRAuFA64uMgveikE_drg.png" /></figure><h3>Modelling Approaches</h3><p>In this notebook, I will explore 2 models:</p><ol><li><strong>Kaplan-Meier Estimator</strong></li></ol><p>The Kaplan-Meier estimator is a test statistic that gives us an approximation of the true survival function of a population, the approximation getting better with increasing sample size. This estimator can robustly handle censoring, and can be derived from the Hazard Function using Maximum Likelihood Estimation.</p><p>This estimator can be used for simple comparison of survival rates between groups (For instance, survival rates between smokers and non-smokers).</p><p>2. <strong>Cox Proportional Hazard Model</strong></p><p>The Cox Proportional Hazard Model is a survival analysis model that assumes that the baseline hazard function of a population is multiplicatively influenced by the covariates. For instance, given a group of smokers and non-smokers, the baseline hazard of the population is multiplied by 2 in case of smokers.</p><p>The Cox Proportional Hazard model can be used to model hazard rates based on multiple features, either categorical or numerical.</p><h3>Section 2: Plotting the Kaplan-Meier Curve</h3><p>The Kaplan-Meier Curve represents a simple non-parametric visualization of survival likelihood function in our data. In that sense, it can be thought of as part of the EDA process for survival analysis. Let’s start by fitting a simple Kaplan-Meier Curve on our data.</p><pre>kmf = KaplanMeierFitter()<br>kmf.fit(data.time, data.DEATH_EVENT, <em>label</em> = &#39;Kaplan Meier Estimate, full sample&#39;)<br>kmf.plot(<em>linewidth</em>=4, <em>figsize</em>=(12, 6))<br>plt.title(&#39;Heart Failure Survival: Kaplan-Meier Curve&#39;)<br>plt.xlabel(&#39;Tenure (Months)&#39;)<br>plt.ylabel(&#39;Survival probability&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*1X0lJ-Bo69_VBfTQ0_v7MQ.png" /></figure><p>From the fitted object, we can also see the survival probabilities by accessing the survival_function_ attribute:</p><pre>kmf.survival_function_</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*dNxr-DhLQ5LQDIGmXHrp6Q.png" /></figure><p>The Kaplan-Meier model provides a table of the cumulative survival probability by time. Such “life tables” are commonly used by life insurance companies in planning life insurance products.</p><h3>Section 3: Examining Variables</h3><p>A Kaplan-Meier plot can also be used to analyse impact of categorical features on survival. For example, is there a decrease in survival for patients with anaemia vs patients without anaemia?</p><p>As we continue to examine the survival function, we may want to relate survival risk with features, or characteristics of our patients. In this example, we will look at differences in survival risk for patients who have anaemia, vs. patients who don’t have anaemia. We can start by plotting a simple histogram for each category.</p><pre>df1 = data[data.anaemia==1]<br>df2 = data[data.anaemia==0]</pre><pre>kmf.fit(df1.time, df1.DEATH_EVENT)<br>kmf.plot(<em>label</em>=&#39;With Anaemia&#39;, <em>figsize</em>=(12, 6))<br>kmf.fit(df2.time, df2.DEATH_EVENT)<br>kmf.plot(<em>label</em>=&#39;Without Anaemia&#39;)<br>plt.title(&#39;Anaemia and Death: Kaplan-Meier Curve&#39;)<br>plt.xlabel(&#39;Months&#39;)<br>plt.ylabel(&#39;Survival probability&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*T0EhuVFEMSEn-4sCmqh6Pw.png" /></figure><p>Are individuals with hypertension (high blood pressure) associated with increased risk of death?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*FY3E1QbF6V5f8OqPg5r3eg.png" /></figure><p>Unsurprisingly, the above plots shows us that patients with hypertension or anaemia have a increased risk of death.</p><p>However, as demonstrated in the Kaplan Meier curves, hypertension and anaemia do carry increased risk of death but the confidence intervals are wide enough that these are not statistically significant.</p><p>Going back to the life insurance example, insurance companies can use such simple models to design business rules for life insurance products. For a smoker, their insurance premiums will be adjusted upwards to counteract the lowered survival probability.</p><h3>Section 4: Cox Proportional Hazards Model</h3><p>Kaplan-Meier curves are useful only when the predictor variable is categorical (e.g.: treatment A vs treatment B; males vs females). They don’t work easily for quantitative predictors such as gene expression, weight, or age.</p><p>An alternative method is the Cox proportional hazards regression analysis, which works for both quantitative predictor variables and for categorical variables. Furthermore, the Cox regression model extends survival analysis methods to assess simultaneously the effect of several risk factors on survival time.</p><pre><em># Using Cox Proportional Hazards Model</em></pre><pre>cph = CoxPHFitter()<br>cph.fit(data, <em>duration_col</em>=&#39;time&#39;, <em>event_col</em>=&#39;DEATH_EVENT&#39;)</pre><p><strong>Risk factors</strong></p><p>Lets plot the individual risk factors</p><pre>cph.plot()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*Xx7xpc5sYOI-8iuOCo6OGA.png" /></figure><p>Here, we can see the coefficient estimate, along with error bars used to assess statistical significance. We see that high blood pressure, anaemia, serum creatinine, age and ejection fraction are all within the 95% confidence interval of affecting HF death.</p><p>Simply put, older patients with high blood pressure, anaemia andincreased serum creatine levels are more likely to die of heart failure. Whereas, higher ejection fraction (Percentage of blood leaving the heart at each contraction) is associated with HF survival.</p><p><strong>Evaluation</strong></p><p>The most common way to measure the performance of a Cox model is to use the Concordance index or C-index. The C-index for a survival model can be thought of as the weighted average of the area under time-specific Receiver Operating Characteristic (ROC) curves.</p><pre>cph.print_summary(<em>columns</em>=[&quot;coef&quot;,&quot;exp(coef)&quot;,&quot;exp(coef) lower 95%&quot;,&quot;exp(coef) upper 95%&quot;, &quot;z&quot;, &quot;p&quot;], <em>decimals</em>=3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*uU0xZyoAxoWQc5nZip-kxA.png" /></figure><p>In the above table, the key output is exp(coef). This is interpreted as the scaling of hazard risk for each additional unit of the variable, 1.00 being neutral.</p><p>For example, the exp(coefficient) corresponding to high_blood_pressure predicts a individual with hypertension is 1.6 more times more likely to die from heart failure.</p><h3>Section 5: Using a survival model</h3><p>A survival model will allow us to estimate how likely a person is to survive or die over time. As an example, we will plot the expected survival function for individual #6 and #69 in the dataset</p><pre>cph.predict_survival_function(data.loc[6]).plot(<em>title</em>=&quot;Survival probability for patient 6 over time&quot;)<br>plt.xlabel(&quot;Time in weeks&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*AK4NoRYrIjEwEsq5EmJJ0Q.png" /></figure><pre>cph.predict_survival_function(data.loc[69]).plot(<em>title</em>=&quot;Survival probability for patient 69 over time&quot;)<br>plt.xlabel(&quot;Time in weeks&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*AxjzemkQUMyerSX-JLJdeQ.png" /></figure><p>Patient #6 has a poor outlook, whereas patient 69 has a good chance of surviving past 30 weeks.</p><p><strong>Conclusions</strong></p><ul><li>The predictive power of the <strong>ejection fraction</strong> is shown very well through the use of the Kaplan Meier curves. A lower ejection fraction seems to have some correlation with increased death. This seems reasonable as typically a low stroke volume is associated with congestive heart failure.</li><li>As expected, <strong>age</strong> also shows a strong correlation with survival, as made apparent through the Kaplan Meier curves.</li><li>Those with <strong>high blood pressure</strong> have an increased risk of death. This is reasonable as hypertension is a major risk factor for heart failure.</li><li><strong>Anaemia</strong> is associated with increased risk of death. Again, this is reasonable as anaemia is a common comorbidity of heart failure.</li><li>Elevated <strong>serum_creatinine</strong> levels appears to indicate increased death.</li></ul><p><strong>Further Work</strong></p><p>Creating the survival curves at each patient level can help us proactively create a tailored made strategy for high risk patients for different survival risk segments along the timeline.</p><h4><strong>Resources</strong></h4><p>The Heart Failure Prediction dataset can be found on <a href="https://www.kaggle.com/datasets/andrewmvd/heart-failure-clinical-data">Kaggle</a>.</p><p>The Jupyter notebook associated with the project can be found on my <a href="https://github.com/bchen022/Machine_Learning_Deep_Learning_Projects/blob/6fe9cc01192cadfe2ecbc79fd5b8e9270a82557c/Heart_failure_survival_analysis.ipynb">Github</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f31c43b3099d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image Classification using Convoluted Neural Networks (Keras) — Deep Learning Algorithm]]></title>
            <link>https://medium.com/@boyangchen02/vehicle-detection-using-convoluted-neural-networks-keras-7fca55f8eb9b?source=rss-4442f75e1292------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fca55f8eb9b</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Boyang Chen]]></dc:creator>
            <pubDate>Mon, 21 Feb 2022 12:00:41 GMT</pubDate>
            <atom:updated>2022-02-21T14:47:56.588Z</atom:updated>
            <content:encoded><![CDATA[<p>Image classification is one of the most important applications of deep learning and Artificial Intelligence. Let’s take a look at the images below (refer to Figure.1). As a human, I can confidently identify what the images depict with ease, however, for a machine this is a challenge. This is where deep learning comes in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*xae2Nk0VVh6uP_xMXOrfSg.png" /><figcaption>Figure 1. Sample images of vehicles and non-vehicles</figcaption></figure><p>Image classification refers to the task of assigning labels to images based on certain characteristics or features present in them. Image classification is done with the help of neural networks. Neural networks are deep learning algorithms. The below picture shows a neural network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*rO867DpyvwTcvcUV6hh05w.png" /><figcaption>Diagram of a Neural Network. Source: <a href="https://www.investopedia.com/terms/n/neuralnetwork.asp">Investopedia</a></figcaption></figure><p>Neural Networks contain multiple layers of neurons that perform prediction, classification, etc. The output of each neuron is fed to the neurons in the next layer which helps fine-tune the output until we reach the final output layer. The different layers which are present in a neural network are :</p><ul><li>Input Layer: This is the layer through which we give the input to your neural network</li><li>Hidden Layer: This layer contains various neurons which process the input received from the input layer</li><li>Output Layer: The final layer in the network which processes your data one last time and gives you the output</li></ul><p>Neural networks can be easily implemented using a deep learning library like <a href="https://www.simplilearn.com/tutorials/deep-learning-tutorial/what-is-keras">Keras</a>,<a href="https://www.simplilearn.com/tutorials/deep-learning-tutorial/tensorflow"> Tensorflow</a>, or <a href="https://www.simplilearn.com/keras-vs-tensorflow-vs-pytorch-article">Pytorch</a>.</p><h3>Vehicle Image Classification Dataset</h3><p>I dataset I will be using is the Vehicle Detection Image Set which can be found on <a href="https://www.kaggle.com/brsdincer/vehicle-detection-image-set">Kaggle</a>. This dataset contains around 17k images of vehicles and non-vehicles of dimensions (64x64) separated in two folders named: vehicles and non-vehicles.</p><p>The approach used for this analysis has four stages exploratory data analysis, data pre-processing, model building, and a model evaluation/error analysis. will be using the keras package for Python for model building and training.</p><p><strong>Import the required libraries</strong></p><pre><em>from</em> tensorflow <em>import</em> keras<br><em>from</em> keras <em>import</em> optimizers<br><em>from</em> tensorflow.keras.models <em>import</em> Sequential<br><em>from</em> tensorflow.keras.layers <em>import</em> Dense, Conv2D , MaxPool2D , Flatten , Activation, Dropout, MaxPooling2D, Input<br><em>from</em> tensorflow.keras.preprocessing.image <em>import</em> ImageDataGenerator<br><em>from</em> tensorflow.keras.optimizers <em>import</em> Adam<br><em>from</em> kerastuner.tuners <em>import</em> RandomSearch<br><em>from</em> keras.callbacks <em>import</em> EarlyStopping</pre><pre><em>from</em> sklearn.metrics <em>import</em> classification_report,confusion_matrix<br><em>from</em> sklearn.model_selection <em>import</em> train_test_split</pre><pre><em>import</em> cv2<br><em>import</em> os<br><em>from</em> os.path <em>import</em> join</pre><pre><em>import</em> pandas <em>as</em> pd<br><em>import</em> numpy <em>as</em> np<br><em>import</em> matplotlib.pyplot <em>as</em> plt<br><em>import</em> seaborn <em>as</em> sns</pre><pre><em>import</em> tqdm<br><em>from</em> tensorflow.keras.preprocessing <em>import</em> image</pre><p>After importing the necessary modules, we can load the image data. Using the <em>os</em> module, we can define the path to our data and specify the main directory.</p><pre>path = &quot;/&quot;<br>dir_list = os.listdir(path)</pre><pre><em># specify the main directory<br></em>maindir = &quot;/vdata&quot;</pre><pre>vehicle_dir = &quot;/vdata/vehicles&quot;<br>nonvehicle_dir = &quot;/vdata/non-vehicles&quot;<br>vehicle = os.listdir(maindir+&quot;/vehicles&quot;)<br>non_vehicle = os.listdir(maindir+&quot;/non-vehicles&quot;)</pre><p><strong>Data visualization</strong></p><p>Let’s take a look at the images files before we process the data, the openCV-Python is a library of Python bindings designed to solve computer vision problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*cVvpR6bTcaTDMvMzUTCCCA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*cMgEEUXV_W9bXPr1WklgVQ.png" /><figcaption>Sample images from the dataset</figcaption></figure><p><strong>Loading the data</strong></p><p>Once we have defined our path. We will use for loops to create two lists train and label. For each image in the folder ‘vehicle’ we will assign it a label “vehicle” and vice versa. We use the Opencv imread function to read the images in the RGB format and resize the images to our desired width and height in this case both being 64. This may take a bit of time for it to run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*iFtNJFSv4mmsw3ugBgzYfw.png" /></figure><p>Then we need to convert the images into numerical data that the machine can utilise in order to analyse the pixel values and look for patterns in them.</p><pre>train = np.array(train)<br>label = np.array(label)<br>train.shape,label.shape</pre><pre>output<br>((17760, 64, 64, 3), (17760,))</pre><p>The shape of the image is 64 x 64x 3 where 64 represents the height, 64 the width, and 3 represents the number of color channels. When we say 64 x 64 it means we have 4096 pixels in the data and every pixel has an R-G-B value hence 3 color channels.</p><pre>plt.style.use(&quot;ggplot&quot;)<br>plt.figure(<em>figsize</em>=(12,5))<br>sns.countplot(<em>x</em> = label)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*E0Df5zYxITMQurKArHr7Fw.png" /><figcaption>Proportion of Vehicle and non-Vehicle in the dataset</figcaption></figure><p>We can see that our data set is balanced. That’s good for building a classification model.</p><p><strong>Pre-processing and label encoding</strong></p><p>Convert labels ‘vehicle’ and ‘non-vehicle’ to binary classes (1/0)</p><pre><em>from</em> tensorflow.keras.utils <em>import</em> to_categorical<br><em>from</em> sklearn.preprocessing <em>import</em> LabelEncoder<br><em>from</em> sklearn.utils <em>import</em> shuffle</pre><pre>le = LabelEncoder()<br>label= le.fit_transform(label)</pre><pre>label = to_categorical(label)<br>train,label = shuffle(train, label)<br>print(label.shape)</pre><pre>output<br>(17760, 2)</pre><p><strong>Train test split</strong></p><p>We will need to split our dataset into train and test sets. In this case, we can use the sklearn.train_test_split procedure as the dataset is balanced and the sample size is large enough.</p><ul><li>Train dataset: Used to fit the machine learning model</li><li>Test dataset: Used to evaluate the fit machine learning model</li></ul><pre>x_train,x_test,y_train,y_test = train_test_split(train,label,<em>test_size</em>=0.2,<em>random_state</em> = 42)</pre><pre>x_train.shape<br>output<br>(14208, 64, 64, 3)</pre><pre>y_train.shape<br>output<br>(14208, 2)</pre><p><strong>Model building</strong></p><p>The convolutional neural network (CNN) is a class of <strong>deep learning neural networks</strong>. CNNs represent a huge breakthrough in image recognition. They’re most commonly used to analyze visual imagery and are frequently working behind the scenes in image classification. They can be found at the core of everything from Facebook’s photo tagging to self-driving cars.</p><p>CNN works by extracting features from the images. Any CNN consists of the following:</p><ol><li>The input layer which is a grayscale image</li><li>The Output layer which is a binary or multi-class labels</li><li>Hidden layers consisting of convolution layers, ReLU (rectified linear unit) layers, the pooling layers, and a fully connected Neural Network</li></ol><p>In our first CNN model, it is not going to be very deep. It contains three convolutional layers following by a <em>maxpooling</em> layers. We will use the default <em>stride </em>(1,1) and add <em>padding</em> (“same”) into the model.</p><p>A <em>dropout</em> layer is added (for regularization) after the third <em>maxpooling</em> layer. <em>Flatten</em> is added to reduce down to one dimension. Finally, a <em>dense</em> layer is added so the output specifies the two classes that we have.</p><pre>model = Sequential()<em><br></em>model.add(Conv2D(32, 3,<em>padding</em>=&quot;same&quot;, <em>activation</em>=&quot;relu&quot;, <em>input_shape</em>=(64,64,3)))<br>model.add(MaxPool2D())<br>model.add(Conv2D(32, 3, <em>padding</em>=&quot;same&quot;, <em>activation</em>=&quot;relu&quot;))<br>model.add(MaxPool2D())<br>model.add(Conv2D(64, 3, <em>padding</em>=&quot;same&quot;, <em>activation</em>=&quot;relu&quot;))<br>model.add(MaxPool2D())<br>model.add(Dropout(0.4))<br>model.add(Flatten())<br>model.add(Dense(128,<em>activation</em>=&quot;relu&quot;))<br>model.add(Dense(2, <em>activation</em>=&quot;sigmoid&quot;))<br>model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/1*xXHLWhlBPpADNYKgNj408Q.png" /></figure><p>We will use <em>adam</em> as the optimizer and <em>binary_crossentropy</em> to calculate loss.</p><pre>opt = Adam(<em>lr</em>=0.001)<br>model.compile(<em>optimizer</em> = opt , <em>loss</em> = &quot;binary_crossentropy&quot;, <em>metrics</em> = [&#39;accuracy&#39;])</pre><pre>history = model.fit(x_train,y_train,<em>epochs</em> = 10 ,<em>batch_size</em>=10, <em>validation_data</em> = (x_test,y_test))</pre><p><strong>Model Evaluation</strong></p><p>We should see a decrease in loss and increase in accuracy of the model with every epoch (a pass across the entire dataset). As the model learns, the accuracy improves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*oT8Xhy9-_twV_jmqDy3rGA.png" /></figure><p>Along with this, you can also save the model predictions and use them to make a classification report of different metrics such as precision, recall, etc to get a clear view of how well the model is performing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*IamMizYion6iFNf4zWmVXg.png" /><figcaption>Classification report</figcaption></figure><p>We see high scores across the board with a 0.99 f1 score. The number of misclassifications were low evidenced by the high precision score of 0.99 and recall score of 0.99.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*hNdN8m5mGf5E4_hmvrDTuw.png" /><figcaption>Confusion matrix</figcaption></figure><pre>model.evaluate(x_test,y_test)<br>output<br>[0.03514926880598068, 0.9878941178321838]</pre><p>Overall model scores: loss: 0.0351 — accuracy: 0.9879. This model is apt for the purpose of image classification.</p><p><strong>Visualization of the predicted data</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*L5yqIl28okySDwP-cOsGcQ.png" /><figcaption>Actual versus predicted results. Red box shows a false negative result.</figcaption></figure><p>We find that the model works quite well with accuracy of 98.94% on training dataset and 99.18% on test dataset. However, as shown in the figure above, there are rare situations were the model incorrectly predicts the absence of a car when it is actually present (false negative).</p><p><strong>Hyperparameter tuning</strong></p><p>A neural network can be defined as a framework that combines inputs and tries to guess the output. If we are lucky enough to have some results, called “the ground truth”, to compare the outputs produced by the network, we can calculate the <strong>error</strong>. So the network guesses, calculates some error function, guesses again, trying to minimize this error, guesses again, until the error does not go down any more. This is optimization.</p><p>Now instead of trying different values by hand, we will use RandomSearchCV from Keras-tuner to try out several values for our hyperparameters and compare the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*N3n3CJsykBd2YFw13zQyqQ.png" /><figcaption>define a function for your model using different weight initializations</figcaption></figure><p>Useful optimisation parameters include: number of convolutional layers, number of dense layers, number of filters, padding, strides, dropout, learning rate, batch number, number of epochs etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*BQ2pwzqqDW8eB2XkkAUuzw.png" /><figcaption>Keras-tuner RandomSearch module</figcaption></figure><p>Of course, automating the tuning of hyperparameters may not always be feasible for a number of reasons:</p><ol><li><strong>It takes a very long time to train a network (e.g. &gt; 1 week).</strong> In this case, you’ll want to be smart about the hyperparameter configuration that you choose to test with. And in most practical cases, using a human being is the simplest way to do it.</li><li><strong>It’s too complicated to set up the extra tuning code. </strong>In some cases, its just easier (in terms of man-hours spent) to manually tune the network. This is relative to the complexity of your network and the number of hyperparameters that requires optimization.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*F5sv8vZibyP131Ok_QV-Rw.png" /></figure><p>In this case the tuning process took around 3 hours to run. But it is worth paying attention to the validation error as you are training the network. Because, if the rate at which the training error decreases is significantly higher than the rate at which the validation error decreases, the model is probably overfitting. So you may end the training early, and decrease the number of nodes/layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*guY6LnQGMB1SxZG0cxasqw.png" /><figcaption>Model summary of the best model</figcaption></figure><p><strong>Model Evaluation</strong></p><pre>model_2.evaluate(val_generator)</pre><pre>[0.004094030242413282, 0.9997183680534363]</pre><p>Model 1 (untuned): Loss 0.0351, accuracy: 0.9879.</p><p>Model 2 (tuned): Loss 0.0041, accuracy: 0.9997.</p><p><strong>Summary</strong></p><p>This is an step by step guide on the building of a convolutional neural network for the application of image classification. I have also demonstrated how you can use RandomSearch to tune the hyperparameters of your deep learning networks in Python using Keras and scikit-learn. Jupyter notebook is available on <a href="https://github.com/bchen022/ML_EDA_projects/blob/f6fe03a38e9937002c54c609b0ff40a22b0466aa/vehicle_classification_notebook1.ipynb">Github</a>.</p><p>Do you have any experience tuning hyperparameters of large neural networks? Please share your stories below.</p><p><strong>Note</strong></p><p>A common mistake is to start with a giant, complicated network and expect it to be a magic bullet. What you want to do instead is to start simple and grow the network. If it looks like the network is converging pretty fast with a single layer, take a mental snapshot and increase it to, say, 3-layers. If a 3-layer network gets worse validation error than the simpler model (given the same training error), we’re probably overfitting. So we should stop training and try something simpler.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fca55f8eb9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Customer Churn Prediction using Machine Learning Classification Algorithms]]></title>
            <link>https://medium.com/@boyangchen02/customer-churn-prediction-using-machine-learning-classification-algorithms-bbfbf63002d7?source=rss-4442f75e1292------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbfbf63002d7</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[churn-prediction]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Boyang Chen]]></dc:creator>
            <pubDate>Sun, 30 Jan 2022 16:46:12 GMT</pubDate>
            <atom:updated>2022-01-30T16:46:12.486Z</atom:updated>
            <content:encoded><![CDATA[<p>Churn prediction is a common use case in machine learning domain. If you are not familiar with the term, churn means “leaving the company”. It is very critical for a business to have an idea about why and when customers are likely to churn. Having a robust and accurate churn prediction model helps businesses to take actions to prevent customers from leaving the company.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qjuZnAsQiGFIuE_-X-wGPQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@robertocortese">Roberto Cortese</a><strong> </strong>on <a href="https://unsplash.com/s/photos/e-commerce">Unsplash</a></figcaption></figure><p>In this project, I will use a ‘Customer Churn’ dataset which is available on <a href="https://www.kaggle.com/ermismbatuhan/digital-marketing-ecommerce-customer-behavior/code).">Kaggle</a>. I will employ three different classifier models to find the best candidate algorithm that accurately predicts whether a customer is churned or not. The full code can be found in my <a href="https://github.com/bchen022/ML_EDA_projects/blob/3a3777de00dd4cce443421200b48f3170dc8afd4/Customer_churn_analysis.ipynb">Jupyter notebook</a>.</p><p>This dataset includes data on the service usage habits of a company’s customers and tags that indicate whether the relevant customer has left the company. The definition of the columns is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*f-MglksDxxAJohtsqp-qEQ.png" /></figure><p><strong>The project is structured as follows:</strong></p><p>1. Exploratory Data Analysis</p><p>2. Data Pre-processing</p><p>3. Model Creation and Evaluation</p><p>4. Improving the Model</p><h3><strong>Exploratory Data Analysis</strong></h3><p>First Import the data and examine the features.</p><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br>import numpy as np</pre><pre>filepath = &#39;customer_churn_data.csv&#39; <br>data = pd.read_csv(filepath, sep=&#39;;&#39;, decimal=&#39;,&#39;)</pre><p>The dataset contains 3333 rows and 20 columns. There is no null values in the dataset. At a quick glance, credit_card_info_save and push_status are categorical columns, these will be encoded into integers.</p><pre>for i in data.select_dtypes(include = [&#39;object&#39;]).columns.values:<br>  data[i] = data[i].replace([&quot;yes&quot;,&quot;no&quot;],[1,0])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*kIGYEeTbrwoteUcZAjv-tQ.png" /></figure><p>The location_code column is also categorical with only 3 values and these will be one hot encoded. This is where the integer encoded variable is removed and a new binary variable is added for each unique integer value.</p><pre>one_hot = pd.get_dummies(data[&#39;location_code&#39;], prefix = &quot;_&quot;)<br>del data[&quot;location_code&quot;]<br>data = data.join(one_hot)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*NWM41mfLB-SZ7zWp9cG0Fg.png" /><figcaption>The distribution of the target variable: churn vs not churned.</figcaption></figure><p>The data is skewed at around 85% towards non-churned customers this will be important to remember when model building.</p><p><strong>Correlation</strong></p><p>Using seaborn, we can plot a heatmap of the variable correlations.</p><pre>fig, ax = plt.subplots(figsize=(15,10))<br>sns.heatmap(data.corr())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*3p8Au9yPEmI3ydOv14WiLw.png" /></figure><p>Lighter colors indicate high correlation. The highly correlated features include desktop_sessions and app_sessions, add_to_wishlist and push_status, session_duration and desktop_transactions, avg_product_value and discount_rate_per_visited_product, and finally, Product_detail_view_per_app_session and add_to_cart_per_session.</p><p>For our target variable churn, we can see weaker correlations with features such as credit_card_info_save, desktop_sessions, app_sessions and customer_service_calls.</p><p><strong>Distribution of numerical features</strong></p><p>Some of the columns are numerical. You want to see the shape of the data’s distribution, especially when determining whether the output of a process is distributed approximately normally. If the data is significantly skewed in a certain direction and log transformation may be required.</p><pre>fig, axes = plt.subplots(5,3, figsize=(24,24))<br>fig.suptitle(&quot;Distribution of Variables&quot;, size=30)</pre><pre>for i in range(5):<br>  for j in range(3):<br>    sns.histplot(data[numeric_columns[3*i+j]], ax=axes[i,j],    kde=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*FMCmmHujDHQj84NDfgyFYA.png" /></figure><p>The variables generally converge to the normal distribution, but the variables app_transactions, add_to_wishlist and customer_service_calls appear to be skewed to the right.</p><h3>Pre-processing</h3><p><strong>Feature Scaling</strong></p><p>We need to perform Feature Scaling when we are dealing with Gradient Descent Based algorithms (Linear and Logistic Regression, Neural Network) and Distance-based algorithms (KNN, K-means, SVM) as these are very sensitive to the range of the data points.</p><p>MinMaxScaler scales all the data features in the range [0, 1] or else in the range [-1, 1] if there are negative values in the dataset.</p><pre>from sklearn.preprocessing import MinMaxScaler<br>mm = MinMaxScaler()<br>for column in [numeric_columns]:<br>  data[column] = mm.fit_transform(data[column])</pre><pre># Drop the User_id column as it does not provide any useful information<br>data.drop(columns=&quot;user_id&quot;, inplace=True)</pre><p>Now that all of our data is encoded and scaled, we can separate the features (X) from the target (y, churn).</p><pre>X = data.drop(columns=&#39;churn&#39;)<br>X_features = X.columns.tolist()</pre><p><strong>Train-test split</strong></p><p>Train-test Split is a technique used to evaluate the performance of a machine learning algorithm</p><p>- Train dataset: Used to fit the machine learning model</p><p>- Test dataset: Used to evaluate the fit machine learning model</p><p>Since we do not have a balanced distribution of churn and not churned data (85% not churned), it is more appropiate to select the stratified train-test split method to preserve the same proportions of the values of each classes in the original dataset.</p><pre># Train_test split<br>from sklearn.model_selection import StratifiedShuffleSplit<br># Get the split indexes<br>strat_shuf_split = StratifiedShuffleSplit(n_splits=1, test_size=0.3, random_state=42)<br>train_idx, test_idx = next(strat_shuf_split.split(data[X_features], data.churn))<br># Create the dataframes<br>X_train = data.loc[train_idx, X_features]<br>y_train = data.loc[train_idx, &#39;churn&#39;]<br>X_test  = data.loc[test_idx, X_features]<br>y_test  = data.loc[test_idx, &#39;churn&#39;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*BdYVV_xM4eT658JY6xcYpw.png" /></figure><p>We can see with the stratified split, we maintain the proportion of churned (15%) and not churned (85%) classes from the original dataset.</p><h3><strong>Model Creation and Evaluation</strong></h3><p><strong>Logistic Regression</strong></p><p>We will first fit a logistic regression model without any regularization using all the features. Then we will use cross validation to determine the hyperparameters, fit models using L1 and L2 regularization.</p><pre>from sklearn.linear_model import LogisticRegression<br># Standard logistic regression<br>lr = LogisticRegression(solver=&#39;liblinear&#39;).fit(X_train, y_train)</pre><pre>from sklearn.linear_model import LogisticRegressionCV<br># L1 regularized logistic regression<br>lr_l1 = LogisticRegressionCV(Cs=10, cv=4, penalty=&#39;l1&#39;, solver=&#39;liblinear&#39;).fit(X_train, y_train)</pre><pre># L2 regularized logistic regression<br>lr_l2 = LogisticRegressionCV(Cs=10, cv=4, penalty=&#39;l2&#39;, solver=&#39;liblinear&#39;).fit(X_train, y_train)</pre><p>Predict the class and the probability for each model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*hqQsrKqkGFLTq4mSxmHt1w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*KPi-ll-rSI7VF7OzYgKYMg.png" /></figure><p>Regularizations are techniques used to reduce the error by fitting a function appropriately on the given training set and avoid overfitting. When we apply regularization, we add an additional penalty term in the error function. The additional term controls the excessively fluctuating function such that the coefficients don’t take extreme values.</p><p>Error metrics: precision, recall, fscore, accuracy, area under the curve (AUC)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*5zjqvsw3dILp7wmg3fB7YA.png" /></figure><p><strong>Confusion matrix</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*5Vsu2mWFA_m8am5H3Oabfw.png" /><figcaption><strong>X axis represent the actual values and Y axis represent predicted values</strong></figcaption></figure><p>We see the logistic regression model has a tendency to predict churned customer even when they are not churned.</p><p><strong>K Nearest Neighbours</strong></p><p>The KNN algorithm assumes that similar things exist in close proximity. In other words, similar things are near to each other. Essentially, this is calculated by the distance between two points. The straight-line distance (also called the Euclidean distance) is a popular and familiar choice.</p><pre>from sklearn.neighbors import KNeighborsClassifier<br>from sklearn.metrics import confusion_matrix, accuracy_score, classification_report, f1_score</pre><pre>knn = KNeighborsClassifier(n_neighbors=5, weights=&#39;distance&#39;)<br>knn = knn.fit(X_train, y_train)<br>y_pred = knn.predict(X_test)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*fCc9P3XHRPjDRmSdCOQgvQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*V4LEHuiBFPaj5JqVjqscYg.png" /></figure><p>Similar to the logistic regression model, the KNN model is good at predicting non-churned customers, as demonstrated by the high precision, recall and f1 scores. Model accuracy is also slightly higher at 0.88 compared to 0.86 of the logistic regression model. However, the number of false positives are still relatively high and the predictive ability of the model is low with an f1 score of 0.44.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*nJOY32pGuTG1WFUrNDWAgA.png" /></figure><p>To determine the right value for K, I examined results for values of K from 1 to 40. This time focusing on the F-1 score and error rate (1 -accuracy). F1-scores decrease with increasing K values. Based on the elbow method, k=5 is identified as the optimal k value for this model.</p><p><strong>Parameter Tuning using Gradient Boosting</strong></p><p>Gradient Boost (GB) builds an additive model in a forward stage-wise fashion; it allows for the optimization of arbitrary differentiable loss functions. In each stage regression trees are fit on the negative gradient of the binomial or multinomial deviance loss function. Binary classification is a special case where only a single regression tree is induced.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*5OAKkXtVrawyPtosjtKPow.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*Q28f0QQ8MsItRGdRbqaHUQ.png" /></figure><p>Compared to the LR and KNN models, we now see higher scores across the board with the GB model. Precision values for churn is still lower at 0.77 but the recall score is now higher at 0.91. In this model, we only see 33 false positives and accuracy score is now 96%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*wugijyaoqH0f5JEbWFe0_A.png" /></figure><p><strong>Conclusions</strong></p><p>The gradientboost model with the optimised parameters (‘n_estimators’: 200, ‘learning_rate’: 0.1, ‘max_features’: 6) is shown to be the best classification model for the customer churn dataset, with an f1 score of 0.96. The number of misclassifications were low as evidenced by the high precision score of 0.88 and recall score of 0.94.</p><p><strong>Next Steps</strong></p><p>We can always try to improve the model. The fuel of machine learning models is data so if we can collect more data, it is always helpful in improving the model.</p><p>The dataset is skewed towards non-churned (85%), a solution to this could be use upsampling to balance the classes. However, resampling the data typically leads to lower precision and recall.</p><p>We can also try a wider range of parameters in GridSearchCV because a little adjustment in a parameter may slightly increase the model accuracy.</p><p>Finally, we can try more robust or advanced models. Please keep in mind that there will be a trade-off when making such kind of decisions. Advanced models may increase the accuracy but they require more data and more computing power. So it comes down to business decision.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbfbf63002d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Level Difficulty in Candy Crush Saga — DataCamp Data Science Project]]></title>
            <link>https://medium.com/@boyangchen02/level-difficulty-in-candy-crush-saga-datacamp-data-science-project-28b979c402d7?source=rss-4442f75e1292------2</link>
            <guid isPermaLink="false">https://medium.com/p/28b979c402d7</guid>
            <category><![CDATA[candy-crush-saga]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Boyang Chen]]></dc:creator>
            <pubDate>Wed, 01 Dec 2021 16:08:50 GMT</pubDate>
            <atom:updated>2021-12-01T16:08:50.735Z</atom:updated>
            <content:encoded><![CDATA[<h3>Level Difficulty in Candy Crush Saga — DataCamp Data Science Project</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*90oawLMSVPGBK2PUQOZ3NQ.png" /><figcaption>Sourced from <a href="https://www.king.com/game/candycrush">https://www.king.com/game/candycrush</a></figcaption></figure><p><a href="https://king.com/game/candycrush"><strong>Candy Crush Saga</strong></a> is a hit mobile game developed by King (part of Activision|Blizzard) that is played by millions of people all around the world.</p><p>The goal of the game is to match similar candy together to clear the level and progress to the next one. Candy Crush has more than 3000 levels, and new ones are added every week.</p><p>In this project, we will see how we can use data collected from players to estimate level difficulty.</p><p>First import the libraries you will need.</p><pre># import libraries<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import numpy as np<br>import seaborn as sns<br>from matplotlib.pyplot import Figure</pre><p>Use pandas read.csv function to read the data</p><pre>data = pd.read_csv(&quot;candy_crush.csv&quot;)</pre><pre># convert data into pandas dataframe.<br>df = pd.DataFrame(com_data)</pre><p>The data type of the date column should be changed to datetime.</p><pre># convert data type of date column to datetime<br>df[&#39;dt&#39;] = pd.to_datetime(df[&#39;dt&#39;])</pre><p>The .<strong>info()</strong> function is used to print a concise summary of a DataFrame. This method prints information about a DataFrame including the index dtype and column dtypes, non-null values and memory usage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*5QfyYIwLClrU9veqTGpQ2g.png" /></figure><p><strong>Number of players that played on a particular level</strong></p><pre>num_player_per_level = df[[&#39;level&#39;,&#39;player_id&#39;]].groupby(&#39;level&#39;).count()</pre><pre>sns.barplot(data=num_player_per_level, x=num_player_per_level.index, y=&#39;player_id&#39;)<br>plt.ylabel(&#39;Number of players&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*dksloPCbocnTJHiu4sj9pg.png" /></figure><p>There is a total of 15 levels in this dataset. Level 15 has an abnormally high player count.</p><p><strong>Data manipulation using Pandas</strong></p><p>You call <strong>.groupby()</strong> and pass the name of the column you want to group on, which is ‘level’. You use the [‘column_name’] to specify the columns on which you want to perform the actual aggregation.</p><pre># creating a new dataframe to show the number of attempts and successes on each level.<br>level_df = df[[&#39;level&#39;, &#39;num_attempts&#39;,&#39;num_success&#39;]].groupby(&#39;level&#39;).sum()</pre><pre># winning players on each level (players that win atleast once on each level)<br>winners = df[[&#39;level&#39;,&#39;num_success&#39;]].groupby(&#39;level&#39;).apply(lambda x:(x&gt;0).sum())<br>level_df[&#39;num_winners&#39;] = winners[&#39;num_success&#39;]</pre><pre># number of players with no success on each level<br>losers = df[[&#39;level&#39;,&#39;num_success&#39;]].groupby(&#39;level&#39;).apply(lambda x:(x==0).sum())<br>level_df[&#39;num_losers&#39;] = losers[&#39;num_success&#39;]</pre><pre># total number of players<br>level_df[&#39;num_players&#39;] = level_df[&#39;num_winners&#39;]+level_df[&#39;num_losers&#39;]</pre><pre># Average number of attempts to win a level: # attempts/ # success<br>level_df[&#39;attempts_success_ratio&#39;] = level_df[&#39;num_attempts&#39;]/level_df[&#39;num_success&#39;]</pre><pre># win rate on each level (lower value = more difficult)<br>win_rate = df.groupby([&#39;level&#39;])[[&#39;num_attempts&#39;,&#39;num_success&#39;]].agg(&#39;sum&#39;)<br>level_df[&#39;win_rate&#39;] = (win_rate.num_success) / (win_rate.num_attempts)</pre><pre># player_win_lose_ratio: # winning players/ total # players<br>level_df[&#39;player_win_lose_ratio&#39;] = level_df[&#39;num_winners&#39;]/level_df[&#39;num_players&#39;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*auksii_IrOlqdra0eZcp1g.png" /></figure><p>The new dataframe should contain all the information you need. Now visualise the data using matplotlib.pyplot and seaborn.</p><pre>fig, ax = plt.subplots(5,1, figsize=(8,13), gridspec_kw={&#39;hspace&#39;:.8})</pre><pre>plt.sca(ax[0])<br>sns.barplot(data=level_df, x=level_df.index, y=&#39;num_success&#39;)<br>plt.title(&quot;Total num success for each level&quot;)<br>plt.xlabel(&#39;&#39;)</pre><pre>plt.sca(ax[1])<br>sns.barplot(data=level_df, x=level_df.index, y=&#39;num_attempts&#39;)<br>plt.title(&quot;Total num attempts for each level&quot;)<br>plt.xlabel(&#39;&#39;)</pre><pre>plt.sca(ax[2])<br>sns.barplot(data=level_df, x=level_df.index, y=&#39;attempts_success_ratio&#39;)<br>plt.title(&quot;Average number of attempts to win a level&quot;)<br>plt.xlabel(&#39;&#39;)</pre><pre>plt.sca(ax[3])<br>sns.barplot(data=level_df, x=level_df.index, y=&#39;win_rate&#39;)<br>plt.title(&quot;Win rate for each level&quot;)<br>plt.xlabel(&#39;&#39;)</pre><pre>plt.sca(ax[4])<br>sns.barplot(data=level_df, x=level_df.index, y=&#39;player_win_lose_ratio&#39;)<br>plt.title(&quot;Winning players / total players&quot;)</pre><p><strong>Exploratory Data Analysis</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*ymyvfVp6YgcwT9Oxi7KmlA.png" /></figure><p>Levels 8 and 15 require on average over 20 attempts to achieve a win. Whilst every other level require no more than 10 attempts.</p><p>As expected, levels 8 and 15 have the low win rates with 0.04 and 0.03 respectively. Levels 5, 7, 9, 11, and 12 also have low win rates (around 0.1). However, the low win rate by itself does not necessarily indicate a high difficulty.</p><p><strong>Correlations between success, attempts, win rate and number of players</strong></p><pre>sns.heatmap(level_df.corr(),cmap=&#39;RdBu&#39;,annot=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*BbE_ZjeV7t-EYiFczEEQmg.png" /></figure><p>As expected the attempts/success ratio, num_attempts are negatively correlated with player win/loss ratio. Generally the harder levels (low win/loss ratio) require more attempts to succeed. Number of successes is uncorrelated with win rate and player win/lose ratio.</p><p><strong>Linear regression model</strong></p><pre>from sklearn.linear_model import LinearRegression</pre><pre>reg = LinearRegression()</pre><pre>temp = level_df.sort_values(by=&#39;player_win_lose_ratio&#39;)</pre><pre>y = temp[&#39;num_players&#39;].values.reshape(-1,1)</pre><pre>X = temp[&#39;player_win_lose_ratio&#39;].values.reshape(-1,1)</pre><pre>sns.regplot(data=level_df, x=1/level_df[&#39;player_win_lose_ratio&#39;], y=&#39;num_players&#39;,order=1,robust=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*kVX9arhpvb-s3fau0DY4Lw.png" /></figure><p>There seems to be a linear correlation between win/lose ratio and number of players. We see that the hardest levels (level 8 and 15) have the most number of players.</p><p>Looking at the correlation graph, lvl 15 appears to be an outlier with 3374 players. One explanation for this is that when a player succeeds on a hard level, that player is more likely to share his/her score to friends, and as a result more players play this level.</p><p><strong>Profiles of player who play multiple levels</strong></p><pre>profile = df[[&#39;player_id&#39;,&#39;level&#39;,&#39;num_attempts&#39;]].pivot_table(index=&#39;player_id&#39;,columns=&#39;level&#39;,values=&#39;num_attempts&#39;,fill_value=False,aggfunc=(lambda x: np.sum(x)&gt;0))</pre><pre>plt.spy(profile.values.astype(float)[:10,:])<br>plt.xlabel(&quot;level&quot;)<br>plt.ylabel(&quot;counts&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*dnHxTXJsScJ21gznA6A5vg.png" /></figure><p>We can see that many players that played the higher levels did not play the lower levels. This could explain why there is a very low win rate for level 15 since most player who attempted this level did not practise on the easier level and thus, they are not well versed in the mechanics of the game.</p><p><strong>Conclusion</strong></p><p>It is important for the game developers to have easy, medium and hard levels. This way competitive players are guaranteed to be challenged on some levels whilst keeping the casual players engaged. The main takeaway from this data analysis is that, hard levels can keep the players engaged by requiring more attempts and time on the game. Additionally, I observed that many players go straight to the hard levels without playing the easy levels. This suggests that many players find the challenge and high difficulty more rewarding. To incentivise the players to play easy level, developers could consider providing more rewards e.g. exp or coins on the easy levels.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28b979c402d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tutorial: Exploratory Data Analysis of Cryptocurrency Sentiment on Reddit using Python.]]></title>
            <link>https://medium.com/@boyangchen02/tutorial-exploratory-data-analysis-of-reddit-sentiment-on-ethereum-b63685f82e98?source=rss-4442f75e1292------2</link>
            <guid isPermaLink="false">https://medium.com/p/b63685f82e98</guid>
            <category><![CDATA[reddit]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <dc:creator><![CDATA[Boyang Chen]]></dc:creator>
            <pubDate>Tue, 30 Nov 2021 13:42:29 GMT</pubDate>
            <atom:updated>2021-11-30T13:44:37.374Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*NO3lVOs7LjXogOwRkJuXKg.png" /></figure><p>The web3.0 world of cryptocurrency has taken the Internet by storm. The decentralized computer and financial platform Ethereum is one of the most important and well-known ones. In this dataset, we explore the social network behaviour and discussions happening around Ethereum over the course of its evolution.</p><p>This <a href="https://www.kaggle.com/pavellexyr/the-reddit-ethereum-dataset">Kaggle dataset </a>contains a comprehensive collection of comments mentioning the term “Ethereum” in their text body. It contains all mentions of Ethereum on Reddit, up to 1st of November 2021. The data is procured using <a href="https://socialgrep.com/datasets?utm_source=kaggle&amp;utm_medium=link&amp;utm_campaign=theredditethereumdataset#the-reddit-ethereum-dataset">SocialGrep.</a> The comments are already labelled with their score and sentiment scores.</p><p>Here, I will be showing you basic exploratory data analysis (EDA) methods you can carry out using Python.</p><p><strong>Methodology</strong></p><p>Libraries you will be using for data manipulation and visualization include: pandas, matplotlib.pyplot, numpy, seaborn, datetime, yfinance.</p><p>Simply use pip install or !pip install if you use Jupyter notebook.</p><p><strong>Download the dataset from Kaggle</strong></p><pre># use read_scv function to read the data<br>com_data = pd.read_csv(&quot;the-reddit-ethereum-dataset-comments.csv&quot;)</pre><pre># convert data into pandas dataframe<br>df = pd.DataFrame(com_data)</pre><p>The default datetime column is in the unix timestamp format, but we will create a new column in the datetime format for increased readability.</p><pre>df[&#39;time&#39;] = pd.to_datetime(df[&#39;created_utc&#39;], unit=&#39;s&#39;).apply(lambda x: x.to_datetime64())</pre><p><strong>Checking the dataset</strong></p><p>Total number of unique commenters: 1,132,331</p><pre>num_users = df[&#39;id&#39;].nunique()<br>print(&#39;Total number of users: {}&#39;.format(num_users))</pre><p>Time period for which we have the data: 3813 days 10:07:22</p><pre>period = df[&#39;time&#39;].max() - df[&#39;time&#39;].min()<br>print(&#39;Time period for which we have the data: {}&#39;.format(period))</pre><p>Oldest comment: 2011–05–25 13:52:30. Most recent comment: 2021–11–01 23:59:52.</p><pre>print(&#39;Oldest comment: {}&#39;.format(df[&#39;time&#39;].min()))</pre><pre>print(&#39;Most recent comment: {}&#39;.format(df[&#39;time&#39;].max()))</pre><p><strong>Most active subreddits</strong></p><pre># Here we are checking for the top 8 most active subreddits<br>subreddit = df[&#39;subreddit.name&#39;].value_counts()[:8].sort_values(ascending=False)<br>print(subreddit)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*Z3yOxlgmioZy5ftaZjza_Q.png" /></figure><p>There are thousands of smaller subreddits that may contain comments mentioning ETH. For visual clarity, I only included the top subreddits.</p><p>One way representing this data is using pie charts.</p><pre># first convert the results to dataframe<br>sub_df = pd.DataFrame(subreddit)<br>sub_df.reset_index(inplace=True)<br>sub_df.rename(columns={&#39;index&#39;:&#39;subreddit&#39;,&#39;subreddit.name&#39;:&#39;values&#39;},inplace=True)</pre><p>For subreddits outside of the top 8, I will group them into an ‘others’ category.</p><pre># create a copy of the sub_df<br>df2 = sub_df[:8].copy()</pre><pre># others category<br>new_row = pd.DataFrame(data = {&#39;subreddit&#39; : [&#39;others&#39;],<br> &#39;values&#39; : [df[&#39;subreddit.name&#39;].value_counts()[8:].sum()]<br> })</pre><pre># combining top 8 with the new row containing other subreddits data<br>new_df = pd.concat([df2, new_row])</pre><p>Lets plot the pie charts</p><pre>fig, axes = plt.subplots(nrows = 1, ncols = 2, figsize = (15,6))<br>sub_df.plot(kind = &#39;pie&#39;, y = &#39;values&#39;, labels =sub_df[&#39;subreddit&#39;], autopct=&#39;%.2f&#39;, ax = axes[0])<br>new_df.plot(kind = &#39;pie&#39;, y = &#39;values&#39;, labels =new_df[&#39;subreddit&#39;], autopct=&#39;%.2f&#39;, ax = axes[1])</pre><pre>axes[0].set_title(&#39;Top 8 subreddits&#39;)<br>axes[0].legend(loc=&quot;upper left&quot;)<br>axes[1].set_title(&#39;All subreddits&#39;)<br>axes[1].legend(loc=&quot;lower right&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-JD5PWZAk97vXKeXhNqTNQ.png" /></figure><p>We can see the subreddits where ETH is most mentioned are: cryptocurrency, ethtrader and ethereum. This is not surprising as these subreddits also have the highest amount of subscribers.</p><p>Additionally, we may want to find out how the reddit trend has changed over time.</p><pre># first create a column names &#39;year&#39;<br>df[&#39;year&#39;] = df[&#39;time&#39;].dt.year</pre><p>Total number of comments each year will show the reddit trend but we can combine this with the names of subreddits to see whether which subreddits are the main drivers for the increase in ETH popularity.</p><pre># groupby function to group the year and subreddit columns <br>grouped = df.groupby([&quot;year&quot;, &quot;subreddit.name&quot;]).size().reset_index(name=&quot;values&quot;)</pre><pre>grouped.sort_values(&#39;values&#39;, ascending=False, inplace=True)</pre><p>stacked bar chart is useful for visualising this data. <a href="https://pandas.pydata.org/docs/reference/api/pandas.pivot_table.html">.pivot_table</a>. function both reshapes and aggregates the data.</p><pre># we will create stacked bar chart to show this data <br>pivot = grouped.pivot(index=&#39;year&#39;, columns=&#39;subreddit.name&#39;, values=&#39;values&#39;)</pre><pre># select the top subreddits <br>pivot2 = pivot[[&#39;cryptocurrency&#39;,&#39;ethtrader&#39;,&#39;ethereum&#39;,&#39;ethfinance&#39;,&#39;bitcoin&#39;,&#39;btc&#39;,&#39;dogecoin&#39;,&#39;ethermining&#39;,&#39;cardano&#39;,&#39;u_anticensor_bot&#39;]]</pre><pre># graph plotting<br>pivot2.plot.bar(stacked=True, figsize=(10, 6), ylabel=&#39;number of comments mentioning ETH&#39;, xlabel=&#39;year&#39;, title=&#39;Trending subreddits from 2011 to 2021&#39;)<br>plt.legend(title=&#39;subreddit&#39;, bbox_to_anchor=(1.05, 1), loc=&#39;upper left&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*aIbLcOxgFZ8qmk8aq5GBNg.png" /></figure><pre># Price data<br>ETH_price = yf.download(&#39;ETH-USD&#39;, period=&quot;max&quot;, interval=&quot;1mo&quot;)</pre><pre>plt.figure(figsize=(20,10))<br>plt.plot(ETH_price.Close, color=&#39;k&#39;,alpha=0.7)<br>plt.title(label= &#39;ETH-USD&#39;,fontsize=25)<br>plt.ylabel(ylabel= &#39;Price (USD)&#39;, fontsize=15)<br>plt.xlabel(xlabel=&#39;Date&#39;, fontsize=15)<br>plt.show()</pre><p>Crypto markets had a large bull run in late 2017 to early 2018, this is reflected in the large peak in 2017 of reddit comments that mentioned ethereum. It is worth to note that, most comments were posted on either ethtrader and ethereum which are specific to ETH, but not much on the general ‘cryptocurrency’ subreddit.</p><p>As the markets cooled down in 2019 and 2020, interest in cryptocurrency and ETH began to dwindle, the parabolic price spike in 2021 is reflected in the bar chart, with over 4 times increase in the number of comments compared to the previous year (2020).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*avO0P_9YwFP1-a8VYgsZUw.png" /></figure><p>Overall, there is a clear correlation between ETH price history and the reddit trend. Over the years, ETH has gain more mainstream media attention and there has been a migration of commenters into the general subreddits like ‘r/cryptocurrency’.</p><p><strong>Sentiment Analysis</strong></p><p>Each comment is assigned a sentiment score base on whether the piece of text is negative, positive or neutral. This is achieved using a Sentiment Analyzer package. The sentiment score ranges between -1 and 1 where, 1 is extremely positive, 0 is neutral and -1 is extremely negative.</p><p>For this analysis we assume comments with a sentiment score of between 0.2 to -0.2 are neutral.</p><pre># create a list for the conditions and choices<br>col = &#39;sentiment&#39;</pre><pre>conditions = [df[col] &gt; 0.2, (df[col] &lt; 0.2) &amp;(df[col] &gt; -0.2), df[col] &lt;-0.2]</pre><pre>choices = [1,0,-1]</pre><pre>df[&quot;label&quot;] = np.select(conditions, choices, default=np.nan)</pre><p>Using the pivot_table. method as shown before we can generate a stacked bar chart showing the sentiment over time.</p><pre>group2 = df.groupby([&quot;year&quot;, &quot;label&quot;]).size().reset_index(name=&quot;values&quot;)<br>group2.sort_values(&#39;values&#39;, ascending=False, inplace=True)</pre><pre>piv = group2.pivot(index=&#39;year&#39;, columns=&#39;label&#39;, values=&#39;values&#39;)</pre><pre>mylabels =[&#39;Negative&#39;, &#39;Neutral&#39;, &#39;Positive&#39;]</pre><pre>piv.plot.bar(stacked=True, figsize=(10, 6), ylabel=&#39;numer of comments mentioning ETH&#39;, xlabel=&#39;year&#39;, title=&#39;sentiment trend from 2011 to 2021&#39;)<br>plt.legend(title=&#39;sentiment scores&#39;, labels=mylabels, bbox_to_anchor=(1.05, 1), loc=&#39;upper left&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*CXMP19AGW16EnKavGbcpxg.png" /></figure><p>As you can see, the reddit sentiment on ETH is overwhelmingly positively. Positive comments outweighed the negative comments even during ‘bearish’ market conditions (2019 and 2020). In this graph, we used annual intervals but it may be better to use smaller time intervals as social media sentiments can change very quickly especially within the crypto space.</p><p><strong>Word Distribution Analysis</strong></p><p>We will then generate a word distribution of the most common words within the comments that are associated with their respective sentiment labels.</p><p>Tokenization is the process of breaking a stream of text up into meaningful elements called tokens. You can tokenize a paragraph into sentences, a sentence into words and so on.</p><p>For this you will need to install the <strong>nltk</strong> library.</p><pre>import nltk<br>from nltk.tokenize import word_tokenize, RegexpTokenizer</pre><pre>tokenizer = RegexpTokenizer(r&#39;\w+&#39;)</pre><p>Download or define a list of stopwords, these are ‘filler’ words such as ‘a’, ‘and’, ‘it’, ‘the’ which don’t add any useful information.</p><pre>from nltk.corpus import stopwords</pre><pre>stops = nltk.corpus.stopwords.words(&#39;english&#39;)</pre><p>Then, define a function that will read a list of comments and perform lowercasing, tokenizing and stopwords removal.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9ef92bc23c2a82d110082b6b9492cab/href">https://medium.com/media/f9ef92bc23c2a82d110082b6b9492cab/href</a></iframe><p>Lets look at the positive word distributions for October 2021. First specific the time range.</p><pre>start_oct = dt.datetime(year=2021,month=10, day=1)</pre><pre>end_oct = dt.datetime(year=2021, month=10, day=31)</pre><pre>temp_df = df.loc[(df[&#39;time&#39;].between(start_oct,end_oct)),[&#39;subreddit.name&#39;,&#39;body&#39;,&#39;label&#39;]]</pre><p>For example, you can specify rows that are labelled positive (1) and posted from the “cryptocurrency” subreddit.</p><pre>pos_lines = list(temp_df[(temp_df.label == 1) &amp; (temp_df[&#39;subreddit.name&#39;] == &quot;cryptocurrency&quot;)].body)</pre><pre>pos_tokens = process_text(pos_lines)</pre><pre>pos_freq = nltk.FreqDist(pos_tokens)</pre><pre>pos_freq.most_common(20)</pre><p>For negative comments you need to change label == -1. Lets plot the results in a bar chart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*tlstvANqr0EI9P0pzk1x6w.png" /></figure><p>Now we can compare the word distributions in both positive and negative comments. Unsurprisingly, words such as ‘gas’ and ‘fees’ appear quite often within negative comments as Ethereum blockchain is notorious for its high transaction fees.</p><p>For more informative analysis, you can try to analysis the most frequently appearing bi-gram (2 words) or tri-grams (3 words) using the <strong>nltk.ngram </strong>tool.</p><p>To summarise, this guide shows you how you can apply basic exploratory data analysis methods using Python on Reddit data. Feel free to test the code or perform further analysis.</p><p><strong>Limitations</strong></p><p>The demographic of reddit and its data may not be completely reflective of the overall sentiment across all online communities.</p><p>Reddit’s ‘karma’ system may incentivise users to ‘farm’ upvotes through posting of popular opinions and discourage negative opinions or views that go against the popular sentiment.</p><p>The sentiment score provided in the original data was labelled using a bot, rather than human methods, thus may not be accurately reflect the comment true sentiment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b63685f82e98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Backtesting a Stochastic, RSI, MACD cryptocurrency trading strategy using Python.]]></title>
            <link>https://medium.com/@boyangchen02/backtesting-a-stochastic-rsi-macd-cryptocurrency-trading-strategy-using-python-9f880abf52e6?source=rss-4442f75e1292------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f880abf52e6</guid>
            <category><![CDATA[backtesting]]></category>
            <category><![CDATA[trading-strategy]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[trading]]></category>
            <dc:creator><![CDATA[Boyang Chen]]></dc:creator>
            <pubDate>Sat, 13 Nov 2021 16:32:49 GMT</pubDate>
            <atom:updated>2021-11-15T10:55:13.798Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey guys, I will be using Python to backtest a highly popular trading strategy shown in Data Trader’s <a href="https://www.youtube.com/watch?v=hh3BKTFE1dc&amp;t=3s">Youtube video</a>. The trading strategy consists of the stochastic, relative strength index (RSI) and moving average convergence divergence (MACD) combination.</p><p>In this particular strategy, the stochastic is used to identify overbought and oversold conditions. Usually when both K% and D% lines go above 75%, this generates an overbought signal. And when both K% and D% lines fall below 25%, this generates an oversold signal. However, a common mistake that many traders make is they rely solely on the stochastic for their buy and sell signals, resulting in a low win rate. Instead, the stochastic should be combined with other indicators to generate a better strategy.</p><p>The second indicator in this strategy is the RSI. The RSI is often used as an overbought/oversold indicator. However, for this combination strategy we already have the stochastic indicator to do that job. Instead, we will use the RSI as a trend confirmation indicator. To put it simply, if the RSI rises above 50, we assume the price trending upwards and we classify this as a buy signal. Conversely, if the RSI falls below 50, we assume the price is trending downwards and therefore we consider this as a sell signal.</p><p>The third indicator in our strategy is the MACD. The MACD is often used as a momentum detector. A common method of using MACD is to take a buy position if the MACD crosses above the signal line and take a sell position if the MACD crosses below the signal line. However, this strategy often gives false signals during sideways markets. Therefore, we will be using MACD with the other two indicators to provide additional confirmation that the momentum is on our side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*TFgWCHxjYNeuFId6ac_X1A.png" /><figcaption>Here is an example showing the combination strategy on BTC-USD data.</figcaption></figure><h3>Backtest the strategy</h3><p><strong>Install and import the libraries</strong></p><p>Simply use pip install or !pip install if you use Jupyter notebook.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d61fb128d65ba5c605c033d7c9e7082/href">https://medium.com/media/6d61fb128d65ba5c605c033d7c9e7082/href</a></iframe><p><strong>Get the Cryptocurrency technical data</strong></p><p>For this data, we will download the price data from yfinance, I will be using 30 minute intervals.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d61fb128d65ba5c605c033d7c9e7082/href">https://medium.com/media/6d61fb128d65ba5c605c033d7c9e7082/href</a></iframe><p>We will then calculate the technical indicators and create columns in the dataframe.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0320aa0802d75d0fec6e95c126f4772f/href">https://medium.com/media/0320aa0802d75d0fec6e95c126f4772f/href</a></iframe><p>Create a function to calculate the stochastic. This function allows to check if the stochastic indicator has met the buy conditions or sell conditions within the specific window (defined by lags).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0320aa0802d75d0fec6e95c126f4772f/href">https://medium.com/media/0320aa0802d75d0fec6e95c126f4772f/href</a></iframe><p>Next we use the function on the original dataframe. If the conditions are met we get a 1, and if not we get a 0. Notice that I used 4 lags here, so if the K% and D% has crossed the thresholds (25% or 75%) in any of the previous 4 rows, the buy or sell conditions are met.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0320aa0802d75d0fec6e95c126f4772f/href">https://medium.com/media/0320aa0802d75d0fec6e95c126f4772f/href</a></iframe><p>Then we create a columns for Buy or Sell depending on if all conditions are met.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0320aa0802d75d0fec6e95c126f4772f/href">https://medium.com/media/0320aa0802d75d0fec6e95c126f4772f/href</a></iframe><p>Now we can create two list: Buying dates and Selling dates. Here, we have a function that checks for the buy signal in the original in the dataframe. If met we append the date to a list. For the sell signal, we check from the buying date when the selling conditions are met.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0320aa0802d75d0fec6e95c126f4772f/href">https://medium.com/media/0320aa0802d75d0fec6e95c126f4772f/href</a></iframe><p>Since we are using the latest data, we may encounter a situation where we have a buying date but no selling date since the selling conditions have not been fulfilled.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0320aa0802d75d0fec6e95c126f4772f/href">https://medium.com/media/0320aa0802d75d0fec6e95c126f4772f/href</a></iframe><pre># convert the lists into a dataframe.<br>frame = pd.DataFrame({&#39;Buying_dates&#39;:Buying_dates, &#39;Selling_dates&#39;: Selling_dates})</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*8ySh9oGK2Lbq73Ct-SnqkQ.png" /></figure><p>Notice that in the dataframe we have overlapping dates. We don’t want to open and new position before we have closed the last one. We can avoid this by specifying that buying date must be greater than the selling date of the previous row.</p><pre>actuals = frame[frame.Buying_dates &gt; frame.Selling_dates.shift(1)]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*9pShVy55SXJJnyhcFEMjog.png" /></figure><h3>Results</h3><p>We then calculate the profits from each trade using the following function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0320aa0802d75d0fec6e95c126f4772f/href">https://medium.com/media/0320aa0802d75d0fec6e95c126f4772f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*9LWbu3p2KEyIHFLz2zQkmQ.png" /></figure><p>Overall we have 6 transactions with a mean returns of 2.43% per trade and a cumulative returns of 15.39%.</p><p>We can visualize the data using matplotlib.pyplot</p><pre>plt.figure(figsize=(20,10))<br>plt.plot(df.Close, color=&#39;k&#39;,alpha=0.7)<br>plt.scatter(actuals.Buying_dates, df.Open[actuals.Buying_dates], marker=&#39;^&#39;, color=&#39;g&#39;, s=500)<br>plt.scatter(actuals.Selling_dates, df.Open[actuals.Selling_dates], marker=&#39;v&#39;, color=&#39;r&#39;, s=500)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TymrXpUqAwIw9AA425Lw4A.png" /></figure><p>As you can see there are several great trades and some bad trades.</p><p>I also backtested this strategy on other cryptocurrencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UawPr8OGkZFcRug-urBfgg.png" /></figure><p>With ETH-USD, we have 5 transactions with a mean returns of 1.16% and cumulative returns of 5.9%.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fg-W7c24wXl_F6HOF7sm6Q.png" /></figure><p>Finally, I’ve tested this strategy with BNB-USD with a mean returns of 1.34% and cumulative returns of 7.3% across the 6 transactions.</p><p><strong>Limitations</strong></p><p>Recently, we are seeing a bullish trend in the crypto markets, which are ideal conditions for the stochastic and RSI indicators. However, I have yet to backtest the strategy in a sideways market, where these indicators may generate a fair amount of false signals.</p><p>In this study, I used 30 minute charts but cryptocurrencies prices are highly volatile and you may observe better results using 15 minute or even 5 minute candles.</p><p>I would not recommend this strategy for cryptocurrencies with low trading volume as the spread between buying and selling prices can be very high.</p><p>Feel free to play around with the settings and optimise the strategy yourself. Here is the link to the <a href="https://github.com/bchen022/Trading_strategies/blob/997d1b97bf667169084220e5acbcc45df258574a/Stochastic_RSI_MACD_strat%20copy.ipynb">Jupyter notebook</a>.</p><p><strong>Disclaimer</strong></p><p>This article is made for entertainment and educational purposes and should not be taken as financial advice. Please do your own research and due diligence before making any financial investments. Cryptocurrency trading carries a huge amount of risk and may result in a total loss of your invested capital.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f880abf52e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google Data Analytics Certificate — Bike Share Case Study]]></title>
            <link>https://medium.com/@boyangchen02/google-data-analytics-certificate-bike-share-case-study-1fd396a1f8e8?source=rss-4442f75e1292------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fd396a1f8e8</guid>
            <category><![CDATA[google-data-analytics]]></category>
            <category><![CDATA[bike-sharing]]></category>
            <category><![CDATA[case-study]]></category>
            <dc:creator><![CDATA[Boyang Chen]]></dc:creator>
            <pubDate>Wed, 06 Oct 2021 19:59:21 GMT</pubDate>
            <atom:updated>2021-10-06T20:01:47.604Z</atom:updated>
            <content:encoded><![CDATA[<h3>Google Data Analytics Certificate — Bike Share Case Study</h3><p><strong>About the company</strong></p><p>In 2016, Cyclistic launched a successful bike-share offering. Since then, the program has grown to a fleet of 5,824 bicycles that are geotracked and locked into a network of 692 stations across Chicago. The bikes can be unlocked from one station and returned to any other station in the system anytime</p><p>Cyclistic’s bike sharing program has three pricing plans: single-ride passes, full-day passes, and annual membership. The flexibility of these pricing plans has boosted the brand awareness and attracted more customers since its introduction.</p><p>Financial analysts concluded annual members are much more profitable than casual riders and conversion of casual rider to annual riders is the key to future growth. In order to do, the marketing analyst team needs to understand how annual members and casual riders differ.</p><p><strong>Scenario</strong></p><p>You are a junior data analyst working in the marketing analyst team at Cyclistic, a bike-share company in Chicago. The director of marketing believes the company’s future success depends on maximizing the number of annual memberships. Therefore, your team wants to understand how casual riders and annual members use Cyclistic bikes differently. From these insights, your team will design a new marketing strategy to convert casual riders into annual members. But first, Cyclistic executives must approve your recommendations, so they must be backed up with compelling data insights and professional data visualizations.</p><p>Moreno has assigned you the first question to answer: How do annual members and casual riders use Cyclistic bikes differently?</p><p><strong>Business Task</strong></p><p>Analysis of casuals riders and annual member’s bike shares usage patterns to inform of marketing strategies for the membership conversion program.</p><p>Tools: R for data cleaning, Microsoft Power Bi for data visualization.</p><p>Dataset: <a href="https://divvy-tripdata.s3.amazonaws.com/index.html">Cyclistic’s historical trip data from April 2020 to April 2021</a></p><p>R code and Output can be found on <a href="https://github.com/bchen022/bchen022.github.io/blob/4a675068b476ff24147a4cc0aceca89874cd9e77/bike_case_study.txt">Github</a></p><p><strong>Results</strong></p><p>Here is what I found from the data:</p><p>1. Total trip duration and number of trips were highest at the weekends and peaked in July.</p><p>2. Total trip duration for casual riders is 1.97 times higher than the total trip duration of members.</p><p>3. Casual riders have a higher average trip duration (31.2 mins) compared to members (14.4 mins).</p><p>4. Total trip duration increased significantly in the afternoon and evening</p><figure><img alt="Dashboard" src="https://cdn-images-1.medium.com/max/602/1*kbeMovint7pmRUg_6gkbCQ.png" /></figure><p>We can see from the bar chart above the majority of bike trips occurred in the summer and they decreased significantly during the winter period.</p><figure><img alt="Day Trend Analysis (Casual)" src="https://cdn-images-1.medium.com/max/472/1*l5pSFhaQwOWJw1Ob715dWQ.png" /></figure><figure><img alt="Day Trend Analysis (Members)" src="https://cdn-images-1.medium.com/max/498/1*otW7J_uSr4jbOiTg_BcE7Q.png" /></figure><p>We can see from the box plots, the total trip duration of casual users is significantly higher on the weekends, whilst the total trip duration of members is constant throughout the week.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*SslqsTq7_b-J1GcYrZcdyA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*VGFtKyWmhsJ86oBfvWaU9A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*v4-5L2Hzl5HndZlOuwp2gA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*h9Al5MakmzjHqGRAdR5XHg.png" /></figure><p><strong>Summary</strong></p><p>In summary, the total trip duration for casual users and members are affected by season. During the winter season, the temperature is low and people are less likely to go outside. Those that require to commute to work most likely will use other forms of public transport. Consequently, the total trip duration is the lowest during the winter season.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*mSwpLzjYTnIdlRjr5SrvxQ.png" /></figure><p>Throughout the year, we see a sharp increase in the total trip duration in the afternoon and evenings at around 5 p.m. Many schools finish in the afternoon and many workers finished around 5 p.m, thus this could explain the increase in trip duration around this time. This is further substantiated by the two peaks observed for annual members which is at 7 a.m and 5 p.m, this mostly likely indicates many annual members are office workers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/1*bJF3GJnivOeFAIz7e2gPpg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*WAmZSExbD2w2eqM9MW3soQ.png" /></figure><p>The top 20 stations visited by casual bikes users are popular tourist locations in Chicago, thus casual users are mostly likely are tourists, family, couples and students. Whereas, annual members visit various stations around the city evenly.</p><p>Based on the data analysis, my suggestion would be to launch the new marketing campaign during the summer season and consider introducing seasonal passes to capture the tourists, students and summer vacation customers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fd396a1f8e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>