<?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[Python experiments - Medium]]></title>
        <description><![CDATA[To share learning points from our Python experiments - Medium]]></description>
        <link>https://medium.com/python-experiments?source=rss----5c34e9b6bd69---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Python experiments - Medium</title>
            <link>https://medium.com/python-experiments?source=rss----5c34e9b6bd69---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 21:34:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/python-experiments" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Simple Linear Regression — OLS vs Mini-batch Gradient Descent (Python)]]></title>
            <link>https://medium.com/python-experiments/simple-linear-regression-ols-vs-mini-batch-gradient-descent-python-deb5e83d9fa?source=rss----5c34e9b6bd69---4</link>
            <guid isPermaLink="false">https://medium.com/p/deb5e83d9fa</guid>
            <category><![CDATA[ordinary-least-square]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[mini-batch]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <dc:creator><![CDATA[LU ZOU]]></dc:creator>
            <pubDate>Thu, 28 Feb 2019 10:05:43 GMT</pubDate>
            <atom:updated>2019-02-28T10:05:43.576Z</atom:updated>
            <content:encoded><![CDATA[<h3>Simple Linear Regression — OLS vs Mini-batch Gradient Descent (Python)</h3><h3>Motivation</h3><p>It started with the discussion on the linear regression between a traditional statistician (me) and a computer scientist/mathematician. The question is simple but interesting….</p><p>Two approaches to fit a linear regression model are:</p><ol><li>Ordinary Least Squares (OLS) (an analytical method)</li><li>Mini-batch gradient descent (GD) (a numerical method)</li></ol><p><strong>Will these two approaches return the same fitted line given the same data and model, almost the same loss/error function?</strong></p><p>The mathematical/theoretical differences are described in this blog: <a href="https://towardsdatascience.com/linear-regression-simplified-ordinary-least-square-vs-gradient-descent-48145de2cf76">Linear Regression Simplified — Ordinary Least Square vs Gradient Descent</a>. There are three common ways to batch the data for GD:</p><ol><li>All data in one batch (Batch Gradient Descent)</li><li>One observation per batch (Stochastic Gradient Descent)</li><li>Subset observations per batch (Mini-batch Gradient Descent)</li></ol><p>The blog focus on the mini-batch GD which lies between batch GD and stochastic GD. I will try to show the differences in practice.</p><h3>Generate data (small data size)</h3><p>An artificial data set of 10 points is generated with an intercept of <strong>6</strong>, a slope of 1, and residuals sampled from the standard normal distribution.</p><pre>random.seed(999)<br>x = np.random.normal(size=10) <br>y = x+ 6 +np.random.normal(size=10)</pre><p>The data looks like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*PpU7P27Xg2FyQS1B1P4HUw.png" /></figure><p>For simplicity, I will use the simple linear regression (uni-variate linear regression) with intercept term.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/1*8Rm7ek4OLbJ13V7a9tGXAA.png" /></figure><p>When batching the data, I use a batch size of <strong>2</strong>, which always determines a line without residual within each batch. This makes things easier in later investigations.</p><h3>OLS approach</h3><p>The OLS estimate the slope 𝛽 and intercept 𝛼 of the straight line by minimizing the sum of squared residuals (SSE).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*y-LRgpDIzNXNx0BBovvZ0g.png" /></figure><p>From the SSE, we can derive the estimates of 𝛽 and 𝛼 as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*457Or2mdZQRCeeQN1DLsZg.png" /></figure><p>This uses all the data in one go and one iteration. This can be implemented by the Python module sk<a href="https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html">learn.linear_model.LinearRegression()</a>.</p><blockquote><strong>The estimate of intercept </strong>𝛼̂ <strong>is 6.089, and the estimate of slope </strong>𝛽̂ <strong>is 0.767 using OLS.</strong></blockquote><pre>lm = linear_model.LinearRegression()<br>lm.fit(x.reshape(-1,1), y)</pre><h3>Gradient descent approach</h3><p>Similar to OLS, Gradient descent approach aims to minimize a cost function by iterations. The cost function for the simple linear regression is equivalent to the average of squared residuals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*xGe4JKlSDK0XnUaIXcbDfg.png" /></figure><p>where <em>m</em> is the batch size. The partial derivatives of the cost function represent the change of the corresponding parameters. In the case of simple linear regression, the partial derivatives of 𝛼 and 𝛽 are as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*EeXRw7hpP1-UjLWt9ILoww.png" /></figure><p>After each batch, the estimates of 𝛼 and 𝛽 are updated as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*qjiDfveXIVDRcrGme_t-Uw.png" /></figure><p>where 𝛾 is the learning rate. <strong>When the learning rate is zero, GD will learn nothing. While the learning rate has no upper limit, the larger it is, the more GD learns from the latest batch.</strong></p><h4>Define functions</h4><p>Here is the function I use to batch the data.</p><pre>def batch_data(num, data, labels, shuffle=True):<br>    idx = np.arange(0 , len(data))<br>    if shuffle:<br>        np.random.shuffle(idx)<br>    ind = np.array(range(1,len(data)+1))<br>    b_ends = ind[ind%num==0]</pre><pre>    x_batched = []<br>    y_batched = []<br>    for i in b_ends:<br>        data_batch = data[idx[(i-num):i]] <br>        labels_batch = labels[idx[(i-num):i] ]<br>        x_batched.append(data_batch)<br>        y_batched.append(labels_batch)<br>    return x_batched, y_batched</pre><p>GD model is defined as follows:</p><pre>X = tf.placeholder(&quot;float&quot;) <br>Y = tf.placeholder(&quot;float&quot;)</pre><pre>W = tf.Variable(np.random.randn(), name = &quot;W&quot;) <br>b = tf.Variable(np.random.randn(), name = &quot;b&quot;)</pre><pre>y_pred  = tf.add(tf.multiply(X, W), b)<br># Mean Squared Error Cost Function<br>cost = tf.reduce_sum(tf.pow(y_pred-Y, 2)) / (2 * tf.to_float(tf.size(y_pred)))</pre><pre># Global Variables Initializer <br>init = tf.global_variables_initializer()</pre><pre>#####################run the model#################################</pre><pre>def run_GD(lr_choices, n_batches, n_epochs):</pre><pre>    lr_ls = []<br>    epoch_ls = []<br>    batch_ls = []<br>    cost_ls = []<br>    beta_ls = []<br>    alpha_ls = []<br>    <br>    for lr in lr_choices:<br>        # Gradient Descent Optimizer <br>        optimizer =                  tf.train.GradientDescentOptimizer(lr).minimize(cost)</pre><pre>with tf.Session() as sess:</pre><pre># Initializing the Variables <br>            sess.run(init)</pre><pre>            for epoch in range(n_epochs):</pre><pre>               x_b, y_b = batch_data(int(len(x)/n_batches),x,y, shuffle=False)</pre><pre># Iterating through all the epochs <br>                  for btch in range(n_batches): <br>                     lr_ls.append(lr)<br>                     epoch_ls.append(epoch)<br>                     batch_ls.append(btch)</pre><pre># Feeding each data point into the optimizer using Feed Dictionary <br>                     sess.run(optimizer, feed_dict = {X : x_b[btch], Y : y_b[btch]})</pre><pre>                     cost_ls.append(sess.run(cost, feed_dict = {X : x_b[btch], Y : y_b[btch]}) )<br>                     beta_ls.append(sess.run(W) )<br>                     alpha_ls.append(sess.run(b))<br>    return pd.DataFrame({&#39;learning_rate&#39;: lr_ls,<br>                       &#39;epoch&#39;: epoch_ls,<br>                       &#39;batch&#39;: batch_ls,<br>                       &#39;cost&#39;: cost_ls,<br>                       &#39;beta&#39;: beta_ls,<br>                       &#39;intercept&#39;: alpha_ls})</pre><h3>Batch GD</h3><p>Applying the batch GD converges to the same estimates as OLS if the learning rate falls within a reasonable range and the GD runs through enough epochs.</p><p>This is not surprising; each epoch the GD learns the whole information, thus eventually pushing the estimates from the initialized values to the OLS ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*ZFB0KgEzWLPXQvK0mf7s_A.png" /><figcaption>Batch Gradient Descent</figcaption></figure><h3>Mini-batch GD</h3><p>The mini-batch GD goes through the batches in the same order 50 times (50 epochs, no shuffling) using different learning rates. The 10 data points are split into 5 batches with the order kept fixed, so that it is easier to track the convergence behavior.</p><p>It’s obvious that a learning rate of 1 is over-shooting, not converging.</p><p>When the learning rate is right, the results of mini-batch GD are very close to OLS estimates.</p><p>Because the batches are not shuffled, the final estimates at every epoch are shifted by the last batch; this repeated pattern is clearly shown in the right plot when learning rate is 0.9.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*DSzyfSJajdlrToE3hnj0rw.png" /><figcaption>mini-batch GD convergence</figcaption></figure><p>Look at the final estimates of 50th epoch, different learning rates reached different results and differ from the OLS estimates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*B7PBYxMeiISs5fPVE_rLqQ.png" /></figure><p>The following plots compare the estimates against OLS estimates at epoch 0, 1, 2, 3, 4, and 10, excluding learning rate of 1 (diverged). The learning rate of 0.1 seems a conservative choice, but <strong>does mini-batch GD converge at this learning rate?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*qqoM_2vH3ZaHxCnYHkw0BQ.png" /></figure><p>Although learning rate of 0.1 gave fairly good estimates using 50 epochs, but the estimate of slope didn’t converge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*h5dyfCNJQJs1-L5tPZStAA.png" /><figcaption>mini-batch GD lr=0.1</figcaption></figure><h3>mini-batch GD vs OLS per batch</h3><p>To better understand the mini-batch GD process, I did the following experiment:</p><ul><li>Fit a line per batch using OLS</li><li>Fit the GD with 50 epochs (shuffling batches, learning rate 0.4)</li></ul><p>Compare the slope and intercept estimates of 5 batches to those from OLS for each epoch.</p><p>The graph below plots the estimates of intercept against slope of 5 batches by OLS fittings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*4GDuTbDrqP6TLbFePi5qqw.png" /></figure><p>The initialized values of slope and intercept start outside of the OLS estimates, and quickly move inside and wander around the average of OLS estimates. Smaller learning rate narrows the wandering area. This makes sense because each batch carries partial information.</p><p>Because of the small size of the data, mini-batch GD doesn’t reach the convergence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fug4IDC6gKT-kE3qzzHYRg.png" /></figure><h3>Summary</h3><p>This blog is not to show one approach is better than the other. I hope it could help understanding the differences between these two methods in a practical way.</p><p><strong>OLS </strong>is easy and fast if the data is not big.</p><p><strong>Mini-batch GD</strong> is beneficial when the data is big and memory is limited. Using this approach, the learning rate choice and batch size are important. We should always check the convergence, even the final estimates look good.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=deb5e83d9fa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/python-experiments/simple-linear-regression-ols-vs-mini-batch-gradient-descent-python-deb5e83d9fa">Simple Linear Regression — OLS vs Mini-batch Gradient Descent (Python)</a> was originally published in <a href="https://medium.com/python-experiments">Python experiments</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bayesian CNN model on MNIST data using Tensorflow-probability (compared to CNN)]]></title>
            <link>https://medium.com/python-experiments/bayesian-cnn-model-on-mnist-data-using-tensorflow-probability-compared-to-cnn-82d56a298f45?source=rss----5c34e9b6bd69---4</link>
            <guid isPermaLink="false">https://medium.com/p/82d56a298f45</guid>
            <category><![CDATA[tensorflow-probability]]></category>
            <category><![CDATA[convolution-neural-net]]></category>
            <category><![CDATA[bayesian-neural-network]]></category>
            <dc:creator><![CDATA[LU ZOU]]></dc:creator>
            <pubDate>Tue, 29 Jan 2019 09:54:16 GMT</pubDate>
            <atom:updated>2019-01-29T09:48:16.408Z</atom:updated>
            <content:encoded><![CDATA[<h3>Motivation</h3><p>I’ve been recently reading about the Bayesian neural network (BNN) where traditional backpropagation is replaced by Bayes by Backprop. This was introduced by <a href="https://arxiv.org/abs/1505.05424">Blundell et al (2015)</a> and then adopted by many researchers in recent years. Instead of point estimate of weights, BNN approximates the distribution of weights, commonly a Gaussian/normal distribution with two hyperparameters (mean and standard deviation), based on prior information and data. The prediction uses the posterior distribution of weights. The backpropagation is to update the hyperparameters of the weights. This way, the model can provide uncertainty estimates of the weights and predictions.</p><p>BNN can be integrated into any neural network models, but here I’m interested in its application on convolutional neural networks (CNN).</p><p>So far, there are several existing packages in Python that implement Bayesian CNN. For example, <a href="https://arxiv.org/pdf/1806.05978.pdf">Shridhar et al 2018</a> used Pytorch (also see their <a href="https://medium.com/neuralspace">blogs</a>), <a href="https://twiecki.io/blog/2016/06/01/bayesian-deep-learning/">Thomas Wiecki 2017</a> used PyMC3, and <a href="https://arxiv.org/abs/1610.09787">Tran et al 2016</a> introduced the package Edward and then merged into TensorFlow Probability (<a href="https://arxiv.org/abs/1812.03973">Tran et al 2018</a>).</p><p>This blog will use TensorFlow Probability to implement Bayesian CNN and compare it to regular CNN, using the famous MNIST data. The human accuracy on the MNIST data is about <a href="https://papers.nips.cc/paper/656-efficient-pattern-recognition-using-a-new-transformation-distance.pdf">97.5% — 98%</a>. A single node neural network model will be used as the baseline model.</p><pre>from __future__ import absolute_import<br>from __future__ import division<br>from __future__ import print_function</pre><pre>import os<br>import warnings<br># warnings.simplefilter(action=&quot;ignore&quot;)<br>warnings.filterwarnings(&#39;ignore&#39;)<br>os.environ[&#39;TF_CPP_MIN_LOG_LEVEL&#39;] = &#39;3&#39;</pre><pre>import matplotlib.pyplot as plt<br>from matplotlib import figure <br>from matplotlib.backends import backend_agg<br>import seaborn as sns<br>from tensorflow.examples.tutorials.mnist import input_data<br>import tensorflow as tf<br>import numpy as np<br>tf.logging.set_verbosity(tf.logging.ERROR)</pre><pre># Dependency imports<br>import matplotlib<br>import tensorflow_probability as tfp</pre><pre>matplotlib.use(&quot;Agg&quot;)<br>%matplotlib inline</pre><h3>Import data</h3><p>Tensorflow’s built-in MNIST API saves you a lot of effort on manipulating the MNIST data, so that you can focus on model development. It allows you to import the data with different shapes and one-hot encoded labels, to easily select batches, and the images have been normalized.</p><p>The MNIST data are imported here in three versions:</p><ol><li>images reshaped to 784(28*28) vector, labels one-hot coded</li><li>images not reshaped (28<em>28</em>1 images), labels not one-hot coded (integers 1–9)</li><li>images not reshaped, labels one-hot coded.</li></ol><pre>mnist_onehot = input_data.read_data_sets(data_dir, one_hot=True)<br>mnist_conv = input_data.read_data_sets(data_dir,reshape=False ,one_hot=False)<br>mnist_conv_onehot = input_data.read_data_sets(data_dir,reshape=False ,one_hot=True)</pre><pre># display an image<br>img_no = 485<br>one_image = mnist_conv_onehot.train.images[img_no].reshape(28,28)<br>plt.imshow(one_image, cmap=&#39;gist_gray&#39;)</pre><pre>print(&#39;Image label: {}&#39;.format(np.argmax(mnist_conv_onehot.train.labels[img_no])))</pre><p>Image label: 6</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/1*VhxYhg9JTIDNen37RkhpMA.png" /></figure><h3>Baseline model</h3><p>As a baseline model, a neural network with one hidden layer of a single node is built. This is equivalent to a <a href="https://en.wikipedia.org/wiki/Multinomial_logistic_regression">multinomial logistic regression</a> model. The model flattens the image, ignoring the connections between neighboring pixels in the image.</p><p>The baseline model actually does a good job reaching around 91–93% accuracy.</p><p>Codes are from Udemy course <a href="https://www.udemy.com/complete-guide-to-tensorflow-for-deep-learning-with-python/learn/v4/content">“Complete Guide to Tensorflow for Deep Learning with Python”</a>.</p><pre># define placeholders<br>x = tf.placeholder(tf.float32, shape=[None, 28*28])<br>y_true = tf.placeholder(tf.float32, shape=[None, 10])</pre><pre># define variables: weights and bias<br>W = tf.Variable(tf.zeros([28*28, 10]))<br>b = tf.Variable(tf.zeros([10]))</pre><pre># create graph operations<br>y = tf.matmul(x,W)+b</pre><pre># define loss function<br>cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_true, logits=y))</pre><pre># define optimizer<br>optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.5)<br>train=optimizer.minimize(cross_entropy)</pre><pre># create session<br>epochs = 5000<br>init = tf.global_variables_initializer()<br>with tf.Session() as sess:<br>    sess.run(init)<br>    for step in range(epochs):<br>        batch_x, batch_y = mnist_onehot.train.next_batch(50)<br>        sess.run(train, feed_dict={x:batch_x, y_true:batch_y})<br>    <br>    #EVALUATION<br>    correct_preds = tf.equal(tf.argmax(y,1), tf.argmax(y_true, 1))<br>    acc = tf.reduce_mean(tf.cast(correct_preds, tf.float32))<br>    <br>    print(&#39;Accuracy on test set: {}&#39;.format(<br>        sess.run(acc, feed_dict={x: mnist_onehot.test.images, y_true: mnist_onehot.test.labels})))</pre><blockquote>Accuracy on test set: 0.9124000072479248</blockquote><h3>CNN model</h3><p>The CNN model is a simple version of the following:</p><ol><li>Convolutional layer (32 kernels)</li><li>Max pooling</li><li>Convolutional layer (64 kernels)</li><li>Max pooling</li><li>Flattening layer</li><li>Fully connected layer (1024 output units)</li><li>Dropout layer (50% dropping rate)</li><li>Fully connected layer (10 output units, one for each digit)</li></ol><p>The number of kernels, dropping out rate, and output units are arbitrary here, without any parameter tuning. After 5000 batches, the model accuracy reached 99%, overtaking human accuracy.</p><pre>x = tf.placeholder(tf.float32,shape=[None,28,28,1])<br>y_true = tf.placeholder(tf.float32,shape=[None,10])<br>hold_prob = tf.placeholder(tf.float32)</pre><pre>cnn = tf.keras.Sequential()<br>cnn.add(tf.keras.layers.Conv2D(32, kernel_size=5, padding=&#39;SAME&#39;, activation=tf.nn.relu))<br>cnn.add(tf.keras.layers.MaxPooling2D(pool_size=[2, 2], strides=[2, 2], padding=&quot;SAME&quot;))<br>cnn.add(tf.keras.layers.Conv2D(64, kernel_size=5, padding=&#39;SAME&#39;, activation=tf.nn.relu))<br>cnn.add(tf.keras.layers.MaxPooling2D(pool_size=[2, 2], strides=[2, 2], padding=&quot;SAME&quot;))<br>cnn.add(tf.keras.layers.Flatten())<br>cnn.add(tf.keras.layers.Dense(1024, activation=tf.nn.relu))<br>cnn.add(tf.keras.layers.Dropout(hold_prob))<br>cnn.add(tf.keras.layers.Dense(10))</pre><pre>y_pred = cnn(x)</pre><pre>cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_true,logits=y_pred))<br>optimizer = tf.train.AdamOptimizer(learning_rate=0.0001)<br>train = optimizer.minimize(cross_entropy)</pre><pre>steps = 5000<br>init = tf.global_variables_initializer()</pre><pre>with tf.Session() as sess:<br>    sess.run(init)<br>    <br>    for i in range(steps+1):<br>        batch_x , batch_y = mnist_conv_onehot.train.next_batch(50)<br>        sess.run(train,feed_dict={x:batch_x,y_true:batch_y,hold_prob:0.5})<br>        <br>        # PRINT OUT A MESSAGE EVERY 100 STEPS<br>        if i%500 == 0:<br>            matches = tf.equal(tf.argmax(y_pred,1),tf.argmax(y_true,1))<br>            acc = tf.reduce_mean(tf.cast(matches,tf.float32))</pre><pre>            print(&#39;Step {}: accuracy={}&#39;.format(i, sess.run(acc,feed_dict={x:mnist_conv_onehot.test.images,                 y_true:mnist_conv_onehot.test.labels,                                                                           hold_prob:1.0})))</pre><blockquote>Step 0: accuracy=0.20010000467300415<br>Step 500: accuracy=0.9563999772071838<br>Step 1000: accuracy=0.973800003528595<br>Step 1500: accuracy=0.9807999730110168<br>Step 2000: accuracy=0.9815000295639038<br>Step 2500: accuracy=0.9854000210762024<br>Step 3000: accuracy=0.9864000082015991<br>Step 3500: accuracy=0.9868000149726868<br>Step 4000: accuracy=0.9886000156402588<br>Step 4500: accuracy=0.9894999861717224<br>Step 5000: accuracy=0.9865999817848206</blockquote><h3>Bayesian CNN</h3><p>I chose TensorFlow Probability to implement Bayesian CNN purely for convenience and familiarity with TensorFlow. This package uses the <a href="https://arxiv.org/pdf/1803.04386.pdf">Flipout</a> gradient estimator to minimize the negative ELBO as the loss. It computes the integration when deriving the posterior distribution. Other implementations may be more efficient; for example, <a href="https://arxiv.org/pdf/1806.05978.pdf">Shridhar et al </a>2018’s applied the Local Reparameterization Trick to avoid the integration by sampling from an approximation of posterior distribution.</p><p>The codes are modified based on the provided example <a href="https://github.com/tensorflow/probability/blob/master/tensorflow_probability/examples/bayesian_neural_network.py">here</a>. The codes of the plots below are taken from the original example, thus not displayed here.</p><pre>images = tf.placeholder(tf.float32,shape=[None,28,28,1])<br>labels = tf.placeholder(tf.float32,shape=[None,])<br>hold_prob = tf.placeholder(tf.float32)</pre><pre># define the model<br>neural_net = tf.keras.Sequential([<br>      tfp.layers.Convolution2DReparameterization(32, kernel_size=5,  padding=&quot;SAME&quot;, activation=tf.nn.relu),<br>      tf.keras.layers.MaxPooling2D(pool_size=[2, 2],  strides=[2, 2],  padding=&quot;SAME&quot;),<br>      tfp.layers.Convolution2DReparameterization(64, kernel_size=5,  padding=&quot;SAME&quot;,  activation=tf.nn.relu),<br>      tf.keras.layers.MaxPooling2D(pool_size=[2, 2], strides=[2, 2], padding=&quot;SAME&quot;),<br>      tf.keras.layers.Flatten(),<br>      tfp.layers.DenseFlipout(1024, activation=tf.nn.relu),<br>      tf.keras.layers.Dropout(hold_prob),<br>      tfp.layers.DenseFlipout(10)])</pre><pre>logits = neural_net(images)</pre><pre># Compute the -ELBO as the loss, averaged over the batch size.<br>labels_distribution = tfp.distributions.Categorical(logits=logits)<br>neg_log_likelihood = -tf.reduce_mean(labels_distribution.log_prob(labels))<br>kl = sum(neural_net.losses) / mnist_conv.train.num_examples<br>elbo_loss = neg_log_likelihood + kl</pre><pre>optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)<br>train_op = optimizer.minimize(elbo_loss)</pre><pre># Build metrics for evaluation. Predictions are formed from a single forward<br># pass of the probabilistic layers. They are cheap but noisy predictions.<br>predictions = tf.argmax(logits, axis=1)<br>accuracy, accuracy_update_op = tf.metrics.accuracy(labels=labels, predictions=predictions)</pre><pre>learning_rate = 0.001   #initial learning rate<br>max_step = 5000 #number of training steps to run<br>batch_size = 50 #batch size</pre><pre>viz_steps = 500 #frequency at which save visualizations.<br>num_monte_carlo = 50 #Network draws to compute predictive probabilities.</pre><pre>init_op = tf.group(tf.global_variables_initializer(),<br>                     tf.local_variables_initializer())</pre><pre><br>with tf.Session() as sess:<br>        sess.run(init_op)</pre><pre># Run the training loop.<br>        for step in range(max_step+1):<br>            images_b, labels_b = mnist_conv.train.next_batch(<br>batch_size)<br>            images_h, labels_h = mnist_conv.validation.next_batch(<br>mnist_conv.validation.num_examples)<br>            <br>            _ = sess.run([train_op, accuracy_update_op], feed_dict={<br>                   images: images_b,labels: labels_b,hold_prob:0.5})</pre><pre>        if (step==0) | (step % 500 == 0):<br>                loss_value, accuracy_value = sess.run([elbo_loss, accuracy], feed_dict={images: images_b,<br>labels: labels_b,hold_prob:0.5})<br>                <br>                print(&quot;Step: {:&gt;3d} Loss: {:.3f} Accuracy: {:.3f}&quot;.format(step, loss_value, accuracy_value))</pre><blockquote><em>Step: 0 Loss: 161.928 Accuracy: 0.140<br>Step: 500 Loss: 135.825 Accuracy: 0.858<br>Step: 1000 Loss: 117.817 Accuracy: 0.907<br>Step: 1500 Loss: 99.129 Accuracy: 0.927<br>Step: 2000 Loss: 80.596 Accuracy: 0.938<br>Step: 2500 Loss: 63.682 Accuracy: 0.946<br>Step: 3000 Loss: 48.857 Accuracy: 0.950<br>Step: 3500 Loss: 36.574 Accuracy: 0.954<br>Step: 4000 Loss: 27.315 Accuracy: 0.957<br>Step: 4500 Loss: 20.480 Accuracy: 0.959<br>Step: 5000 Loss: 15.652 Accuracy: 0.961</em></blockquote><h3>Results</h3><p>The regular CNN takes a shorter time to run and achieves better accuracy, compared to the Bayesian CNN using the same model structure. However, the one advantage that Bayesian CNN brings in is an uncertainty measure of the weights and predictions.</p><p>The following plots show the hyper parameters of weight posterior distributions converge through training steps. At the beginning, priors dominate the distributions so that all are similar; in the end, the posteriors differ as driven by the data. Recall the layers in the model:</p><p>Layer 0: Convolutional layer (32 kernels) <br>Layer 2: Convolutional layer (64 kernels) <br>Layer 5: Fully connected layer (1024 output units) <br>Layer 7: Fully connected layer (10 output units, one for each digit)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W2UO9Gb8S8-rIrYKQXkqyg.png" /></figure><p>The graphs below show the uncertainties of prediction at training steps 1, 500 and 5000 (from left to right). Step 1 shows higher uncertainties; after 500 training batches, the predictions become more confident in general, except for some unclear hand writings. For example, the second last case is difficult even for humans to be certain (3 or 5?). After step 5000, the model confidence is improved significantly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*athtntPOO8-GpLZ0zsroXg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82d56a298f45" width="1" height="1" alt=""><hr><p><a href="https://medium.com/python-experiments/bayesian-cnn-model-on-mnist-data-using-tensorflow-probability-compared-to-cnn-82d56a298f45">Bayesian CNN model on MNIST data using Tensorflow-probability (compared to CNN)</a> was originally published in <a href="https://medium.com/python-experiments">Python experiments</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parallelising in Python (mutithreading and mutiprocessing) with practical templates]]></title>
            <link>https://medium.com/python-experiments/parallelising-in-python-mutithreading-and-mutiprocessing-with-practical-templates-c81d593c1c49?source=rss----5c34e9b6bd69---4</link>
            <guid isPermaLink="false">https://medium.com/p/c81d593c1c49</guid>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[multiprocessing]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[LU ZOU]]></dc:creator>
            <pubDate>Wed, 16 Jan 2019 15:19:57 GMT</pubDate>
            <atom:updated>2019-01-16T15:01:12.299Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Motivation</strong></h4><p>In a recent project, we were required to shorten code run times, as such few interesting methods were investigated, namely multithreading and multiprocessing. Here we provide some sample codes and brief explanations on how to get your code running with these techniques. We hope this can save you some time searching for solutions.</p><p>In python, multithreading and multiprocessing are popular methods to consider when you want to parallelise your programmes. The two methods and their differences are well explained in <a href="https://www.quantstart.com/articles/Parallelising-Python-with-Threading-and-Multiprocessing">this article</a>.</p><p>The performance was estimated based on the Windows system:<br> <em>- Windows 10, 4 cores, 16GB RAM, x64-based processor</em></p><pre># automatically display running time of a cell<br>%reload_ext autotime</pre><pre># output results of multiple statements in one cell<br>from IPython.core.interactiveshell import InteractiveShell<br>InteractiveShell.ast_node_interactivity = “all”</pre><pre># load libraries<br>from multiprocessing import freeze_support<br>from multiprocessing import Pool<br>from functools import partial<br>import threading<br>import math<br>import pandas as pd<br>import numpy as np<br>from random import randint<br>from time import sleep</pre><p>Suppose the task is to determine whether a number is a prime number. The function below requires an integer as an input and output whether it’s a prime number as <strong>True</strong> or <strong>False</strong>.</p><pre># define a test function that determines whether or not an integer is a prime number<br>def is_prime(n):<br>    if (n &lt; 2) or (n % 2 == 0 and n &gt; 2):<br>        return (n, False)<br>    elif n == 2:<br>        return (n, True)<br>    elif n == 3:<br>        return (n, True)<br>    else:<br>        for i in range(3, math.ceil(math.sqrt(n)) + 1, 2):<br>            if n % i == 0:<br>                return (n, False)<br>        return (n, True)</pre><p>We applied three methods to set up the baseline performance: looping, mapping and vectorizing. They are similar in terms of running time.</p><pre># set the maximum range to detect prime numbers in (0 to num_max-1)<br>num_max = 1000000</pre><pre># looping<br>%timeit np.array([is_prime(x) for x in list(range(num_max))])</pre><pre>#mapping<br>%timeit np.array(list(map(is_prime, list(range(num_max)))))</pre><pre># vectorizing<br>%timeit np.vectorize(is_prime)(list(range(num_max)))</pre><blockquote>Looping: 27.1 s ± 475 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)</blockquote><blockquote>Map: 26.2 s ± 667 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)</blockquote><blockquote>Vectorizing: 26.6 s ± 363 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)</blockquote><h3>Multithreading</h3><p>For the prime number task, the threading does <strong>NOT</strong> work with functions with <strong>RETURN</strong> command. In order to extract the results, we need to append it from each thread. We can do this because the threads share the same memory space, which is more challenging using multiple processors, because processors use separate memory spaces.</p><p>The running time is much longer (&gt; 2 mins) than the looping.</p><pre># mutithreading version<br>def func_thread(n, out):<br>    out.append(is_prime(n))</pre><pre>x_ls =list(range(num_max))<br>thread_list = []<br>results = []<br>for x in x_ls:<br> thread = threading.Thread(target=func_thread, args=(x, results))<br> thread_list.append(thread)<br>for thread in thread_list:<br> thread.start()<br>for thread in thread_list:<br> thread.join()</pre><pre># time: 2min 58s</pre><p>Why does it take much longer?</p><p>In Python, the real multithreading cannot be achieved because of the global interpreter lock (<a href="https://wiki.python.org/moin/GlobalInterpreterLock">GIL</a>). This lock prevents multiple threads from executing codes at the same time.</p><p>However, Python still provides the <a href="https://docs.python.org/2/library/threading.html">Threading</a> library. When should we use it then? Although one thread is running one at a time, the waiting time is optimised by the library between the threads. The following example will demonstarte time saving by running multiple threads.</p><p>The function does no calculation, just waits for a random time from 1 to 10 seconds. Applying this function 10 times in a single thread, it took over 50 seconds; while using multiple threads, one doesn’t need to wait until the sleeping time is ended on another thread, so the running time is shortened to under 10 seconds.</p><p>However, if the task is highly numerically intensive, then no benefit can be gained using Python multithreading. In contrast to the sleeping task, the prime determination is computational. There is little waiting time on the disk IO.</p><pre>def sleeping(number):<br>    # Sleeps a random 1 to 10 seconds<br>    rand_int_var = randint(1, 10)<br>    sleep(rand_int_var)<br>#     print(&quot;Thread &quot; + str(number) + &quot; slept for &quot; + str(rand_int_var) + &quot; seconds\n&quot;)</pre><pre>def sleep_thread():<br>    thread_list = []</pre><pre>for i in range(1, 10):<br>        # Instantiates the thread<br>        t = threading.Thread(target=sleeping, args=(i,))<br>        # Sticks the thread in a list so that it remains accessible<br>        thread_list.append(t)</pre><pre># from the main-thread, starts child threads<br>    for thread in thread_list:<br>        thread.start()</pre><pre># main-thread &#39;sleeping&#39; in join-method, waiting for child-thread to finish <br>    for thread in thread_list:<br>        thread.join()</pre><pre>%timeit np.array([sleeping(i) for i in range(1, 10)])</pre><blockquote><em>Time: 52.5 s ± 11.9 s per loop (mean ± std. dev. of 7 runs, 1 loop each)</em></blockquote><pre>%timeit sleep_thread()</pre><blockquote><em>Time: 9.44 s ± 728 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)</em></blockquote><h3>Mutiprocessing</h3><p>First of all, <a href="https://docs.python.org/3.4/library/multiprocessing.html?highlight=multiprocessing.manager">mutiprocessing</a> cannot be run interactively. Functionality within this package requires the <strong>__name__ == “__main__”</strong> part on <strong>Windows</strong> machine. This is to make sure that the main module can be safely imported by a new Python interpreter, e.g. by a child process. One clear explanation can be found <a href="https://docs.python.org/2/library/multiprocessing.html#programming-guidelines">here</a>.</p><p>For the prime number task, we wrap the following codes in a .py file, and either run the file as a whole in interpreter or run it in the terminal.</p><blockquote><em>python prime_mutiprocessing.py</em></blockquote><p>It takes under 10 seconds to run the scripts using 6 processors; it shortens the time by more than a half compared to looping.</p><blockquote><em>Mutiprocessing time: 6.412 seconds.</em></blockquote><pre><em># prime_mutiprocessing.py</em><br><br><strong>import</strong> time<br><strong>import</strong> math<br><strong>from</strong> multiprocessing <strong>import</strong> Pool<br><strong>from</strong> multiprocessing <strong>import</strong> freeze_support<br><br><br>&#39;&#39;&#39;Define function to run mutiple processors and pool the results together&#39;&#39;&#39;<br><strong>def</strong> run_multiprocessing(func, i, n_processors):<br>    <strong>with</strong> Pool(processes<strong>=</strong>n_processors) <strong>as</strong> pool:<br>        <strong>return</strong> pool.map(func, i)<br><br><br>&#39;&#39;&#39;Define task function&#39;&#39;&#39;<br><strong>def</strong> is_prime(n):<br>    <strong>if</strong> (n <strong>&lt;</strong> 2) <strong>or</strong> (n <strong>%</strong> 2 <strong>==</strong> 0 <strong>and</strong> n <strong>&gt;</strong> 2):<br>        <strong>return</strong> <strong>False</strong><br>    <strong>elif</strong> n <strong>==</strong> 2:<br>        <strong>return</strong> <strong>True</strong><br>    <strong>elif</strong> n <strong>==</strong> 3:<br>        <strong>return</strong> <strong>True</strong><br>    <strong>else</strong>:<br>        <strong>for</strong> i <strong>in</strong> range(3, math.ceil(math.sqrt(n)) <strong>+</strong> 1, 2):<br>            <strong>if</strong> n <strong>%</strong> i <strong>==</strong> 0:<br>                <strong>return</strong> <strong>False</strong><br>        <strong>return</strong> <strong>True</strong><br><br><br><strong>def</strong> main():<br>    start <strong>=</strong> time.clock()<br><br>    &#39;&#39;&#39;<br>    set up parameters required by the task<br>    &#39;&#39;&#39;<br>    num_max <strong>=</strong> 1000000<br>    n_processors <strong>=</strong>6<br>    x_ls <strong>=</strong> list(range(num_max))<br><br>    &#39;&#39;&#39;<br>    pass the task function, followed by the parameters to processors<br>    &#39;&#39;&#39;<br>    out <strong>=</strong> run_multiprocessing(is_prime, x_ls, n_processors)<br><br>    print(&quot;Input length: {}&quot;.format(len(x_ls)))<br>    print(&quot;Output length: {}&quot;.format(len(out)))<br>    print(&quot;Mutiprocessing time: {}mins\n&quot;.format((time.clock()<strong>-</strong>start)<strong>/</strong>60))<br>    print(&quot;Mutiprocessing time: {}secs\n&quot;.format((time.clock()<strong>-</strong>start)))<br><br><br><strong>if</strong> __name__ <strong>==</strong> &quot;__main__&quot;:<br>    freeze_support()   <em># required to use multiprocessing</em><br>    main()</pre><h3>Summary</h3><p>In a piece of recent work, running time was a real constraint. After vectorization where possible additional time saving approaches were investigated. Mutiprocessing was found to greatly reduce are execution time and some working examples are given above.</p><p>Hopefully this guide allows you to save some time implementing multiprocessing in your next project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c81d593c1c49" width="1" height="1" alt=""><hr><p><a href="https://medium.com/python-experiments/parallelising-in-python-mutithreading-and-mutiprocessing-with-practical-templates-c81d593c1c49">Parallelising in Python (mutithreading and mutiprocessing) with practical templates</a> was originally published in <a href="https://medium.com/python-experiments">Python experiments</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>