<?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 LU ZOU on Medium]]></title>
        <description><![CDATA[Stories by LU ZOU on Medium]]></description>
        <link>https://medium.com/@heron20012003?source=rss-b5206b5319bb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*N08DWnwE79jxnMJf.</url>
            <title>Stories by LU ZOU on Medium</title>
            <link>https://medium.com/@heron20012003?source=rss-b5206b5319bb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 22:05:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@heron20012003/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[Image caption by transfer learning — Flickr8k data]]></title>
            <link>https://medium.com/@heron20012003/image-caption-by-transfer-learning-flickr8k-data-51b54d3e6e02?source=rss-b5206b5319bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/51b54d3e6e02</guid>
            <category><![CDATA[flickr8k]]></category>
            <category><![CDATA[image-captions]]></category>
            <category><![CDATA[transfer-learning]]></category>
            <dc:creator><![CDATA[LU ZOU]]></dc:creator>
            <pubDate>Fri, 15 May 2020 08:47:24 GMT</pubDate>
            <atom:updated>2020-05-15T08:47:24.189Z</atom:updated>
            <content:encoded><![CDATA[<h3>Image caption by transfer learning — Flickr8k data</h3><h3>Introduction</h3><p>The MultiModel neural network architecture that brings the CNN and LSTM models into one has achieved state-of-the-art results on image caption. There are many applications using Tensorflow published online, and I found <a href="https://machinelearningmastery.com/develop-a-deep-learning-caption-generation-model-in-python/">this page</a> by <a href="https://machinelearningmastery.com/author/jasonb/"><strong>Jason Brownlee</strong></a><strong> </strong>is most useful.</p><p>This blog is a play run using transfer learning from <a href="https://cloud.google.com/tpu/docs/inception-v3-advanced">InceptionV3 </a>for CNN and <a href="https://github.com/stanfordnlp/GloVe">GloVe </a>for word embeddings. All the codes are included in this blog.</p><p>The model structure is below. The left hand side is the model to process the image descriptions (<em>Word embedding &gt; Dropout &gt; LSTM</em>); the right hand side is the model to process the image (<em>InceptionV3 &gt; Dropout &gt; Dense</em>). Merge these two models by concatenating text and image features and then add two dense layers where the last layer with the dimension of vocabulary size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MkSDmxL2-TyH-k1otTQKrA.png" /><figcaption>Model architecture</figcaption></figure><p>The model requires the input in the following format. The input features include two parts: Image features from InceptionV3 and caption in sequences. The target variable is one-hot encoded vectors with a length of vocabulary size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*Qob20fhYEatSDutYN8B_cg.jpeg" /><figcaption>Input data structure</figcaption></figure><h3>Flickr8k data</h3><p>The full data information can be found <a href="https://machinelearningmastery.com/prepare-photo-caption-dataset-training-deep-learning-model/">here</a>. The original paper on this dataset is <a href="https://www.jair.org/index.php/jair/article/view/10833">here</a>. The original website to download this data is broken. You can download it <a href="https://machinelearningmastery.com/prepare-photo-caption-dataset-training-deep-learning-model/">here</a>.</p><blockquote><em>Flickr8k consisting of 8,000 images that are each paired with five different captions which provide clear descriptions of the salient entities and events.</em></blockquote><p>The <strong>Flickr8k_text</strong> contains the text information, and the following are used in this experiment.</p><ul><li><strong>Flickr8k.token.txt</strong> the raw captions of the Flickr8k Dataset . The first column is the ID of the caption which is “image address # caption number”</li><li><strong>Flickr_8k.trainImages.txt</strong> The training images used in our experiments</li><li><strong>Flickr_8k.devImages.txt</strong> The development/validation images used in our experiments</li><li><strong>Flickr_8k.testImages.txt</strong> The test images used in our experiments</li></ul><p>The <strong>Flickr8k_Dataset</strong> contains all the images.</p><h3>Outline</h3><ol><li>Loading and extracting image features</li><li>Loading and processing captions</li><li>Extract GloVe embeddings</li><li>Data generator to prepare input X[i] and target Y[i]</li><li>Define and train model</li></ol><h3>Packages required</h3><pre>import string<br>import os<br>import matplotlib.pyplot as plt<br>import pickle as pk<br>import numpy as np<br>import tensorflow as tf</pre><pre>from keras.preprocessing.image import load_img, img_to_array<br>from keras.applications.inception_v3 import InceptionV3, preprocess_input<br>from keras.applications import vgg16 <br>from keras.models import Model, load_model<br>from keras.preprocessing.sequence import pad_sequences<br>from keras.utils import to_categorical<br>from keras.layers import Input, Dropout, Dense, LSTM, Embedding, Add</pre><pre>from keras.preprocessing.text import Tokenizer</pre><pre>from IPython.display import SVG<br>from keras.utils.vis_utils import model_to_dot</pre><pre>%matplotlib inline</pre><h3>1. Loading and extracting image features</h3><p>All the images are saved in one folder “Flickr8k_Dataset” as JPG files. They are already split into training, dev and test sets. The following code is to load the image names/IDs for these three sets.</p><pre># define function to read text file<br>def load_text(filename):<br>    # open the file as read only<br>    file = open(filename, &#39;r&#39;)<br>    # read all text<br>    text = file.read()<br>    text = text.split(&#39;\n&#39;)<br>    # close the file<br>    file.close()<br>    return text</pre><pre>train_imgs = load_text(os.path.join(text_folder, &quot;Flickr_8k.trainImages.txt&quot;))<br>test_imgs = load_text(os.path.join(text_folder, &quot;Flickr_8k.testImages.txt&quot;))<br>dev_imgs = load_text(os.path.join(text_folder, &quot;Flickr_8k.devImages.txt&quot;))</pre><pre>train_imgs = [x for x in train_imgs if x != &#39;&#39;]<br>test_imgs = [x for x in test_imgs if x != &#39;&#39;]<br>dev_imgs = [x for x in dev_imgs if x != &#39;&#39;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*PUIle7GiEK3-qElglvIPkQ.png" /><figcaption>Training, dev, test splitting</figcaption></figure><p>Here is an example of the training images.</p><pre>image999 = train_imgs[999]<br>image_999 = load_img(os.path.join(img_folder, image999))<br>plt.imshow(image_999)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*xGe1C4RdLIqavSA2hncK5g.png" /><figcaption>One example image</figcaption></figure><p>The transfer learning is done using one of the pre-trained models from Keras application APIs. The available models are: <em>Xception, VGG16, VGG19, ResNet, ResNetV2, ResNeXt, </em><strong><em>InceptionV3, </em></strong><em>InceptionResNetV2, MobileNet, MobileNetV2, DenseNet, NASNet</em>. The comparison of some of models above can be found in <a href="https://www.pyimagesearch.com/2017/03/20/imagenet-vggnet-resnet-inception-xception-keras/">this blog</a>.</p><p>InceptionV3 initially was called GoogLeNet by <a href="https://arxiv.org/pdf/1409.4842.pdf">Szegedy et al (2014)</a>. It is a widely-used image recognition model that has been shown to attain greater than <a href="https://arxiv.org/pdf/1805.08974.pdf">78%</a> top1 accuracy on the ImageNet dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*wE0A2Er3mz9E-iGoXJsK2A.png" /><figcaption>InceptionV3 model architecture</figcaption></figure><p>To extract the image features, we define the InceptionV3 model without the last layer. Then load one image, reshape and predict on this image by the pre-trained model weights. The output has a shape of <strong>(2048,)</strong>.</p><p>You can run the function <strong><em>get_inceptionv3_feature()</em></strong> defined below through all the images, to extract the image features of InceptionV3. The format will be a <strong><em>dictionary </em></strong>with image name as key and its InceptionV3 features as value.</p><pre>def get_inceptionv3_feature(img_folder, img_name, model):<br>    # Convert all the images to size 299x299 as expected by the<br>    # inception v3 model<br>    img = load_img(os.path.join(img_folder, img_name), target_size=(299,299))<br>    # Convert PIL image to numpy array of 3-dimensions<br>    x = img_to_array(img)<br>    # Add one more dimension<br>    x = np.expand_dims(x, axis=0)<br>    # preprocess images using preprocess_input() from inception module<br>    x = preprocess_input(x)<br>    x = model.predict(x)<br>    # reshape from (1, 2048) to (2048, )<br>    x = np.reshape(x, x.shape[1])<br>    return x</pre><pre># Get the InceptionV3 model trained on imagenet data<br>model_inceptionv3 = InceptionV3(weights=&#39;<strong>imagenet</strong>&#39;)<br># Remove the last layer (output softmax layer) from the inception v3<br>model_inceptionv3 = Model(model_inceptionv3.input, model_inceptionv3.layers[-2].output)</pre><pre>incv3_features_img999 = get_inceptionv3_feature(img_folder, train_imgs[999], model_inceptionv3)</pre><pre>print(&quot;Shape of image vector for one image: {}&quot;.format(incv3_features_img999.shape))</pre><h3>2. Loading and processing captions</h3><p>The “Flickr8k.token.txt” file contains the captions of images in the format per row: [Image caption]. For one image, it looks like the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fxstsv4D3nIvou5VJhRixQ.png" /></figure><p>When loading this TXT file, we re-arrange the captions into a dictionary with the image name as key and a list of five captions as the value. For each caption, we add the start and end signs, “<em>startseq</em>” and “<em>endseq</em>” respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*e89hxWe0RGQKWinS-YZNBg.png" /><figcaption>Loaded image descriptions</figcaption></figure><p>At the cleaning stage, several standard processes of text data are applied: tokenizing, converting to lower case, removing punctuation and single letter words (“s” and “a”).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*2QUki9Xd0FQCC4-pZMpqYQ.png" /><figcaption>Cleaned image descriptions</figcaption></figure><pre>def load_descriptions(doc):<br>    mapping = dict()<br>    # process lines<br>    for line in doc:<br>        # split line by white space<br>        tokens = line.split()<br>        if len(tokens) &lt; 2:<br>            continue<br>        # take the first token as the image id, the rest as the description<br>        image_id, image_desc = tokens[0], tokens[1:]<br>        # remove filename from image id<br>        image_id = image_id.split(&#39;.&#39;)[0]<br>        # convert description tokens back to string<br>        # add &#39;startseq&#39; and &#39;endseq&#39; to each description<br>        image_desc = &#39;startseq &#39;+&#39; &#39;.join(image_desc) + &#39; endseq&#39;<br>        # store the first description for each image<br>        if image_id not in mapping.keys():<br>            mapping[image_id] = []<br>        mapping[image_id].append(image_desc)<br>    return mapping</pre><pre>def clean_description(desc_dict):<br>    # prepare translation table for removing punctuation<br>    table = str.maketrans(&#39;&#39;, &#39;&#39;, string.punctuation)<br>    for key, desc_list in desc_dict.items():<br>        for i in range(len(desc_list)):<br>            desc = desc_list[i]<br>            # tokenize<br>            desc = desc.split()<br>            # convert to lower case<br>            desc = [word.lower() for word in desc]<br>            # remove punctuation from each token<br>            desc = [w.translate(table) for w in desc]<br>            # remove hanging &#39;s&#39; and &#39;a&#39;<br>            desc = [word for word in desc if len(word)&gt;1]<br>            # store as string<br>            desc_list[i] =  &#39; &#39;.join(desc)</pre><pre>descriptions = load_text(os.path.join(text_folder, &quot;Flickr8k.token.txt&quot;))<br>desc_dict = load_descriptions(descriptions)<br>clean_description(desc_dict)</pre><h3>3. Extract GloVe embeddings</h3><p>The pre-trained word embedding can be downloaded <a href="https://github.com/stanfordnlp/GloVe">here</a>. The <a href="https://www.kaggle.com/rtatman/glove-global-vectors-for-word-representation#glove.6B.200d.txt">200 dimension embeddings</a> are used in this blog i.e. each word is represented using 200 embedding values.</p><p>This step applies the follow in order:</p><ul><li>Create the vocabulary</li><li>Map the words to integers, save the mappers</li><li>Load GloVe vectors</li><li>Create GloVe vectors for each word in the vocabulary</li></ul><pre># Create the vocabulary.<br>vocabulary = set()<br>for key in desc_dict.keys():<br>    [vocabulary.update(d.split()) for d in desc_dict[key]]</pre><pre>vocabulary = list(vocabulary)<br>print(&#39;Original Vocabulary Size: %d&#39; % len(vocabulary))</pre><pre># Create the word &lt;--&gt; index mappers.<br># NOTE: index starts from 1, not 0.<br>ixtoword = {}<br>wordtoix = {}<br>ix = 1<br>for w in vocabulary:<br>    wordtoix[w] = ix<br>    ixtoword[ix] = w<br>    ix += 1</pre><pre># Load Glove vectors<br>embeddings_index = {} # empty dictionary<br>f = open(os.path.join(glove_folder, &#39;glove.6B.200d.txt&#39;), encoding=&quot;utf-8&quot;)<br>for line in f:<br>    values = line.split()<br>    word = values[0]<br>    coefs = np.asarray(values[1:], dtype=&#39;float32&#39;)<br>    embeddings_index[word] = coefs<br>f.close()<br>print(&quot;Volcabulary size of GLOVE: {}&quot;.format(len(embeddings_index)))</pre><pre># Get 200-dim dense vector for each of words in vocabulary<br>embedding_dim = 200<br>vocab_size = len(vocabulary)+1    # added 1 for padding<br>embedding_matrix = np.zeros((vocab_size, embedding_dim))<br>for word, i in wordtoix.items():<br>    #if i &lt; max_words:<br>    embedding_vector = embeddings_index.get(word)<br>    if embedding_vector is not None:<br>        # Words not found in the embedding index will be all zeros<br>        embedding_matrix[i] = embedding_vector<br>        <br>print(&quot;Shape of embedding weights for the current vocabulary {}&quot;.format(embedding_matrix.shape))</pre><p>The current vocabulary size is 8811 and 200 embedding values represent each word.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*BobM68zneA5jiagZfjbmlA.png" /><figcaption>Word embedding dimentions</figcaption></figure><p>Note that ‘startseq’ and ‘endseq’ are not included in the GloVe vocabulary, so the vector for them are all zero. The padding value is also zero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*iM5Ji1HjNrie9abP5syJIQ.png" /><figcaption>Starting and end word embeddings</figcaption></figure><h3>4. Data generator to prepare input X[i] and target Y[i]</h3><p>Instead of loading all the images at once, which may cause memory issue, the data generator is used to get around it. It requires all the images are saved in one folder. When training the model, instead of <strong><em>model.fit()</em></strong>, it’s only required changing to <strong><em>model.fit_generator()</em></strong>.</p><p>Assume that you have the following prepared from the previous steps:</p><ul><li>Cleaned image descriptions as a dictionary;</li><li>InceptionV3 image features as a dictionary;</li><li>wordtoix mapper</li><li>Plus the functions defined below.</li></ul><pre># convert a dictionary of clean descriptions to a list of descriptions<br>def to_lines(descriptions):<br>    all_desc = list()<br>    for key in descriptions.keys():<br>        [all_desc.append(d) for d in descriptions[key]]<br>    return all_desc</pre><pre># calculate the length of the description with the most words<br>def max_length(descriptions):<br>    lines = to_lines(descriptions)<br>    return max(len(d.split()) for d in lines)</pre><pre># define the data generator function<br>def data_generator(descriptions, photos, wordtoix, max_length, num_photos_per_batch):<br>    X1, X2, y = list(), list(), list()<br>    n=0<br>    # loop for ever over images<br>    while 1:<br>        for key, desc_list in descriptions.items():<br>            n+=1<br>            # retrieve the photo feature<br>            photo = photos[key]<br>            for desc in desc_list:<br>                # encode the sequence<br>                seq = [wordtoix[word] for word in desc.split(&#39; &#39;) if word in wordtoix]<br>                # split one sequence into multiple X, y pairs<br>                for i in range(1, len(seq)):<br>                    # split into input and output pair<br>                    in_seq, out_seq = seq[:i], seq[i]<br>                    # pad input sequence<br>                    in_seq = pad_sequences([in_seq], maxlen=max_length)[0]<br>                    # encode output sequence<br>                    out_seq = to_categorical([out_seq], num_classes=vocab_size)[0]<br>                    # store<br>                    X1.append(photo)<br>                    X2.append(in_seq)<br>                    y.append(out_seq)<br>            # yield the batch data<br>            if n==num_photos_per_batch:<br>                yield [[np.array(X1), np.array(X2)], np.array(y)]<br>                X1, X2, y = list(), list(), list()<br>                n=0</pre><p>To apply the generator, we determine the maximal length of the description, and define the the batch size as the number of photos to fit into the model each time.</p><pre>max_length = max_length(desc_dict)<br>print(&#39;Max Description Length: %d&#39; % max_length)<br>num_photos_per_batch =5</pre><pre>batch_generator = data_generator(descriptions=desc_dict,<br>               photos=encoded_train_images, wordtoix=wordtoix, max_length=max_length, <br>               num_photos_per_batch=num_photos_per_batch)</pre><pre>inputs, outputs = next(batch_generator)<br>print(inputs[0].shape)<br>print(inputs[1].shape)<br>print(outputs.shape)</pre><p>Here is the outcome dimensions of 5 photos. The <strong>input X has two parts</strong>: image features from InceptionV3 (2048 features) and sequential descriptions with a length of max_length (34). The dimension of 283 based on the number of words in the five descriptions. Remember that we are aiming to have the input as the structure like <a href="https://cdn-images-1.medium.com/max/1000/1*Qob20fhYEatSDutYN8B_cg.jpeg">this</a>. The <strong>output Y</strong> has a dimension of vocabulary size (8811) because it uses one-hot encoding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/120/1*50qRnRDtaToiFrWAah-IIQ.png" /></figure><h3>5. Define and train model</h3><p>To define the model, we need four things from the previous steps:</p><ul><li><em>embedding_matrix</em>: transfered GloVe weights</li><li><em>max_length</em>: the maximal length of the descriptions</li><li><em>vocab_size</em>: vocabulary size of descriptions</li><li><em>embedding_dim</em>: the word vector dimension</li></ul><p>The model is using categorical crossentropy (i.e. multinomial distribution across the vocabulary)because of the one-hot encoded output Y.</p><pre># image feature extractor model<br>inputs1 = Input(shape=(2048,))<br>fe1 = Dropout(0.5)(inputs1)<br>fe2 = Dense(256, activation=&#39;relu&#39;)(fe1)</pre><pre># partial caption sequence model<br>inputs2 = Input(shape=(max_length,))<br>se1 = Embedding(vocab_size, embedding_dim, mask_zero=True)(inputs2)<br>se2 = Dropout(0.5)(se1)<br>se3 = LSTM(256)(se2)</pre><pre># decoder (feed forward) model<br>decoder1 = Add()([fe2, se3])<br>decoder2 = Dense(256, activation=&#39;relu&#39;)(decoder1)<br>outputs = Dense(vocab_size, activation=&#39;softmax&#39;)(decoder2)</pre><pre># merge the two input models<br>model = Model(inputs=[inputs1, inputs2], outputs=outputs)</pre><pre># use pre-fixed weights for embeddding layer and not trainable.<br>model.layers[2].set_weights([embedding_matrix])<br>model.layers[2].trainable = False</pre><pre># model compile<br>model.compile(loss=&#39;categorical_crossentropy&#39;, optimizer=&#39;adam&#39;)</pre><p>I trained this model in the PyCharm, because Jupyter couldn’t pick up the GPU for some reason.</p><pre>for ep in range(1, num_epoch):<br>    print(&quot;run epoch {}&quot;.format(ep))<br>    model.fit_generator(generator=train_generator, steps_per_epoch=len(encoded_train_images), epochs=1)<br>    model.save(os.path.join(proc_folder, &#39;inceptionv3_trained&#39;, &quot;trained_model_{}epochs.h5&quot;.format(ep)))</pre><h3>Predictions</h3><p>This is the kitten photo of my cat. First, I use the function <em>get_inceptionv3_feature()</em> to extract the image features with dimension of 2048 on this photo. Then use the following function to generate the caption from the model. The text input will be a list starting with ‘startseq’.</p><pre>def caption_generator_incpt3glove(photo, model, max_length, wordtoix, ixtoword):<br>    # start with &#39;stratseq&#39;<br>    in_text = [&#39;startseq&#39;]<br>    # iterate over the maximal length of description<br>    for s in range(max_length):<br>        seq = [wordtoix[i] for i in in_text]<br>        seq = pad_sequences([seq], maxlen=max_length)[0]</pre><pre>in_put = [np.array([photo]), np.array([seq])]<br>       <br>        out_word = model.predict(in_put, verbose=0)<br>        # convert probability to integer<br>        out_word = np.argmax(out_word)<br>        # map ix to word<br>        out_word = ixtoword[out_word]<br>        # stop if we cannot map the word<br>        if out_word is None:<br>            break<br>        # append as input for generating the next word<br>        in_text.append(out_word)<br>        # stop if we predict the end of the sequence<br>        if out_word == &#39;endseq&#39;:<br>            break<br>    return in_text</pre><p>Based on the model, my cat is a dog. I also tried the transfer learning from VGG16 for image features, it also identified the kittens as dogs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/1*IOG3PMEhnLxT_ySGdLlApQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*ltdI1aW2k1UDnPBagi_6pQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*_tY1TaMUcQfNFhjdCmdR3A.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51b54d3e6e02" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parallelising (multi-processing) in R — prime number example]]></title>
            <link>https://medium.com/r-practices/parallelising-multi-processing-in-r-prime-number-example-c05dc118fa9a?source=rss-b5206b5319bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/c05dc118fa9a</guid>
            <category><![CDATA[multiprocessing]]></category>
            <category><![CDATA[r]]></category>
            <category><![CDATA[parallel-processing]]></category>
            <dc:creator><![CDATA[LU ZOU]]></dc:creator>
            <pubDate>Tue, 05 Mar 2019 15:09:20 GMT</pubDate>
            <atom:updated>2019-03-05T15:09:20.089Z</atom:updated>
            <content:encoded><![CDATA[<h3>Parallelising (multi-processing) in R — prime number example</h3><h3>Motivation</h3><p>This is a practice blog to implement multi-processing in R.</p><p>R and Python are the most popular programming languages in data science, and both has their advantages at different aspects. This <a href="https://medium.com/@data_driven/python-vs-r-for-data-science-and-the-winner-is-3ebb1a968197">blog </a>compares them in terms of data collection, exploration, modelling and visualization. For applying the multi-processing, I have to say R is much easier and convenient to use.</p><p>I will use the prime number example used in my <a href="https://medium.com/python-experiments/parallelising-in-python-mutithreading-and-mutiprocessing-with-practical-templates-c81d593c1c49">Python parallelization blog</a>. Given an integer, the following function is to determine whether it is a prime number. It will return a list of two elements: the input integer and whether it’s prime (0 for no, 1 for yes).</p><pre>is_prime &lt;- function(n){<br>  if ((n&lt;2) | ((n%%2==0)&amp;(n&gt;2))){<br>    return(c(n, FALSE))<br>  }else if(n==2 | n==3){<br>    return(c(n, TRUE))<br>  }else{<br>    for (i in seq(3, ceiling(sqrt(n)+1), 2)){<br>      if (n%%i ==0) {return(c(n, FALSE))}<br>    }<br>    return(c(n, TRUE))<br>  }<br>}</pre><p>The R library to implement the both socket and forking parallelizations is:</p><blockquote><strong><em>library(parallel)</em></strong></blockquote><p>I will use <em>lapply() </em>from the <em>*apply()</em> functions as the benchmark, because it runs usually faster than a <em>for </em>loop and tidier to use.</p><pre>system.time({<br>  prime_results1 &lt;- lapply(1:1000000, is_prime)<br>})</pre><blockquote>Time of using lapply() is 16.71s.</blockquote><p>There are two methods for parallelization: socket and forking. Forking is not working on Windows system, so cannot achieve acceleration on running time which I will demonstrate later. <a href="http://dept.stat.lsa.umich.edu/~jerrick/courses/stat701/notes/parallel.html">Parallel Processing in R</a> describes the differences between socket and forking, as well as many details that are not covered in this blog.</p><h3>Socket parallelization</h3><p>Socket parallelization runs one unique process on one node, thus no cross-contamination. As a results, the libraries need to be loaded onto each node.</p><p>For the prime number task, we don’t need to load any extra libraries. The general steps to apply socket parallelization are:</p><ol><li>Start a cluster with n nodes (normally the number of cores available);</li><li>Apply any pre-processing codes on each node (e.g. loading libraries)</li><li>Apply <em>par*apply()</em> functions, here is <em>parLapply()</em></li><li>Close the cluster</li></ol><pre>system.time({<br>  cl &lt;- makeCluster(detectCores())<br>  clusterEvalQ(cl, {})  # load libraries inside {} <br>  prime_results &lt;- parLapply(cl, 1:1000000, is_prime)<br>  stopCluster(cl)<br>})</pre><blockquote>Time for socket parallelization is 6.51s.</blockquote><h3>Forking parallelization</h3><p>In R, simply replacing <em>*apply()</em> functions with <em>mcapply()</em> applies the forking parallelization. As mentioned above, this doesn’t achieve any speed gain on Windows; it calls the <em>*apply() </em>underline.</p><pre>system.time({<br>  prime_results2 &lt;- mclapply(1:1000000, is_prime)<br>})</pre><blockquote>Time for forking parallelization is 16.37s.</blockquote><h3>Summary</h3><p>If you are not on Windows, using forking parallelization is a better and convenient choice.</p><p>On Windows, socket parallelization works just fine for the purpose. Although there’re more arrangements on the codes, the application in R is much easier and straight forward compared to Python.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c05dc118fa9a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/r-practices/parallelising-multi-processing-in-r-prime-number-example-c05dc118fa9a">Parallelising (multi-processing) in R — prime number example</a> was originally published in <a href="https://medium.com/r-practices">R practices</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <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-b5206b5319bb------2</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-b5206b5319bb------2</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:48: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-b5206b5319bb------2</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:01:12 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>