<?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 Amy Zhuang on Medium]]></title>
        <description><![CDATA[Stories by Amy Zhuang on Medium]]></description>
        <link>https://medium.com/@amzhuang_52800?source=rss-be64482f9ed6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Amy Zhuang on Medium</title>
            <link>https://medium.com/@amzhuang_52800?source=rss-be64482f9ed6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 15:31:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amzhuang_52800/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[Putting Neural Network Models into Production]]></title>
            <link>https://medium.com/@amzhuang_52800/putting-neural-network-models-into-production-adcc002a6498?source=rss-be64482f9ed6------2</link>
            <guid isPermaLink="false">https://medium.com/p/adcc002a6498</guid>
            <category><![CDATA[deploy-model]]></category>
            <category><![CDATA[production]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[predictive-modeling]]></category>
            <dc:creator><![CDATA[Amy Zhuang]]></dc:creator>
            <pubDate>Mon, 25 Mar 2019 12:44:34 GMT</pubDate>
            <atom:updated>2019-03-25T12:44:34.625Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Qj0q2MDfQjYlecDa" /><figcaption>Photo by <a href="https://unsplash.com/@timmossholder?utm_source=medium&amp;utm_medium=referral">Tim Mossholder</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the article “Introduction to Neural Network Model”, we explored the titanic dataset and built a neural network model to predict the probability of survival. Now that we already have a predictive model with decent performance available, what’s the next step? How can we utilize the model and make predictions? In this article, we will talk about how to use the neural network model to make predictions for new data.</p><p>Putting a neural network model (and most machine learning models) into production involves the following steps:</p><p>· Step 1: Save the finalized model after model training and tuning.</p><p>· Step 2: Process the new data so that the format is the same as the modeling dataset.</p><p>· Step 3: When we would like to make prediction (usually after a while since the model is built), load the saved model.</p><p>· Step 4: Use the loaded model to make prediction.</p><p>· Step 5: Productionize the process</p><p>Now let’s go into details for each step.</p><p><strong>Step 1: Save the finalized model after model training and tuning</strong></p><p>Let’s refresh our memory about the neural network model we built using Tatanic data.</p><pre># Import Python packages<br>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>%matplotlib inline</pre><pre>from sklearn.preprocessing import StandardScaler<br>from sklearn.externals import joblib<br>from sklearn.metrics import accuracy_score, classification_report, confusion_matrix<br>from sklearn import cross_validation<br>from keras.models import Sequential<br>from keras.layers import Dense<br>from keras.models import model_from_json</pre><pre># Create model<br>nn_model=Sequential()<br>nn_model.add(Dense(5,input_dim=11,activation=&#39;relu&#39;))<br>nn_model.add(Dense(1,activation=&#39;sigmoid&#39;))</pre><pre>#Compile model<br>nn_model.compile(loss=&#39;binary_crossentropy&#39;,optimizer=&#39;adam&#39;,metrics=[&#39;accuracy&#39;])</pre><pre>#Fit the model<br>nn_model.fit(X_train,y_train, epochs=150,batch_size=100,verbose=0)</pre><p>We created, compiled, and fit a neural network classification model to predict survival using Keras. Keras has the functionality of saving neural network model to local drive for future use. There are two options of saving a neural network model.</p><p>The first option is to save the model structure and weights separately. The model structure is saved as json file using to_json(), and the model weights are saved in hdf5 format using save_weights. The code below shows how to save the model structure and weights separately.</p><pre># Serialize model to JSON<br>nn_model_json=nn_model.to_json()<br>with open(“nn_model.json”,”w”) as json_file:<br> json_file.write(nn_model_json)</pre><pre># Serialize weights to HDF5<br>nn_model.save_weights(“nn_model.h5”)<br>print(“Saved nn_model to disk”)</pre><p>The second option is to save the model in one file using .save(). Both the model structure and the weights are saved in the same HDF5 file in this case.</p><pre># creates a HDF5 file ‘my_model.h5’<br>nn_model.save(‘nn_model_all.h5’)</pre><p><strong>Step 2: Process the new data so that the format is the same as the modeling dataset.</strong></p><p>We will use the Titanic data we processed in the article “Introduction to Neural Network Model” and pretend it to be new data for illustration purpose only. In the case that new data is available, the same data processing steps need to be followed.</p><p><strong>Step 3: Load the saved model for new data prediction</strong></p><p>If the model structure and weights were saved separately, we can use the following code to load the model:</p><pre>#load the saved model <br>from keras.models import model_from_json<br>json_file=open(r’nn_model.json’,’r’)<br>loaded_nn_model_json=json_file.read()<br>json_file.close()<br>loaded_nn_model=model_from_json(loaded_nn_model_json)</pre><pre>#load weight into classification model<br>loaded_nn_model.load_weights(r&quot;nn_model.h5&quot;)</pre><p>If the model structure and weights were saved together, we use the following code to load the model:</p><pre>from keras.models import load_model<br>loaded_nn_model_all = load_model(‘nn_model_all.h5’)</pre><p>After loading the neural network model, the next steps are all the same, so we will use loaded_nn_model to illustrate the process, but the process for loaded_nn_model_all will be exactly the same.</p><p><strong>Step 4: Use the loaded model to make prediction</strong></p><p>After putting the new data into desired format (step2) and loading the neural network model (step3), we are ready to make predictions.</p><pre># Make classification predictions<br>y_predict=loaded_nn_model.predict_classes(X)<br># Predicted probability<br>y_pred_prob=loaded_nn_model.predict_proba(X)</pre><p>We can get the predicted classes (survived) directly using predict_classes() or get the probability of survival using predict_proba(). predict_classes() produces the output of 0 and 1 for each record, where 0 represents non-survival and 1 represents survival. predict_proba() produces the output of a continuous number between 0 and 1. The closer the number is to 1, the more likely the passenger will survive. On the other hand, the closer the number is to 0, the less likely the passenger will survive.</p><p>The default is to use the probability of 0.5 as the cutoff point. If the predicted probability is above 0.5, the model predict 1 (survival), and if the predicted probability is below 0.5, the model predict 0 (non-survival). But this cutoff point can be adjusted manually based on data and project needs.</p><p>It is usually a good idea to check the distribution of predicted values and see if the results make sense.</p><pre># Predicted percent of survival<br>y_predict.mean()</pre><p>Since we have binary predicted output, the mean() will give us the percentage of passengers that are predicted to survive by the model. This percentage needs to be compared with the survival rate in the modeling dataset. We expected they are very close to each other, otherwise, the cutoff point for the predicted probability needs to be adjusted.</p><pre># Distribution of predicted probability<br>prob=pd.DataFrame(y_pred_prob)<br>prob.columns=[‘y_pred_prob’]<br>prob.describe()</pre><p>The code above give the distribution of predicted probability. You can confirm if the probability is between 0 and 1, and use the code below to create a distribution chart.</p><pre># this is to plot the kde<br>import seaborn as sns<br>sns.kdeplot(prob[‘y_pred_prob’],label=’Probability of Survival’);<br># add labels<br>import matplotlib.pyplot as plt<br>plt.xlabel(‘Predicted Probability’)<br>plt.ylabel(‘Density’)<br>plt.show()</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adcc002a6498" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Neural Networks Model]]></title>
            <link>https://medium.com/@amzhuang_52800/introduction-to-neural-networks-model-c04c7d04812a?source=rss-be64482f9ed6------2</link>
            <guid isPermaLink="false">https://medium.com/p/c04c7d04812a</guid>
            <category><![CDATA[predictive-modeling]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Amy Zhuang]]></dc:creator>
            <pubDate>Mon, 18 Mar 2019 14:55:01 GMT</pubDate>
            <atom:updated>2019-03-18T14:55:01.173Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CMoMvqkZySAZX1gR" /><figcaption>Photo by <a href="https://unsplash.com/@yogesh_7?utm_source=medium&amp;utm_medium=referral">Yogesh Pedamkar</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What are Neural Network Models?</h3><p>Neural Network models, also called Artificial Neural Network (ANN) models, are a type of machine learning model that is inspired by human brain.</p><p>Neural Network models typically contain multiple layers. Each layer contains multiple nodes that are called neurons. There are three types of layers: input, hidden, and output. Input layers take in features/predictors and passes to the hidden layer(s). Output layers compute information and provide predictions. A hidden layer exists between the input layer and output layer. Neural Network models can have zero, one, or multiple hidden layers, where the input information is processed and delivered to the output layer.</p><p>There are numerous python packages implementing neural network modeling. Tensorflow is the most popular one. Keras is built on top of Tensorflow and is more user friendly. In this article, we will use Keras to build a simple classification model.</p><h3>Data for the exercise</h3><p>We will use the Titanic data for this exercise. The table below has the variable list and description.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*kFLz59ce_naiBe1uUba6cw.png" /><figcaption>Titanic Data</figcaption></figure><h3>Read in Data</h3><p>We will first import the libraries needed and read in data.</p><pre># Import Python packages<br>import pandas as pd<br>import numpy as np<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.metrics import accuracy_score, classification_report, confusion_matrix<br>from sklearn import cross_validation<br>from keras.models import Sequential<br>from keras.layers import Dense</pre><pre># Readin Data<br>df = pd.read_excel(open(&#39;titanic.xlsx&#39;,&#39;rb&#39;), sheet_name=&#39;titanic3&#39;)<br>df.head()</pre><p>Then we get some basic information about this dataset.</p><pre>df.info()<br>df[&#39;survived&#39;].value_counts()</pre><p>We can see that there several variables with missing values. Since the focus of this exercise is neural network model, we will delete those variables to quickly build a modeling dataset. But in a real project, we may want to explore ways to do missing imputation and check if that helps with the prediction accuracy. There are also some observation identifier variables that do not have strong predictive power (e.g. ticket number). We will drop those variables as well.</p><pre># Drop the variables with a lot of missing values and name, ticket<br>df=df.drop([&#39;cabin&#39;,&#39;boat&#39;,&#39;body&#39;,&#39;home.dest&#39;, &#39;name&#39;,&#39;ticket&#39;],axis=1)<br>df.head()<br># Drop records with missing values<br>df = df.dropna()<br>df.info()</pre><h3>Data pre-processing</h3><p>This gives us the universe for the modeling dataset. The next step is to do data pre-processing and change all the categorical variables to flags.</p><pre># Check the number of categories in pclass: There are 3<br>df[&#39;pclass&#39;].value_counts()<br># Check the number of categories in sibsp: There are 7. Will regroup to 3<br>df[&#39;sibsp&#39;].value_counts()<br>df[&#39;sibsp_cat&#39;]=df[&#39;sibsp&#39;].apply(lambda x: 2 if x&gt;=2 else x)<br>df[&#39;sibsp_cat&#39;].value_counts()<br># Check the number of categories in parch: There are 7.  Will regroup to 3<br>df[&#39;parch&#39;].value_counts()<br>df[&#39;parch_cat&#39;]=df[&#39;parch&#39;].apply(lambda x: 2 if x&gt;=2 else x)<br>df[&#39;parch_cat&#39;].value_counts()<br># Check the number of categories in embarked: There are 3<br>df[&#39;embarked&#39;].value_counts()<br># Drop the variables for sibsp and parch before regroup<br>df=df.drop([&#39;sibsp&#39;,&#39;parch&#39;],axis=1)</pre><p>The function below change the categorical variables to dummy variables and delete the original categorical variables from the dataframe.</p><pre># A function to create dummy variables<br>def create_dummies(df,colname):<br>    col_dummies=pd.get_dummies(df[colname],prefix=colname)<br>    col_dummies.drop(col_dummies.columns[0],axis=1,inplace=True)<br>    df=pd.concat([df,col_dummies],axis=1)<br>    df.drop(colname,axis=1,inplace=True)<br>    return df<br># Create a list for the categorical variables<br>col_list=[&#39;pclass&#39;,&#39;sex&#39;,&#39;embarked&#39;,&#39;sibsp_cat&#39;,&#39;parch_cat&#39;]<br># Apply the function to the list<br>for i in range(len(col_list)):<br>    df=create_dummies(df,col_list[i])<br>df.head()</pre><h3>Train test split</h3><p>After creating the categorical variables, all the columns in the dataframe are numeric. We drop the dependent variable ‘survived’ and create a dataframe for the features/predicters. A standard scaler is applied to bring the variables to the same scale. We then split the data into 80% training ad 20% validation.</p><pre>X_features=df.drop([&#39;survived&#39;],axis=1)<br>sc = StandardScaler()<br>X = pd.DataFrame(sc.fit_transform(X_features),index=X_features.index,columns=X_features.columns)<br>y=df[&#39;survived&#39;]<br>X_train, X_test, y_train, y_test = cross_validation.train_test_split(X,y,test_size=0.2)</pre><h3>Fit the neural network model</h3><p>Now that dataset is ready, we will use Keras to create a model.</p><pre># Create model<br>nn_model=Sequential()<br>nn_model.add(Dense(5,input_dim=11,activation=&#39;relu&#39;))<br>nn_model.add(Dense(1,activation=&#39;sigmoid&#39;))</pre><p>The Keras sequential model is a linear stack of layers. Layers can be added using .add() method. The class Dense helps implement the add operation. The parameter input_dim has the number of features for the model.</p><p>Activation function is used to convert the input information of a neuron into the output. The output is then used as the inputs for the next layer. The most commonly used activation functions are sigmoid, tanh, relu, and linear. Sigmoid function has the form of <em>f(x)=1/1+e^(-x)</em> and has the range of 0 to 1. Tanh function has similar shape as the sigmoid function, but the range is from -1 to 1. Tanh has the function form of <em>tanh(x)=2sigmoid(2x)-1</em>. Relu function has the form of <em>f(x)=max(0,x)</em> and has the range of 0 to infinity. Relu is the most popular activation function.</p><p>For the first layer, we have 5 neurons and relu as the activation function. For the output layer, we have 1 neuron and sigmoid as the activation function. Sigmoid function is commonly used for binary prediction.</p><pre>#Compile model<br>nn_model.compile(loss=&#39;binary_crossentropy&#39;,optimizer=&#39;adam&#39;,metrics=[&#39;accuracy&#39;])</pre><p>Before training the model, we use the compile method to configure the learning process.</p><p>Loss function is one required arguments. It measures the difference between the predicted value and the actual value. A loss function is the objective that the model will try to minimize. Cross-entropy is commonly used for classification.</p><p>An optimizer is another argument required for compiling a Keras model. It helps to adjust the weights and find the weights that minimize the error term. Gradient decent is the foundation of the optimization algorithm. Stochastic Gradient Decent (SGD), AdaDelta, AdaGrad, RMSProp, and Adam are among the popular optimizers.</p><p>How do we know which optimizer to use? Generally speaking, a newer optimizer is better than the older ones because of the algorithms in the newer optimizer usually correct some limitations in the older optimizers. Adam is currently the most popular optimizer to use.</p><p>Accuracy is the metric for classification models. It measures the percentage of correct predictions.</p><pre>#Fit the model<br>nn_model.fit(X_train,y_train, epochs=150,batch_size=100,verbose=0)</pre><p>Keras models are trained on Numpy arrays of input data and labels. For training our Titanic survival model, we will use the fit function. An epoch is a single pass through the whole training dataset. We set the epochs number to be 150, which means that the modeling dataset run through the training process 150 times to update the model weights. Batch_size is the number of training records in one pass. The higher the batch size, the more memory space is needed. We have 834 records in the training dataset. A batch_size of 100 gives us 8 groups with 100 records and 1 group with 34 records. It takes 9 iterations to complete 1 epoch.</p><h3>Model prediction and cross evaluation</h3><pre>#Make prediction<br>y_test_predict=nn_model.predict_classes(X_test)<br>print (accuracy_score(y_test,y_test_predict))</pre><p>After fitting the model, we fed X_test into the model and made predictions. The accuracy_score gives out the percent of correct predictions.</p><pre>#Confusion matrix<br>unique_label = np.unique(y_test)<br>print(pd.DataFrame(confusion_matrix(y_test, y_test_predict, labels=unique_label), <br>                   index=[&#39;true:{:}&#39;.format(x) for x in unique_label], <br>                   columns=[&#39;pred:{:}&#39;.format(x) for x in unique_label]))</pre><p>A confusion matrix also describe the predictive accuracy of a classification model. It is a table with counts of correct and incorrect predictions for each class. The percentage of correct predictions from confusion matrix should match the number will get from the accuracy_score</p><h3>Reference</h3><p><a href="https://keras.io/">https://keras.io/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Qhp9HylQO3aaCn7-" /><figcaption>Photo by <a href="https://unsplash.com/@diesektion?utm_source=medium&amp;utm_medium=referral">Robert Anasch</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c04c7d04812a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>