<?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 Vikas Sangwan on Medium]]></title>
        <description><![CDATA[Stories by Vikas Sangwan on Medium]]></description>
        <link>https://medium.com/@16vikas96?source=rss-f7fc46473942------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8K5qEieMPYkIVpqNrabopA.jpeg</url>
            <title>Stories by Vikas Sangwan on Medium</title>
            <link>https://medium.com/@16vikas96?source=rss-f7fc46473942------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 08:32:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@16vikas96/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[Beginner’s guide to feeding data in Tensorflow — Part2]]></title>
            <link>https://medium.com/coinmonks/beginners-guide-to-feeding-data-in-tensorflow-part2-5e2506d75429?source=rss-f7fc46473942------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e2506d75429</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Vikas Sangwan]]></dc:creator>
            <pubDate>Sun, 24 Jun 2018 00:09:41 GMT</pubDate>
            <atom:updated>2022-06-25T12:54:56.663Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*1RRz25yFDh8C1gSToxm6JA.jpeg" /></figure><p>Hi, this is part 2 of the series. In this post, I will be showing how to feed the TFRecord data format and raw images to your tensorflow model. The various advantages of TFRecords format are —</p><ol><li>Faster to read than PNG or other formats.</li><li>Gives you the flexibility in data pipelining.</li><li>Useful when the data doesn’t fit in memory.</li><li>Less no of files to manage.(Personal opinion)</li></ol><p>Link for part-1 is <a href="https://medium.com/@16vikas96/beginners-guide-to-feeding-data-in-tensorflow-faf21a745e4c">here</a> and link to the code to convert to tfrecords is <a href="https://gist.github.com/shang-vikas/509cc87d4b37694308f717b1cbb3585a">here.</a></p><p><strong>Dataset used — </strong>MNIST</p><p><strong>Model Architecture </strong>— Two hidden layers of 100 neurons each and 1 output layer of 10 neurons.</p><p>I assume that you have the data in TFRecords format.Let’s get started.</p><pre>## import necessary stuff<br>import tensorflow as tf<br>import numpy as np<br>import os,sys<br>import time</pre><pre>## defining the type of features columns to be used on model.<br>feature_column = [tf.feature_column.numeric_column(key=&#39;image&#39;,shape=(784,))]</pre><pre>##defining the model<br>model = tf.estimator.DNNClassifier([100,100],n_classes=10,feature_columns=feature_column)</pre><p>Now that we have created the model, lets define the data flow. We will be using the <strong>TFRecordDataset</strong> method from DATASET API.</p><p>First we need to define a function that will convert the TFRecords format back to tensor of dtype tf.float32 in case of image and to tf.int32 in case of label.</p><p>The conversion would be like this -</p><pre><strong>TFRecords --&gt; Serialized Example --&gt; Example --&gt; Tensor</strong></pre><p>Here’s the function —</p><pre>def _parse_(serialized_example):<br>    feature = {&#39;image_raw&#39;:tf.FixedLenFeature([],tf.string),<br>                &#39;label&#39;:tf.FixedLenFeature([],tf.int64)}<br>    example = tf.parse_single_example(serialized_example,feature)<br>    image = tf.decode_raw(example[&#39;image_raw&#39;],tf.int64) #remember to parse in int64. float will raise error<br>    label = tf.cast(example[&#39;label&#39;],tf.int32)<br>    return (dict({&#39;image&#39;:image}),label)</pre><p>In the above code, we are parsing single example from serialized one. To parse one example or in simple words one data-point, we need to provide the name of the features and their corresponding type as a dictionary to parse_single_example along with the serialized example.I stored the images with the ‘image_raw’ key and label with ‘label’ key with data-types as tf.string and tf.int64 respectively, so i have passed the same values in the dictionary. If you don’t remember the names of the features, there is a trick to find out the names. Just do head -n20 /path/to/tfrecords in Linux. This will print the name of the features in readable format.</p><p>Now that we know how to parse the tfrecords, lets write the function that will use this _parse_ function and will return the batches of (features,label) to be feed to the model.</p><pre>mnist_tfrecord_path = os.path.abspath(&#39;./mnist_train.tfrecords&#39;)</pre><pre>def tfrecord_train_input_fn(batch_size=32):<br>    tfrecord_dataset = tf.data.TFRecordDataset(mnist_tfrecord_path)<br>    tfrecord_dataset = tfrecord_dataset.map(lambda   x:_parse_(x)).shuffle(True).batch(batch_size)<br>    tfrecord_iterator = tfrecord_dataset.make_one_shot_iterator()<br>    <br>    return tfrecord_iterator.get_next()</pre><p>Now that we have created the data input pipeline function, let’s try to train the model.</p><pre>model.train(lambda:tfrecord_train_input_fn(32),steps=200)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*EY5iVIPGWcc96WZFKtYw6w.png" /></figure><ul><li><strong>What if i have the raw Images on disk???</strong></li></ul><blockquote>Code to write the numpy arrays to jpg format on disk is <a href="https://gist.github.com/shang-vikas/3670a06f0e4bfc1a52f4847ac3d31c78">here.</a></blockquote><p>The above code will write the image in the format “image[i]_[class].jpg” where class is the label of the image and i is for the count. Total images are 60k.Now to read the images and preprocess them, we need to write a parse function again that would read the image, split the label ,convert the label to scalar of tf.int32 and image to tf.float and return a tuple.</p><pre>path = os.path.abspath(&#39;./digit-recognizer/train/&#39;)</pre><pre>def _ondisk_parse_(filename):<br>    filename = tf.cast([filename],tf.string)<br>    <br>    label = tf.string_split([tf.string_split(filename,&#39;_&#39;).values[1]],&#39;.&#39;).values[0]<br>    label = tf.string_to_number([label],tf.int32)<br>    <br>    path = os.path.abspath(&#39;./digit-recognizer/train//&#39;)<br>    path = tf.cast([path],tf.string)<br>    <br>    final_path = tf.string_join((path,tf.cast([&#39;/&#39;],tf.string),filename))<br>    <br>    image_string = tf.read_file(final_path[0])<br>    image = tf.image.decode_jpeg(image_string)<br>    image = tf.cast(image,tf.int8)<br>    image = tf.cast(image,tf.float32)<br>    image_reshaped = tf.reshape(image,(784,))<br>    return (dict({&#39;image&#39;:image}),label)</pre><p>Here, i have used the tensorflow’s native string_split , string_to_number etc. methods since it was recommended by tensorflow authors, otherwise i had to wrap my function that would use python methods(.split , string() , etc) around a wrapper given by the tensorflow and i was not in a mood to do that. Here, remember to cast the image back to int8 since at time of saving the image, the format was int8. Directly casting to other format that int8 would cause an error.</p><p>Now that _ondisk_parse is ready, Lets write the final train input function.</p><pre>def ondisk_train_input_fn(filenames,batch_size=32):<br>    dataset  = tf.data.Dataset.from_tensor_slices(filenames)<br>    dataset = dataset.map(lambda x:_ondisk_parse_(x)).shuffle(True).batch(batch_size)<br>    ondisk_iterator = dataset.make_one_shot_iterator()<br>    <br>    return ondisk_iterator.get_next()</pre><p>Here i have used the _from_tensor_slices method again as you can pass the in-memory data(tensors or numpy arrays) or the filenames of the images that you need to feed to this method. Rest of the pipeline is same as mapping the _ondisk_parse_ first then shuffling,creating the batches ,making one_shot_iterator and returning the next batch.</p><p>Finally, the training part —</p><pre>#list of the images in train folder<br>f = !ls ./digit-recognizer/train/ <br>#train the model<br>model.train(lambda:ondisk_train_input_fn(f,32),steps=200)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*_JrSwDNug_iGfMxIDQAL8Q.png" /></figure><p><strong>END</strong></p><blockquote>The full code is available <a href="https://gist.github.com/shang-vikas/f25e13bfa5425258eb47c91d8739536b">here.</a></blockquote><p>If you liked the post, give some claps.</p><blockquote>Join Coinmonks<a href="https://t.me/coincodecap"> Telegram Channel</a> and<a href="https://www.youtube.com/c/coinmonks/videos"> Youtube Channel</a> get daily <a href="http://coincodecap.com/">Crypto News</a></blockquote><h4>Also, Read</h4><ul><li><a href="https://medium.com/coinmonks/top-10-crypto-copy-trading-platforms-for-beginners-d0c37c7d698c">Copy Trading</a> | <a href="https://medium.com/coinmonks/crypto-tax-software-ed4b4810e338">Crypto Tax Software</a></li><li><a href="https://coincodecap.com/grid-trading">Grid Trading</a> | <a href="https://medium.com/coinmonks/the-best-cryptocurrency-hardware-wallets-of-2020-e28b1c124069">Crypto Hardware Wallet</a></li><li><a href="http://Top 4 Telegram Channels for Crypto Traders">Crypto Telegram Signals</a> | <a href="https://medium.com/coinmonks/crypto-trading-bot-c2ffce8acb2a">Crypto Trading Bot</a></li><li><a href="https://medium.com/coinmonks/crypto-exchange-dd2f9d6f3769">Best Crypto Exchange</a> | <a href="https://medium.com/coinmonks/bitcoin-exchange-in-india-7f1fe79715c9">Best Crypto Exchange in India</a></li><li><a href="https://medium.com/coinmonks/best-crypto-apis-for-developers-5efe3a597a9f">Best Crypto APIs</a> for Developers</li><li>Best <a href="https://medium.com/coinmonks/top-5-crypto-lending-platforms-in-2020-that-you-need-to-know-a1b675cec3fa">Crypto Lending Platform</a></li><li>An ultimate guide to <a href="https://medium.com/coinmonks/leveraged-token-3f5257808b22">Leveraged Token</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e2506d75429" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/beginners-guide-to-feeding-data-in-tensorflow-part2-5e2506d75429">Beginner’s guide to feeding data in Tensorflow — Part2</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beginner’s guide to feeding data in Tensorflow — Part1]]></title>
            <link>https://medium.com/coinmonks/beginners-guide-to-feeding-data-in-tensorflow-faf21a745e4c?source=rss-f7fc46473942------2</link>
            <guid isPermaLink="false">https://medium.com/p/faf21a745e4c</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Vikas Sangwan]]></dc:creator>
            <pubDate>Sat, 23 Jun 2018 22:02:43 GMT</pubDate>
            <atom:updated>2022-06-24T18:33:52.908Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi, this series would be regarding feeding data(images and numeric features) to your tensorflow models. After reading all the posts, you will be able to —</p><ol><li>Feed the in-memory data to your model.</li><li>Feed the TFRecords format to your model.</li><li>Feed the Raw Images on disk to your model.</li></ol><p>In this part i will be focusing on feeding the in-memory data .</p><p>This post assumes the following skill-set on reader’s side — <strong>basic working of Neural Nets, basics of Tensorflow or basics model building in Keras.</strong></p><p>The code for this post is available <a href="https://gist.github.com/shang-vikas/36176e3bed6f3234fd1c27465d8bec22">here.</a></p><p>Let’s get started.</p><p><strong>INSTALLATION</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*bk0bcNwkc_Z32fRJjEx6Gg.jpeg" /></figure><p>pip install tensorflow-gpu keras</p><p>or if you don’t have a GPU, install the CPU version of tensorflow.</p><p>pip install tensorflow keras</p><p><strong>DATASET</strong></p><p>We will be using the popular MNIST dataset. It contains the images of digits from 0–9. Generally this dataset is available in <strong>numpy array</strong> format. So I will provide the code to convert the data to <a href="https://gist.github.com/shang-vikas/509cc87d4b37694308f717b1cbb3585a">TFRecords Format</a> and to <a href="https://gist.github.com/shang-vikas/3670a06f0e4bfc1a52f4847ac3d31c78">raw Images</a> on disk.</p><p><strong>Using the Estimator API</strong></p><p>Tensorflow provides the High Level Estimator API for defining your model with minimum efforts. We will be using this API for building our simple Model of <strong>2 Hidden layers</strong> of 100 neurons each with an output layer of 10 since the dataset has <strong>10 classes.</strong></p><p>When you make a model with Estimator API, it expects the type of feature columns of dataset as a list that would be feed during training. Since we are using the images which contains numbers we would be providing one feature column of <strong>Numeric type</strong> to it.</p><pre>feature_column = [tf.feature_column.numeric_column(key=’image’,shape=(784,))]</pre><p>Here key is the name that we wish to give to that feature column. Note that the same key should be passed to the model when your are feeding the data.</p><p>For a more detailed list of type of feature_columns, go to <a href="https://www.tensorflow.org/get_started/feature_columns">tensorflow’s documentation</a>.</p><p>Now for creating the model ,we would be using the pre-made estimators — specifically the DNNClassifier a.k.a Deep neural net classifier in which you can add as many dense layers as you want.</p><p>##defining the model</p><pre>model = tf.estimator.DNNClassifier([100,100],n_classes=10,feature_columns=feature_column)</pre><p>Now that we have defined our model , lets define the <strong>DATASET Flow.</strong></p><ol><li><strong>Working with Numpy arrays</strong></li></ol><pre>import numpy as np<br>import pandas as pd<br>from keras.datasets import mnist</pre><pre>(x_train,y_train),(x_test,y_test) = mnist.load_data()<br>#since the model expects a single feature vector of size 784 #convert from (28,28) to 784 <br>x_train = x_train.reshape(-1,784) <br>x_test = x_test.reshape(-1,784)</pre><ul><li>Since we have the data as numpy arrays here. So the simplest way would be to pass the data to model right??<strong>Correct. </strong>Tensorflow provides this feature under <strong>tf.estimator.inputs.</strong> Let’s pass the data and train the model for 101 steps. Here steps mean the no. of mini-batches seen by the model.Default batch size is <strong>128.</strong></li></ul><pre>model.train(input_fn=tf.estimator.inputs.numpy_input_fn(<br>dict({&#39;image&#39;:x_train}),                                         np.array(y_train,np.int32),<br>shuffle=True),steps=101)<br></pre><p>The output would be look like this -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*mGsswPeQh95dJr0VS6ZykA.png" /></figure><p>This works fine But what if you want to do some preprocessing of the data before feeding it to the model. Here the <strong>DATASET API </strong>comes to the rescue.</p><p>As you saw in the above line of code, model.train expects the data to be feed from an input function.Since that function would require a preprocessing function in case we are doing some preprocessing , Let’s write a preprocessing function that would convert the numpy arrays to tensor and change the data type to float32 since the weights of the dense layers are of dtype float32.</p><p><strong>NOTE: As a rule of thumb, always first convert your data to tensors(float32 ,int32) otherwise you will get weird errors that will cause a lot of problem.</strong></p><pre>&#39;&#39;&#39;parse function to be used. This function is needed to do the preprocessing of data like reshaping ,converting to tensors from numpy arrays ,one-hot encoding ,etc.&#39;&#39;&#39;<br>def _parse_and_preprocess(x,y):<br>    x = tf.cast(x,tf.float32) <br>    #cast to float32 as the weights are float32.<br>    y = tf.cast(y,tf.int32) #cast to tensor of int32<br>    return (dict({&#39;image&#39;:x}),y) #return tuple of dict of feature # name with key as provided in the feature column and label.</pre><p>Now write the input function that would return a generator to fetch the next batch of data.</p><pre>##define the function that feeds the data to the model .<br>def train_input_fn(x_train,y_train,batch_size=64):<br>    ##Here we are using dataset API.<br>    &#39;&#39;&#39;<br>    take the data from tensor_slices i.e. an array of data-points in simple words.<br>    &#39;&#39;&#39;<br>    dataset =    tf.data.Dataset.from_tensor_slices((x_train,y_train)) <br>    <br>    <br>    dataset = dataset.map(lambda x,y:_parse_and_preprocess(x,y)).shuffle(buffer_size=128) \<br>                .batch(batch_size)</pre><pre>    dataset_iterator = dataset.make_one_shot_iterator()   <br>    return dataset_iterator.get_next()</pre><p>Here we are using the DATASET API(tf.data.Dataset). Since we have the data as arrays we can call the from_tensor_slices method and pass on the data.</p><p>I know that the name of method is ambiguous!!</p><p>The tensor_from_slices method also takes the list of filenames stored on disk. I will explain this in next post.</p><p>If you have a dataset that contains various numeric and categorical features, then you should use the <a href="https://www.tensorflow.org/get_started/datasets_quickstart">TextLineDataset</a> method of Dataset API or pandas_input_fn from tf.estimator.inputs but i would highly recommend the former one.</p><p>The incoming data is now passed to _parse_preprocess function that we wrote and would return a tuple of <strong>2</strong> elements — first would be the dictionary with key and image <strong>data as 784 tensor of dtype tf.float32</strong> and second is the <strong>label of dtype tf.int32</strong>.</p><p>Now as the name suggests, the <strong>.shuffle()</strong> and <strong>.batch()</strong> methods shuffles and batches the data respectively.</p><p>To iterate over these batches of data-points, we call <strong>make_one_shot_iterator </strong>that returns the iterator a.k.a generator.</p><p>The .get_next() simply returns the next batch of data.</p><p>Now it’s time to train our model.</p><p>NOTE: the input_fn in estimator.train() doesn’t accept the parameters in the function. The workaround is to use the lambda feature of python.</p><pre>import time<br>t1 = time.time()<br>model.train(input_fn=lambda:train_input_fn(x_train,y_train,64),steps=150)<br>t2= time.time()<br>print(&#39;time taken ---- \t {}&#39;.format(t2 - t1))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*9oLpdd7_7ncyXwxBoumvVA.png" /></figure><p><strong>Conclusion:</strong></p><p>The above code works for image data in numpy array format.Now to generalize, instead of just image data if you have data with various features including numeric columns, ordinal, nominal types,</p><ul><li>Just pass the features names in a list whiling creating a model.</li><li>Use the TextLineDataset method from tf.data.Dataset API instead of from_tensor_slices in the train_input_fn().</li><li>Map the dataset to an appropriate preprocessing function that would still return the tuple containing the features with the appropriate keys in a dict and a label.</li><li>Then shuffle, batch according to the requirements and finally making an iterator and returning the next batch.</li></ul><blockquote>Link for part2 is <a href="https://medium.com/@16vikas96/beginners-guide-to-feeding-data-in-tensorflow-part2-5e2506d75429">here.</a></blockquote><p>Thank you for reading the post. If you liked it, please give some claps.</p><blockquote>Join Coinmonks<a href="https://t.me/coincodecap"> Telegram Channel</a> and<a href="https://www.youtube.com/c/coinmonks/videos"> Youtube Channel</a> get daily <a href="http://coincodecap.com/">Crypto News</a></blockquote><h4>Also, Read</h4><ul><li><a href="http://Top 4 Telegram Channels for Crypto Traders">Crypto Telegram Signals</a> | <a href="https://medium.com/coinmonks/crypto-trading-bot-c2ffce8acb2a">Crypto Trading Bot</a></li><li><a href="https://medium.com/coinmonks/top-10-crypto-copy-trading-platforms-for-beginners-d0c37c7d698c">Copy Trading</a> | <a href="https://medium.com/coinmonks/crypto-tax-software-ed4b4810e338">Crypto Tax Software</a></li><li><a href="https://coincodecap.com/grid-trading">Grid Trading</a> | <a href="https://medium.com/coinmonks/the-best-cryptocurrency-hardware-wallets-of-2020-e28b1c124069">Crypto Hardware Wallet</a></li><li><a href="https://medium.com/coinmonks/crypto-exchange-dd2f9d6f3769">Best Crypto Exchange</a> | <a href="https://medium.com/coinmonks/bitcoin-exchange-in-india-7f1fe79715c9">Best Crypto Exchange in India</a></li><li><a href="https://medium.com/coinmonks/best-crypto-apis-for-developers-5efe3a597a9f">Best Crypto APIs</a> for Developers</li><li>Best <a href="https://medium.com/coinmonks/top-5-crypto-lending-platforms-in-2020-that-you-need-to-know-a1b675cec3fa">Crypto Lending Platform</a></li><li>An ultimate guide to <a href="https://medium.com/coinmonks/leveraged-token-3f5257808b22">Leveraged Token</a></li><li><a href="https://coincodecap.com/best-vpns-for-crypto-trading">Best VPNs for Crypto Trading</a></li><li><a href="https://coincodecap.com/blockchain-analytics">Best Crypto Analytics or On-Chain Data</a> | <a href="https://coincodecap.com/bexplus-review">Bexplus Review</a></li><li><a href="https://coincodecap.com/nft-marketplaces">10 Biggest NFT MarketPlaces to Mint a Collection</a></li><li><a href="https://coincodecap.com/ascendex-staking">AscendEx Staking</a> |<a href="https://coincodecap.com/bot-ocean-review"> Bot Ocean Review</a> |<a href="https://coincodecap.com/bitcoin-wallets-india"> Best Bitcoin Wallets</a></li><li><a href="https://coincodecap.com/bitget-review">Bitget Review</a> |<a href="https://coincodecap.com/gemini-vs-blockfi"> Gemini vs BlockFi</a> |<a href="https://coincodecap.com/okex-futures-trading"> OKEx Futures Trading</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=faf21a745e4c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/beginners-guide-to-feeding-data-in-tensorflow-faf21a745e4c">Beginner’s guide to feeding data in Tensorflow — Part1</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>