<?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 Cameron Cruz on Medium]]></title>
        <description><![CDATA[Stories by Cameron Cruz on Medium]]></description>
        <link>https://medium.com/@cameroncruzin?source=rss-a0310dea18ff------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*iC0MCizY-yuaZYg_</url>
            <title>Stories by Cameron Cruz on Medium</title>
            <link>https://medium.com/@cameroncruzin?source=rss-a0310dea18ff------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 08:30:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cameroncruzin/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[Easy Image Classification with TensorFlow 2.0]]></title>
            <link>https://medium.com/data-science/easy-image-classification-with-tensorflow-2-0-f734fee52d13?source=rss-a0310dea18ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/f734fee52d13</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <dc:creator><![CDATA[Cameron Cruz]]></dc:creator>
            <pubDate>Tue, 02 Apr 2019 13:24:16 GMT</pubDate>
            <atom:updated>2019-04-02T13:24:16.613Z</atom:updated>
            <content:encoded><![CDATA[<h4>Getting started with TensorFlow 2.0 alpha’s improved high-level APIs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ni9QTN23XU2K5LjtzdObew.png" /></figure><h3>A Major Release with Major Benefits</h3><p>At the TensorFlow Dev Summit 2019, Google introduced the alpha version of TensorFlow 2.0. Historically, TensorFlow is considered the “industrial lathe” of machine learning frameworks: a powerful tool with intimidating complexity and a steep learning curve. If you’ve used TensorFlow 1.x in the past, you know what I’m talking about. This 2.0 release represents a concerted effort to improve the usability, clarity and flexibility of TensorFlow. Here are some highlights:</p><ul><li>Eager execution is enabled by default, without sacrificing the performance optimizations of graph-based execution.</li><li>APIs are cleaner, more consistent and less redundant.</li><li>Tighter Keras integration as the high-level API.</li><li><a href="https://www.tensorflow.org/community/roadmap">And more</a></li></ul><p>As a result, TensorFlow 2.0 is more Pythonic and less daunting to learn, while retaining the lower-level customization and complexity if you need it. Let’s get started with TensorFlow 2.0 by exploring how to apply its high-level APIs in a classic image classification setting.</p><h3>Install TensorFlow 2.0 alpha on Colab</h3><p><a href="https://colab.research.google.com/">Google Colaboratory</a> makes it really easy to setup Python notebooks in the cloud. With free access to a GPU for up to 12 hours at a time, Colab has quickly become my go-to platform for performing machine learning experiments.</p><p>Let’s install the TensorFlow 2.0 alpha release (GPU version) on a Colab notebook via pip.</p><pre>!pip install tensorflow-gpu==2.0.0-alpha0</pre><p>To verify it installed properly:</p><pre>import tensorflow as tf<br>print(tf.__version)</pre><pre># Output: 2.0.0-alpha0</pre><p>You should be good to go! If you run into issues, double check that your Colab runtime has “GPU” as the runtime accelerator in Edit&gt;Notebook settings.</p><h3>Load data using tf.data.Dataset</h3><p>Let’s use the dataset from the <a href="https://www.kaggle.com/c/aerial-cactus-identification">Aerial Cactus Identification</a> competition on Kaggle. Our task is to build a classifier capable of determining whether an aerial image contains a columnar cactus or not. This dataset is a modified version of the Cactus Aerial Photos dataset [1](Kaggle resized each image to 32x32 pixels).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/116/1*7jQjRGXeVvKrLCHyIMrC0w.jpeg" /><figcaption>Example image with cactus</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/128/1*Co0dk3PmgQA0dAg81AnQuA.png" /><figcaption>Example image with no cactus (upscaled 4x)</figcaption></figure><p>For example code on downloading/unzipping datasets from Kaggle, see the <a href="https://github.com/cameroncruz/notebooks/blob/master/Easy_Image_Classification_with_TF_2.ipynb">full notebook here</a>.</p><p>Let’s load the image file paths and their corresponding labels into lists using pandas, then create a train-validation split of 90–10 using sklearn.model_selection.</p><pre>train_csv = pd.read_csv(&#39;data/train.csv&#39;)</pre><pre># Prepend image filenames in train/ with relative path<br>filenames = [&#39;train/&#39; + fname for fname in train_csv[&#39;id&#39;].tolist()]<br>labels = train_csv[&#39;has_cactus&#39;].tolist()</pre><pre>train_filenames, val_filenames, train_labels, val_labels = <br>  train_test_split(filenames,<br>                 labels,<br>                 train_size=0.9,<br>                 random_state=42)</pre><p>Now that we have image filenames and labels split into training and validation sets, we can create respective tf.data.Dataset objects.</p><pre>train_data = tf.data.Dataset.from_tensor_slices(<br>  (tf.constant(train_filenames), tf.constant(train_labels))<br>)</pre><pre>val_data = tf.data.Dataset.from_tensor_slices(<br>  (tf.constant(val_filenames), tf.constant(val_labels))<br>)</pre><p>However, our dataset still contains just the image filenames, not the actual images. We need to define a function that can load the images from file and perform any necessary preprocessing. While we’re at it, let’s shuffle and batch the datasets, too.</p><pre>IMAGE_SIZE = 96 # Minimum image size for use with MobileNetV2</pre><pre>BATCH_SIZE = 32</pre><pre># Function to load and preprocess each image<br>def _parse_fn(filename, label):<br>    img = tf.io.read_file(img)<br>    img = tf.image.decode_jpeg(img)<br>    img = (tf.cast(img, tf.float32)/127.5) - 1<br>    img = tf.image.resize(img, (IMAGE_SIZE, IMAGE_SIZE))<br>    return img, label<br></pre><pre># Run _parse_fn over each example in train and val datasets<br># Also shuffle and create batches</pre><pre>train_data = (train_data.map(_parse_fn)<br>             .shuffle(buffer_size=10000)<br>             .batch(BATCH_SIZE)<br>             )</pre><pre>val_data = (val_data.map(_parse_fn)<br>           .shuffle(buffer_size=10000)<br>           .batch(BATCH_SIZE)<br>           )</pre><h3>Build model for transfer learning</h3><p>Transfer learning speeds up training by enabling us to reuse existing pre-trained image classification models, only retraining the top layer of the network that determines the classes an image can belong to [2].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*5F4b6ggZY7hlvGHxbrhTyA.png" /><figcaption>Diagram illustrating transfer learning</figcaption></figure><p>Let’s use TensorFlow 2.0’s high-level Keras API to quickly build our image classification model. For transfer learning, we can use a pre-trained MobileNetV2 model as the feature detector. MobileNetV2 is the second iteration of MobileNet released by Google with the goal of being smaller and more lightweight than models like ResNet and Inception for running on mobile devices [3]. Let’s load the MobileNetV2 model pre-trained on ImageNet without the top layer, freeze its weights, and add a new classification head.</p><pre>IMG_SHAPE = (IMAGE_SIZE, IMAGE_SIZE, 3)</pre><pre># Pre-trained model with MobileNetV2<br>base_model = tf.keras.applications.MobileNetV2(<br>    input_shape=IMG_SHAPE,<br>    include_top=False,<br>    weights=&#39;imagenet&#39;<br>)</pre><pre># Freeze the pre-trained model weights<br>base_model.trainable = False</pre><pre># Trainable classification head<br>maxpool_layer = tf.keras.layers.GlobalMaxPooling2D()<br>prediction_layer = tf.keras.layers.Dense(1, activation=&#39;sigmoid&#39;)</pre><pre># Layer classification head with feature detector<br>model = tf.keras.Sequential([<br>    base_model,<br>    maxpool_layer,<br>    prediction_layer<br>])</pre><pre>learning_rate = 0.0001</pre><pre># Compile the model<br>model.compile(optimizer=tf.keras.optimizers.Adam(lr=learning_rate), <br>              loss=&#39;binary_crossentropy&#39;,<br>              metrics=[&#39;accuracy&#39;]<br>)</pre><p>Note that it is recommended to use TensorFlow optimizers to train tf.keras models. In TensorFlow 2.0, the optimizers in the former tf.train and tf.keras.optimizers APIs have been unified under tf.keras.optimizers , where the original tf.keras optimizers have been replaced with upgraded TensorFlow optimizers [4]. Thus, applying TensorFlow optimizers is now a simpler and more consistent experience, fully supporting usage with the tf.keras API and not sacrificing performance.</p><h3>Train the model</h3><p>The tf.keras API in TensorFlow 2.0 now has full support for the tf.data API, so we can easily use our tf.data.Dataset objects when training the model [5]. Again, training is executed eagerly by default now without sacrificing the performance benefits of graph-based execution.</p><pre>num_epochs = 30<br>steps_per_epoch = round(num_train)//BATCH_SIZE<br>val_steps = 20</pre><pre>model.fit(train_data.repeat(),<br>          epochs=num_epochs,<br>          steps_per_epoch = steps_per_epoch,<br>          validation_data=val_data.repeat(), <br>          validation_steps=val_steps)</pre><p>After 30 epochs, the model’s validation accuracy increases from around 0.63 to 0.94.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*gNv90Sy4mmeuEpG_IuAlYQ.png" /><figcaption>Accuracy and loss over 30 epochs of transfer learning</figcaption></figure><h3>Fine-tune the model</h3><p>Let’s try to improve the accuracy of our model even further. When we applied transfer learning, we only trained the new classification head of the model, freezing the weights from MobileNetV2. If we didn’t freeze those weights initially, the model would “forget” all the knowledge it started with since the new classification head was randomly initialized [2]. However, now that we’ve trained the classification head first, we can unfreeze layers in the pre-trained model to fine-tune on this particular dataset.</p><pre><em># Unfreeze all layers of MobileNetV2</em><br>base_model.trainable = <strong>True</strong><br><br><em># Refreeze layers until the layers we want to fine-tune</em><br><strong>for</strong> layer <strong>in</strong> base_model.layers[:100]:<br>  layer.trainable =  <strong>False</strong></pre><pre># Use a lower learning rate<br>lr_finetune = learning_rate / 10</pre><pre># Recompile the model<br>model.compile(loss=&#39;binary_crossentropy&#39;,<br>              optimizer = tf.keras.optimizers.Adam(lr=lr_finetune),<br>              metrics=[&#39;accuracy&#39;])</pre><pre># Increase training epochs for fine-tuning<br>fine_tune_epochs = 30<br>total_epochs =  num_epochs + fine_tune_epochs<br></pre><pre># Fine-tune model<br># Note: Set initial_epoch to begin training after epoch 30 since we<br># previously trained for 30 epochs.</pre><pre>model.fit(train_data.repeat(), <br>          steps_per_epoch = steps_per_epoch,<br>          epochs=total_epochs, <br>          initial_epoch = num_epochs,<br>          validation_data=val_data.repeat(), <br>          validation_steps=val_steps)</pre><p>After an additional 30 epochs of fine-tuning, the model achieved a validation accuracy of 0.986. Based on the accuracy and loss graphs, more epochs may result in even greater improvements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*9Ez7YXASQSsGbnvvQ2k1eA.png" /><figcaption>Accuracy and loss with additional 30 epochs of fine-tuning</figcaption></figure><h3>Summary</h3><p>In this article, we looked at how TensorFlow 2.0&#39;s focus on usability, clarity and flexibility makes it much less daunting to get started with TensorFlow for machine learning experiments. Eager execution and improved high-level APIs abstract away much of TensorFlow’s usual complexity, making it much easier to quickly implement and run a quintessential image classification experiment.</p><p>At the time of writing, this is just the alpha release of TensorFlow 2.0, with a final release expected sometime later this year. Already, it’s apparent that the TensorFlow team is forging a significantly more intuitive iteration of TensorFlow. This is likely to improve the productivity of machine learning engineers across the board, reducing the usual amount of complexity while retaining lower-level control for those that need it. In addition, while TensorFlow was already a popular choice among machine learning experts, the smoother learning curve makes it a more attractive option for beginners as well.</p><p>Let me know what you think of TensorFlow 2.0 so far in the comments! Also, <strong>if you’re interested in the full code for this tutorial, </strong><a href="https://github.com/cameroncruz/notebooks/blob/master/Easy_Image_Classification_with_TF_2.ipynb"><strong>see the notebook here</strong></a>. If you have any questions, don’t hesitate to ask in the comments section, too.</p><h3>References</h3><p>This tutorial is inspired from the Transfer Learning Using Pretrained ConvNets on TensorFlow.org. To read the original tutorial, see <a href="https://www.tensorflow.org/alpha/tutorials/images/transfer_learning">here</a>.</p><p>[1] J. Vasquez-Gomez, <a href="https://www.kaggle.com/irvingvasquez/cactus-aerial-photos">Cactus Aerial Photos</a> (2019), Kaggle.com</p><p>[2] <a href="https://www.tensorflow.org/alpha/tutorials/images/transfer_learning">Transfer Learning Using Pretrained ConvNets</a> (2019), TensorFlow.org</p><p>[3] M. Sandler, A. Howard, M. Zhu, A. Zhmonginov, L. C. Chen, <a href="https://arxiv.org/pdf/1801.04381.pdf">MobileNetV2: Inverted Residuals and Linear Bottlenecks</a> (2019), Google Inc.</p><p>[4] F. Chollet, <a href="https://github.com/tensorflow/community/blob/master/rfcs/20181016-optimizer-unification.md">TensorFlow 2.0: Optimizer Unification</a> (2018), TensorFlow GitHub</p><p>[5] <a href="https://www.tensorflow.org/community/roadmap">Roadmap</a> (2019), TensorFlow.org</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f734fee52d13" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/easy-image-classification-with-tensorflow-2-0-f734fee52d13">Easy Image Classification with TensorFlow 2.0</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>