<?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 Catch Zeng on Medium]]></title>
        <description><![CDATA[Stories by Catch Zeng on Medium]]></description>
        <link>https://medium.com/@catchzeng?source=rss-fa22b6cbf9d1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*t8cAc7gKIwy3tsR8qZIIYA.jpeg</url>
            <title>Stories by Catch Zeng on Medium</title>
            <link>https://medium.com/@catchzeng?source=rss-fa22b6cbf9d1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 05:21:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@catchzeng/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[The easiest way to train a U-NET Image Segmentation model using TensorFlow and labelme]]></title>
            <link>https://catchzeng.medium.com/the-easiest-way-to-train-a-u-net-image-segmentation-model-using-tensorflow-and-labelme-fe130de45a19?source=rss-fa22b6cbf9d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe130de45a19</guid>
            <category><![CDATA[unet]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[labelme]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Catch Zeng]]></dc:creator>
            <pubDate>Sun, 10 Apr 2022 07:38:38 GMT</pubDate>
            <atom:updated>2022-05-05T02:44:31.871Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>From: </em></strong><a href="https://makeoptim.com/en/deep-learning/yiai-unet"><strong><em>https://makeoptim.com/en/deep-learning/yiai-unet</em></strong></a></p><h3>Foreword</h3><p>Earlier, I covered <a href="https://catchzeng.medium.com/train-a-custom-image-segmentation-model-using-tensorflow-object-detection-api-mask-r-cnn-a8cbfd2321e0">how to use Train a Custom Image Segmentation Model Using TensorFlow Object Detection API Mask R-CNN</a>. However, the Mask R-CNN network is more complex and has high-performance consumption. In practical applications, if it is not a very complex segmentation task, there is a more suitable choice, which is <a href="https://arxiv.org/abs/1505.04597">U-NET</a> to be explained in this article.</p><p>There are many articles about U-NET, but very few articles on custom datasets to model definition, training, and prediction. Therefore, this article aims to cover each step through a Demo, so that everyone can quickly master U-NET.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O3TV_roBue3TInzQwREvPA.gif" /></figure><h3>Installation</h3><p>Download the source code <a href="https://github.com/CatchZeng/tensorflow-unet-labelme">https://github.com/CatchZeng/tensorflow-unet-labelme</a> to your local and enter this directory.</p><p>If you are using <strong>macOS</strong>, you need to execute the following command before installation.</p><pre>❯ brew install pyqt</pre><p>Execute the following command to install the virtual environment named <strong>unet</strong>.</p><pre>❯ conda create -n unet -y python=3.9 &amp;&amp; conda activate unet &amp;&amp; pip install -r requirements.txt</pre><h3>Dataset</h3><p>The article is still used as an example of the cup, teapot, and humidifier in <a href="https://catchzeng.medium.com/train-a-custom-image-segmentation-model-using-tensorflow-object-detection-api-mask-r-cnn-a8cbfd2321e0">The easiest way to Train a Custom Image Segmentation Model Using TensorFlow Object Detection API Mask R-CNN</a>.</p><h3>Annotate images</h3><p>Data annotation has already been explained in <a href="https://catchzeng.medium.com/train-a-custom-image-segmentation-model-using-tensorflow-object-detection-api-mask-r-cnn-a8cbfd2321e0">The easiest way to Train a Custom Image Segmentation Model Using TensorFlow Object Detection API Mask R-CNN</a>, so I won’t repeat it here.</p><h3>Generate VOC format dataset</h3><p>U-NET dataset consists of raw images (jpg) and label (mask) images (png), usually using the VOC format to organize the dataset.</p><p>Store the labeled data in <strong><em>datasets/train</em></strong> of <strong><em>tensorflow-unet-labelme</em></strong>, and create a new <strong><em>datasets/labels.txt</em></strong> with the category names, see <a href="https://github.com/wkentaro/labelme/tree/main/examples/semantic_segmentation">https://github.com/wkentaro/labelme/tree/main/examples /semantic_segmentation.</a></p><pre>❯ tree -L 3<br>.<br>├── Makefile<br>├── README.md<br>├── datasets<br>│   ├── README.md<br>│   ├── labels.txt<br>│   ├── train<br>│   │   ├── 1.jpg<br>│   │   ├── 1.json<br>......<br>│   │   ├── 9.jpg<br>│   │   └── 9.json<br>├── labelme2voc.py<br>├── train.gif<br>├── unet.ipynb<br>└── voc_annotation.py</pre><blockquote>Note: You can refer to <a href="https://github.com/CatchZeng/tensorflow-unet-labelme/tree/master/datasets">https://github.com/CatchZeng/tensorflow-unet-labelme/tree/master/datasets</a> .</blockquote><p>Execute the following command to generate a VOC format dataset.</p><pre>❯ make voc</pre><pre>❯ tree -L 5<br>.<br>├── Makefile<br>├── README.md<br>├── datasets<br>│   ├── README.md<br>│   ├── labels.txt<br>│   ├── test<br>│   │   └── 1.jpg<br>│   ├── train<br>│   │   ├── 1.jpg<br>│   │   ├── 1.json<br>......<br>│   │   ├── 9.jpg<br>│   │   └── 9.json<br>│   └── train_voc<br>│       ├── ImageSets<br>│       │   └── Segmentation<br>│       │       ├── test.txt<br>│       │       ├── train.txt   # List of training set image names<br>│       │       ├── trainval.txt<br>│       │       └── val.txt  # list of validation set image names<br>│       ├── JPEGImages # raw images<br>│       │   ├── 1.jpg<br>......<br>│       │   └── 9.jpg<br>│       ├── SegmentationClass<br>│       │   ├── 1.npy<br>......<br>│       │   └── 9.npy<br>│       ├── SegmentationClassPNG # mask images<br>│       │   ├── 1.png<br>......<br>│       │   └── 9.png<br>│       ├── SegmentationClassVisualization<br>│       │   ├── 1.jpg<br>......<br>│       │   └── 9.jpg<br>│       └── class_names.txt<br>├── labelme2voc.py<br>├── train.gif<br>├── unet.ipynb<br>└── voc_annotation.py</pre><p>The generated <strong><em>datasets/train_voc</em></strong> is the dataset used for training.</p><h3>Training</h3><p>Open <strong><em>unet.ipynb</em></strong> and select the Python interpreter as <strong><em>unet</em></strong> to start training.</p><h3>Detailed code</h3><p>The dataset is divided into the training set and validation set, and files are read from <strong><em>ImageSets/Segmentation/train.txt</em></strong> and <strong><em>ImageSets/Segmentation/val.txt</em></strong> respectively. Then, it is constructed as a <strong><em>tf.keras.utils.Sequence</em></strong> object through the <strong><em>UnetDataset</em></strong> class, which is convenient for direct training through <strong><em>model.fit</em></strong> later.</p><pre>dataset_path = &#39;datasets/train_voc&#39;</pre><pre># read dataset txt files<br>with open(os.path.join(dataset_path, &quot;ImageSets/Segmentation/train.txt&quot;),<br>          &quot;r&quot;,<br>          encoding=&quot;utf8&quot;) as f:<br>    train_lines = f.readlines()</pre><pre>with open(os.path.join(dataset_path, &quot;ImageSets/Segmentation/val.txt&quot;),<br>          &quot;r&quot;,<br>          encoding=&quot;utf8&quot;) as f:<br>    val_lines = f.readlines()</pre><pre>train_batches = UnetDataset(train_lines, INPUT_SHAPE, BATCH_SIZE, NUM_CLASSES,<br>                            True, dataset_path)<br>val_batches = UnetDataset(val_lines, INPUT_SHAPE, BATCH_SIZE, NUM_CLASSES,<br>                          False, dataset_path)</pre><pre>STEPS_PER_EPOCH = len(train_lines) // BATCH_SIZE<br>VALIDATION_STEPS = len(val_lines) // BATCH_SIZE // VAL_SUBSPLITS</pre><p>The <strong><em>UnetDataset</em></strong> class inherits from <strong><em>tf.keras.utils.Sequence</em></strong> . Return a set of <strong><em>batch_size</em></strong> data through the <strong><em>__getitem__</em></strong> method, which includes the original image (images) and the label image (targets). Because the model has a fixed input shape, the resize operation is performed in the <strong><em>process_data</em></strong> method; during the training process, data enhancement can also be added, and a simple <strong><em>flip</em></strong> is used here</p><pre>class UnetDataset(tf.keras.utils.Sequence):</pre><pre>def __init__(self, annotation_lines, input_shape, batch_size, num_classes,<br>                 train, dataset_path):<br>        self.annotation_lines = annotation_lines<br>        self.length = len(self.annotation_lines)<br>        self.input_shape = input_shape<br>        self.batch_size = batch_size<br>        self.num_classes = num_classes<br>        self.train = train<br>        self.dataset_path = dataset_path</pre><pre>def __len__(self):<br>        return math.ceil(len(self.annotation_lines) / float(self.batch_size))</pre><pre>def __getitem__(self, index):<br>        images = []<br>        targets = []<br>        for i in range(index * self.batch_size, (index + 1) * self.batch_size):<br>            i = i % self.length<br>            name = self.annotation_lines[i].split()[0]<br>            jpg = Image.open(<br>                os.path.join(os.path.join(self.dataset_path, &quot;JPEGImages&quot;),<br>                             name + &quot;.jpg&quot;))<br>            png = Image.open(<br>                os.path.join(<br>                    os.path.join(self.dataset_path, &quot;SegmentationClassPNG&quot;),<br>                    name + &quot;.png&quot;))</pre><pre>jpg, png = self.process_data(jpg,<br>                                         png,<br>                                         self.input_shape,<br>                                         random=self.train)</pre><pre>images.append(jpg)<br>            targets.append(png)</pre><pre>images = np.array(images)<br>        targets = np.array(targets)<br>        return images, targets</pre><pre>def rand(self, a=0, b=1):<br>        return np.random.rand() * (b - a) + a</pre><pre>def process_data(self, image, label, input_shape, random=True):<br>        image = cvtColor(image)<br>        label = Image.fromarray(np.array(label))<br>        h, w, _ = input_shape</pre><pre># resize<br>        image, _, _ = resize_image(image, (w, h))<br>        label, _, _ = resize_label(label, (w, h))</pre><pre>if random:<br>            # flip<br>            flip = self.rand() &lt; .5<br>            if flip:<br>                image = image.transpose(Image.FLIP_LEFT_RIGHT)<br>                label = label.transpose(Image.FLIP_LEFT_RIGHT)</pre><pre># np<br>        image = np.array(image, np.float32)<br>        image = normalize(image)</pre><pre>label = np.array(label)<br>        label[label &gt;= self.num_classes] = self.num_classes</pre><pre>return image, label</pre><p>The model definition part is relatively simple, as in the paper, mainly <strong>downsampling</strong>, <strong>upsampling</strong>, and <strong>concat</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K5xjAikN1FoeNHY-.png" /></figure><p>Here, the author refers to <a href="https://www.tensorflow.org/tutorials/images/segmentation">https://www.tensorflow.org/tutorials/images/segmentation</a>, you can check the detailed analysis.</p><pre>def unet_model(output_channels: int):<br>    inputs = tf.keras.layers.Input(shape=INPUT_SHAPE)</pre><pre># Downsampling through the model<br>    skips = down_stack(inputs)<br>    x = skips[-1]<br>    skips = reversed(skips[:-1])</pre><pre># Upsampling and establishing the skip connections<br>    for up, skip in zip(up_stack, skips):<br>        x = up(x)<br>        concat = tf.keras.layers.Concatenate()<br>        x = concat([x, skip])</pre><pre># This is the last layer of the model<br>    last = tf.keras.layers.Conv2DTranspose(filters=output_channels,<br>                                           kernel_size=3,<br>                                           strides=2,<br>                                           padding=&#39;same&#39;)  #64x64 -&gt; 128x128</pre><pre>x = last(x)</pre><pre>return tf.keras.Model(inputs=inputs, outputs=x)</pre><p>In the <strong><em>Callback</em></strong> part, the author mainly uses <strong><em>DisplayCallback</em></strong> and <strong><em>ModelCheckpointCallback</em></strong>.</p><p><strong><em>DisplayCallback</em></strong> is used to display the predicted results after training an epoch, so as to observe the effect of the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O3TV_roBue3TInzQwREvPA.gif" /></figure><p><strong><em>ModelCheckpointCallback</em></strong> is used to save the weights (model) in the <strong><em>logs</em></strong> folder after training an epoch, and record the accuracy and loss rate after each epoch. In this way, the user can select a better model after training.</p><pre>def on_epoch_end(self, epoch, logs=None):<br>        clear_output(wait=True)<br>        show_predictions()<br>        print(&#39;\nSample Prediction after epoch {}\n&#39;.format(epoch + 1))</pre><pre>class ModelCheckpointCallback(tf.keras.callbacks.Callback):</pre><pre>def __init__(self,<br>                 filepath,<br>                 monitor=&#39;val_loss&#39;,<br>                 verbose=0,<br>                 save_best_only=False,<br>                 save_weights_only=False,<br>                 mode=&#39;auto&#39;,<br>                 period=1):<br>        super(ModelCheckpointCallback, self).__init__()<br>        self.monitor = monitor<br>        self.verbose = verbose<br>        self.filepath = filepath<br>        self.save_best_only = save_best_only<br>        self.save_weights_only = save_weights_only<br>        self.period = period<br>        self.epochs_since_last_save = 0</pre><pre>if mode not in [&#39;auto&#39;, &#39;min&#39;, &#39;max&#39;]:<br>            warnings.warn(<br>                &#39;ModelCheckpoint mode %s is unknown, &#39;<br>                &#39;fallback to auto mode.&#39; % (mode), RuntimeWarning)<br>            mode = &#39;auto&#39;</pre><pre>if mode == &#39;min&#39;:<br>            self.monitor_op = np.less<br>            self.best = np.Inf<br>        elif mode == &#39;max&#39;:<br>            self.monitor_op = np.greater<br>            self.best = -np.Inf<br>        else:<br>            if &#39;acc&#39; in self.monitor or self.monitor.startswith(&#39;fmeasure&#39;):<br>                self.monitor_op = np.greater<br>                self.best = -np.Inf<br>            else:<br>                self.monitor_op = np.less<br>                self.best = np.Inf</pre><pre>def on_epoch_end(self, epoch, logs=None):<br>        logs = logs or {}<br>        self.epochs_since_last_save += 1<br>        if self.epochs_since_last_save &gt;= self.period:<br>            self.epochs_since_last_save = 0<br>            filepath = self.filepath.format(epoch=epoch + 1, **logs)<br>            if self.save_best_only:<br>                current = logs.get(self.monitor)<br>                if current is None:<br>                    warnings.warn(<br>                        &#39;Can save best model only with %s available, &#39;<br>                        &#39;skipping.&#39; % (self.monitor), RuntimeWarning)<br>                else:<br>                    if self.monitor_op(current, self.best):<br>                        if self.verbose &gt; 0:<br>                            print(<br>                                &#39;\nEpoch %05d: %s improved from %0.5f to %0.5f,&#39;<br>                                &#39; saving model to %s&#39; %<br>                                (epoch + 1, self.monitor, self.best, current,<br>                                 filepath))<br>                        self.best = current<br>                        if self.save_weights_only:<br>                            self.model.save_weights(filepath, overwrite=True)<br>                        else:<br>                            self.model.save(filepath, overwrite=True)<br>                    else:<br>                        if self.verbose &gt; 0:<br>                            print(&#39;\nEpoch %05d: %s did not improve&#39; %<br>                                  (epoch + 1, self.monitor))<br>            else:<br>                if self.verbose &gt; 0:<br>                    print(&#39;\nEpoch %05d: saving model to %s&#39; %<br>                          (epoch + 1, filepath))<br>                if self.save_weights_only:<br>                    self.model.save_weights(filepath, overwrite=True)<br>                else:<br>                    self.model.save(filepath, overwrite=True)</pre><p>In the prediction model part, first, resize the file to the <strong><em>INPUT_SHAPE</em></strong> size of the model. It should be noted here that the predicted graph is not necessarily the same scale as <strong><em>INPUT_SHAPE</em></strong>. In order not to cause inaccurate prediction results due to the scale problem, the author adds <strong><em>gray placeholders</em></strong> for the place where the image is not proportional when resize, as shown in the following figure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/0*8P-wHvBc80NvEc-P.png" /></figure><p>Then after the prediction is finished, the <strong><em>gray placeholders</em></strong> is removed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/0*wcE0EEDu90j3kP9D.png" /></figure><blockquote>Note: Because the rendering of this case is a Demo, only 20 epochs are trained, and the accuracy is general. In practical applications, you can train more to improve the accuracy.</blockquote><pre>def detect_image(image_path):<br>    image = Image.open(image_path)<br>    image = cvtColor(image)</pre><pre>old_img = copy.deepcopy(image)<br>    ori_h = np.array(image).shape[0]<br>    ori_w = np.array(image).shape[1]</pre><pre># resize and add gray placeholders<br>    image_data, nw, nh = resize_image(image, (INPUT_SHAPE[1], INPUT_SHAPE[0]))</pre><pre>image_data = normalize(np.array(image_data, np.float32))</pre><pre>image_data = np.expand_dims(image_data, 0)</pre><pre>pr = model.predict(image_data)[0]</pre><pre>## remove gray placeholders<br>    pr = pr[int((INPUT_SHAPE[0] - nh) // 2) : int((INPUT_SHAPE[0] - nh) // 2 + nh), \<br>            int((INPUT_SHAPE[1] - nw) // 2) : int((INPUT_SHAPE[1] - nw) // 2 + nw)]</pre><pre>pr = cv2.resize(pr, (ori_w, ori_h), interpolation=cv2.INTER_LINEAR)</pre><pre>pr = pr.argmax(axis=-1)</pre><pre># seg_img = np.zeros((np.shape(pr)[0], np.shape(pr)[1], 3))<br>    # for c in range(NUM_CLASSES):<br>    #     seg_img[:, :, 0] += ((pr[:, :] == c ) * colors[c][0]).astype(&#39;uint8&#39;)<br>    #     seg_img[:, :, 1] += ((pr[:, :] == c ) * colors[c][1]).astype(&#39;uint8&#39;)<br>    #     seg_img[:, :, 2] += ((pr[:, :] == c ) * colors[c][2]).astype(&#39;uint8&#39;)<br>    seg_img = np.reshape(<br>        np.array(colors, np.uint8)[np.reshape(pr, [-1])], [ori_h, ori_w, -1])</pre><pre>image = Image.fromarray(seg_img)<br>    image = Image.blend(old_img, image, 0.7)</pre><pre>return image</pre><h3>Summary</h3><p>This article, through a demo, introduces how to create a data set to train a U-NET model and predict the picture, the entire process. You can find a scene by yourself, make a custom dataset, and practice it again to get a better grasp. That’s it for this article, see you in the next one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe130de45a19" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[软件修养 — 一篇搞定设计原则和 23 种设计模式]]></title>
            <link>https://catchzeng.medium.com/%E8%BD%AF%E4%BB%B6%E4%BF%AE%E5%85%BB-%E4%B8%80%E7%AF%87%E6%90%9E%E5%AE%9A%E8%AE%BE%E8%AE%A1%E5%8E%9F%E5%88%99%E5%92%8C-23-%E7%A7%8D%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-e1c7711b29a?source=rss-fa22b6cbf9d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1c7711b29a</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[design-principles]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Catch Zeng]]></dc:creator>
            <pubDate>Fri, 14 Jan 2022 07:01:00 GMT</pubDate>
            <atom:updated>2022-01-14T07:03:05.987Z</atom:updated>
            <content:encoded><![CDATA[<h3>软件修养 — 一篇搞定设计原则和 23 种设计模式</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*QxWjwhUEPg61Q7HOw9vIEw.jpeg" /></figure><p><a href="https://makeoptim.com/training/typescript-design-patterns"><strong>原文：https://makeoptim.com/training/typescript-design-patterns</strong></a></p><h3>前言</h3><p><strong>设计原则和设计模式是通用的知识点，无论你使用什么语言，皆可阅读，毫无阻碍</strong>。</p><blockquote>代码仓库：<a href="https://github.com/CatchZeng/typescript-design-patterns">https://github.com/CatchZeng/typescript-design-patterns</a></blockquote><h3>设计原则</h3><p><strong>设计原则（Design Principles）</strong>指的是<strong>抽象性比较高、编程都应该遵守的原则</strong>，对应的<strong>设计模式（Design Pattens）</strong>是解决<strong>具体场景</strong>下特定问题的<strong>套路</strong>，这里要对两个概念进行区分。换句话说，<strong>设计模式要遵循设计原则</strong>。</p><h3>单一职责原则（Single Responsibility Principle）</h3><p>一个类<strong>只负责一项职责</strong>（只有一个发生变化的原因）</p><p>详见<a href="https://makeoptim.com/training/single-responsibility-principle">软件修养 — 单一职责原则</a></p><h3>开闭原则（Open-Closed Principle）</h3><p>对<strong>扩展开放</strong>，对<strong>修改封闭</strong></p><p>详见<a href="https://makeoptim.com/training/open-closed-principle">软件修养 — 开闭原则</a></p><h3>里氏替换原则（Liskov Substitution Principle）</h3><p>基类适用的，子类一定适用（<strong>子类</strong>可以扩展父类的功能，但<strong>不能改变父类</strong>原有的功能）</p><p>详见<a href="https://makeoptim.com/training/liskov-substitution-principle">软件修养 — 里氏替换原则</a></p><h3>依赖倒置原则（Dependence Inversion Principle）</h3><p>依赖<strong>抽象</strong>，不要依赖具体（<strong>面向接口编程</strong>）</p><p>详见<a href="https://makeoptim.com/training/dependence-inversion-principle">软件修养 — 依赖倒置原则</a></p><h3>迪米特原则（Law Of Demeter）</h3><p>一个对象应该对其他对象尽可能少的了解（<strong>最少知道</strong>）</p><p>详见<a href="https://makeoptim.com/training/law-of-demeter-principle">软件修养 — 迪米特法则</a></p><h3>接口隔离原则（Interface Segregation Principle）</h3><p>使用多个<strong>专门的接口</strong>，而不要使用一个单一的（大）接口（<strong>接口单一职责</strong>）</p><p>详见<a href="https://makeoptim.com/training/interface-segregation-principle">软件修养 — 接口隔离原则</a></p><h3>组合/聚合复用原则 (Composite/Aggregate Reuse Principle)</h3><p>尽量使用<strong>组合/聚合</strong>，而<strong>不是继承</strong>。</p><p>详见<a href="https://makeoptim.com/training/composite-reuse-principle">软件修养 — 组合/聚合复用原则</a></p><h3>23 种常用设计模式</h3><h3>创建型</h3><h4><a href="https://github.com/CatchZeng/typescript-design-patterns/blob/master/src/factory-method/index.ts">工厂方法模式 (Factory Method)</a></h4><p>定义一个<strong>创建对象的接口</strong>，但让<strong>实现这个接口的类</strong>来决定<strong>实例化哪个类</strong>。工厂方法让类的实例化<strong>推迟到子类中进行</strong>。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*WllpDjcOC2UgXmBA.jpeg" /></figure><h4><a href="https://github.com/CatchZeng/typescript-design-patterns/blob/master/src/abstract-factory/index.ts">抽象工厂模式 (Abstract Factory)</a></h4><p>为一个<strong>产品族</strong>提供了<strong>统一的创建接口</strong>。当需要这个产品族的某一系列的时候，可以从抽象工厂中选出相应的系列创建一个具体的工厂类，而<strong>无需指定它们的具体类</strong>。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*egT-cTQWoysfR9iG.jpeg" /></figure><h4><a href="https://github.com/CatchZeng/typescript-design-patterns/blob/master/src/builder/index.ts">创建者/生成器模式 (Builder)</a></h4><p>将一个<strong>复杂对象</strong>的<strong>构建</strong>与它的<strong>表示分离</strong>，使得<strong>同样的构建过程</strong>可以创建<strong>不同的表示</strong>。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*qHSlqqkKnOBzFCsy.jpeg" /></figure><h4><a href="https://github.com/CatchZeng/typescript-design-patterns/blob/master/src/prototype/index.ts">原型模式 (Prototype)</a></h4><p>用原型实例<strong>指定</strong>创建对象的<strong>种类</strong>，并且通过<strong>拷贝</strong>这些原型,创建<strong>新的对象</strong>。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*OoqtZzC4viMnFETG.jpeg" /></figure><h4><a href="https://github.com/CatchZeng/typescript-design-patterns/blob/master/src/singleton/index.ts">单例模式 (Singleton)</a></h4><p>确保一个类<strong>只有一个实例</strong>，并提供对该实例的<strong>全局访问</strong>。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*PcZTc_meQ9W5nNVr.jpeg" /></figure><h3>结构型</h3><h4><a href="https://github.com/CatchZeng/typescript-design-patterns/blob/master/src/facade/index.ts">外观模式 (Facade)</a></h4><p>为子系统中的<strong>一组接口</strong>提供一个<strong>一致的界面</strong>，外观模式定义了一个<strong>高层接口</strong>，这个接口使得这一子系统<strong>更加容易使用</strong>。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/0*FRF9TGf1T7Lm8qXX.jpeg" /></figure><h4><a href="https://github.com/CatchZeng/typescript-design-patterns/blob/master/src/adapter/index.ts">适配器模式 (Adapter/Wrapper/Translator)</a></h4><p>将某个类的接口<strong>转换成客户端期望的</strong>另一个<strong>接口表示</strong>。适配器模式可以<strong>消除由于接口不匹配</strong>所造成的<strong>类兼容性问题</strong>。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*iCO2_XRJoCya3VQI.jpeg" /></figure><h4><a href="https://github.com/CatchZeng/typescript-design-patterns/blob/master/src/proxy/index.ts">代理模式 (Proxy)</a></h4><p>为其他对象提供一个<strong>代理</strong>以<strong>控制对这个对象的访问</strong>。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/0*h2yQKlJHfggoy8fh.jpeg" /></figure><h4><a href="https://github.com/CatchZeng/typescript-design-patterns/blob/master/src/composite/index.ts">组合模式 (Composite)</a></h4><p>把多个对象组成<strong>树状结构</strong>来表示<strong>局部</strong>与<strong>整体</strong>，这样用户可以<strong>一样的对待单个对象和对象的组合</strong>。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*woQXuOxvqaxvoBsS.jpeg" /></figure><h4><a href="https://github.com/CatchZeng/typescript-design-patterns/blob/master/src/flyweight/index.ts">享元模式 (Flyweight)</a></h4><p>通过<strong>共享</strong>以便有效的支持<strong>大量小颗粒对象</strong>。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*E9C7sFnC0e2-32pv.jpeg" /></figure><h4><a href="https://github.com/CatchZeng/typescript-design-patterns/blob/master/src/decorator/index.ts">装饰模式 (Decorator)</a></h4><p>向某个对象<strong>动态地添加更多的功能</strong>。修饰模式是<strong>除类继承</strong>外另一种<strong>扩展功能</strong>的方法。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/0*e5ul1ITKq9bwcgu-.jpeg" /></figure><h4><a href="https://github.com/CatchZeng/typescript-design-patterns/blob/master/src/bridge/index.ts">桥模式 (Bridge)</a></h4><p>将一个<strong>抽象与实现解耦</strong>，以便两者可以<strong>独立的变化</strong>。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/0*acqNs5mYNdLZwZCs.jpeg" /></figure><h3>行为型</h3><h4><a href="https://github.com/CatchZeng/typescript-design-patterns/blob/master/src/mediator/index.ts">中介者模式 (Mediator)</a></h4><p>包装了<strong>一系列对象相互作用</strong>的方式，使得这些对象<strong>不必相互明显作用</strong>，从而使它们可以<strong>松散偶合</strong>。当<strong>某些对象</strong>之间的<strong>作用</strong>发生<strong>改变</strong>时，<strong>不会立即影响其他的一些对象之间的作用</strong>，保证这些作用可以彼此<strong>独立的变化</strong>。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*_QqpgFV7lafxkENv.jpeg" /></figure><h4><a href="https://github.com/CatchZeng/typescript-design-patterns/blob/master/src/observer/index.ts">观察者模式 (Observer or Publish/subscribe)</a></h4><p>在对象间定义一个<strong>一对多</strong>的联系性，由此<strong>当一个对象改变</strong>了状态，所有其他<strong>相关的对象</strong>会被<strong>通知</strong>并且<strong>自动刷新</strong>。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*MRClogamM69fWOWY.jpeg" /></figure><h4><a href="https://github.com/CatchZeng/typescript-design-patterns/blob/master/src/command/index.ts">命令模式 (Command)</a></h4><p>将一个<strong>请求</strong>封装为一个<strong>对象</strong>，从而使你可用不同的请求对客户进行参数化；对请求排队或记录请求<strong>日志</strong>，以及支持<strong>可取消</strong>的操作。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/0*k_Z6juvL41yVqJFr.jpeg" /></figure><h4><a href="https://github.com/CatchZeng/typescript-design-patterns/blob/master/src/iterator/index.ts">迭代器模式 (Iterator)</a></h4><p>提供一种方法<strong>顺序访问</strong>一个<strong>聚合对象</strong>中<strong>各个元素</strong>, 而又<strong>不需暴露该对象的内部表示</strong>。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/0*ssTfFB59a3KdfJ0l.jpeg" /></figure><h4><a href="https://github.com/CatchZeng/typescript-design-patterns/blob/master/src/template-method/index.ts">模板方法模式 (Template Method)</a></h4><p>模板方法模式准备一个<strong>抽象类</strong>，将<strong>部分逻辑</strong>以<strong>具体方法</strong>及<strong>具体构造子类</strong>的形式实现，然后声明一些<strong>抽象方法</strong>来迫使子类<strong>实现剩余的逻辑</strong>。不同的子类可以以不同的方式实现这些抽象方法，从而对剩余的逻辑有不同的实现。先构建一个<strong>顶级逻辑框架</strong>，而将<strong>逻辑的细节</strong>留给具体的<strong>子类</strong>去实现。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*iUxd4Ij0oLQ1ygeX.jpeg" /></figure><h4><a href="https://github.com/CatchZeng/typescript-design-patterns/blob/master/src/strategy/index.ts">策略模式 (Strategy)</a></h4><p>定义一个<strong>算法的系列</strong>，将其各个<strong>分装</strong>，并且使他们<strong>有交互性</strong>。策略模式使得<strong>算法</strong>在用户使用的时候能<strong>独立的改变</strong>。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*lWBR4HfT842l4aCZ.jpeg" /></figure><h4><a href="https://github.com/CatchZeng/typescript-design-patterns/blob/master/src/state/index.ts">状态模式 (State)</a></h4><p>让一个对象在其<strong>内部状态</strong>改变的时候，其<strong>行为也随之改变</strong>。状态模式需要对每一个系统可能获取的<strong>状态</strong>创立一个<strong>状态类的子类</strong>。当系统的<strong>状态变化时</strong>，系统便<strong>改变所选的子类</strong>。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*_AnED8yYkVhN-PdG.jpeg" /></figure><h4><a href="https://github.com/CatchZeng/typescript-design-patterns/blob/master/src/memento/index.ts">备忘录模式 (Memento)</a></h4><p>备忘录对象是一个用来<strong>存储另外一个对象内部状态的快照</strong>的对象。备忘录模式的用意是在<strong>不破坏封装</strong>的条件下，将一个<strong>对象的状态捉住</strong>，并<strong>外部化</strong>，<strong>存储起来</strong>，从而可以在将来合适的时候把这个<strong>对象还原</strong>到存储起来的状态。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/0*TY8aWTaDY_qstLke.jpeg" /></figure><h4><a href="https://github.com/CatchZeng/typescript-design-patterns/blob/master/src/interpreter/index.ts">解释器模式 (Interpreter)</a></h4><p>给定一个语言, <strong>定义</strong>它的<strong>文法</strong>的一种表示，并定义一个<strong>解释器</strong>, 该解释器使用该表示来<strong>解释</strong>语言中的句子。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/0*vQgviXTrZ2TV61aa.jpeg" /></figure><h4><a href="https://github.com/CatchZeng/typescript-design-patterns/blob/master/src/chain-of-responsibility/index.ts">职责链模式 (Chain of Responsibility)</a></h4><p>为解除请求的<strong>发送者</strong>和<strong>接收者</strong>之间耦合，而使<strong>多个对象都有机会处理这个请求</strong>。将这些对象连成一条链，并沿着这条<strong>链传递</strong>该请求，<strong>直到有一个对象处理它</strong>。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*mLGALneJVsLyP2pX.jpeg" /></figure><h4><a href="https://github.com/CatchZeng/typescript-design-patterns/blob/master/src/visitor/index.ts">访问者模式 (Visitor)</a></h4><p>封装一些施加于某种<strong>数据结构元素之上的操作</strong>。一旦这些操作<strong>需要修改</strong>，接受这个操作的<strong>数据结构可以保持不变</strong>。访问者模式适用于<strong>数据结构相对未定的系统</strong>，它把<strong>数据结构</strong>和<strong>作用于结构上的操作</strong>之间的耦合解脱开，使得<strong>操作集合</strong>可以相对<strong>自由的演化</strong>。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*9UWDOO09ue8ruD5_.jpeg" /></figure><h3>参考链接</h3><ul><li><a href="https://en.wikipedia.org/wiki/Design_Patterns">https://en.wikipedia.org/wiki/Design_Patterns</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1c7711b29a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Neural Style Transfer Online & Free Tool]]></title>
            <link>https://catchzeng.medium.com/neural-style-transfer-online-free-tool-28fbaeb3aaa1?source=rss-fa22b6cbf9d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/28fbaeb3aaa1</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[style-transfer]]></category>
            <category><![CDATA[tensorflowjs]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Catch Zeng]]></dc:creator>
            <pubDate>Thu, 18 Nov 2021 02:57:58 GMT</pubDate>
            <atom:updated>2021-11-18T02:57:58.947Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://style-transfer.makeoptim.com/">Makeoptim’s style transfer Tool</a></h3><p><a href="https://style-transfer.makeoptim.com/">https://style-transfer.makeoptim.com/</a></p><p>Create artistic images in a single tap.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*D8Gogjj_-LFHT-xT.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iILWpqEqoPsWnTwh.gif" /></figure><h3>Features</h3><ul><li><strong>Multiple modes</strong> are available</li><li>Adjustable <strong>stylization strength</strong></li><li>Many <strong>pre-made pictures</strong></li><li>Support <strong>uploading pictures</strong></li></ul><h3>How to Use</h3><h3>Select or Upload The Content Image</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*-YsecPbfrLWv24jJ.png" /></figure><h3>Select or Upload The Style Image</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*WleXNlt-9vs5-jCK.png" /></figure><h3>Stylize</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*DPGdUhsXA6lT_ESC.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28fbaeb3aaa1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy image segmentation (Mask R-CNN) model service using TensorFlow Serving & Flask]]></title>
            <link>https://catchzeng.medium.com/deploy-image-segmentation-mask-r-cnn-model-service-using-tensorflow-serving-flask-808c308dc9bc?source=rss-fa22b6cbf9d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/808c308dc9bc</guid>
            <category><![CDATA[tensorflow-serving]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[mask-rcnn]]></category>
            <category><![CDATA[object-detection-api]]></category>
            <category><![CDATA[image-segmentation]]></category>
            <dc:creator><![CDATA[Catch Zeng]]></dc:creator>
            <pubDate>Tue, 19 Oct 2021 03:41:53 GMT</pubDate>
            <atom:updated>2022-02-21T08:53:51.772Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deploy image segmentation (Mask R-CNN) model service with TensorFlow Serving &amp; Flask</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*Bcdq7QbEV249Kmb8.jpeg" /></figure><p><strong><em>From </em></strong><a href="https://makeoptim.com/en/deep-learning/yiai-serving-flask-mask-rcnn"><strong><em>https://makeoptim.com/en/deep-learning/yiai-serving-flask-mask-rcnn</em></strong></a></p><h3>Foreword</h3><p><a href="https://makeoptim.com/en/deep-learning/yiai-image-segmentation">The Previous article</a> introduced how to <strong>train and export an image segmentation model</strong>. After getting the model, I will use it. The following will show how to deploy an image segmentation model service using <a href="https://github.com/tensorflow/serving">TensorFlow Serving</a> and <a href="https://flask.palletsprojects.com/">Flask</a>.</p><h3>TensorFlow Serving</h3><p><a href="https://github.com/tensorflow/serving">TensorFlow Serving</a> is a flexible, high-performance serving system for machine learning models, designed for production environments. It deals with the <strong>inference</strong> aspect of machine learning, taking <strong>models after training</strong> and <strong>managing their lifetimes</strong>, providing clients with versioned access via a <strong>high-performance, reference-counted lookup table</strong>. <a href="https://github.com/tensorflow/serving">TensorFlow Serving</a> provides <strong>out-of-the-box</strong> integration with TensorFlow models but can be easily extended to serve <strong>other types of models and data</strong>.</p><h3>Features</h3><ul><li>Can serve multiple models, or <strong>multiple versions</strong> of the same model simultaneously</li><li>Exposes both <strong>gRPC</strong> as well as <strong>HTTP</strong> inference endpoints</li><li>Allows deployment of new model versions <strong>without changing any client code</strong></li><li>Supports <strong>canarying new versions</strong> and <strong>A/B testing</strong> experimental models</li><li>Adds minimal latency to inference time due to efficient, <strong>low-overhead</strong> implementation</li><li>Features a <strong>scheduler</strong> that groups individual inference requests into batches for joint execution on GPU, with configurable latency controls</li><li>Supports <strong>many servables</strong>: Tensorflow models, embeddings, vocabularies, feature transformations, and even non-Tensorflow-based machine learning models</li></ul><h3>Usage</h3><p>It is recommended that you use <a href="https://github.com/tensorflow/serving">TensorFlow Serving</a> based on <a href="https://www.docker.com/">Docker</a>.</p><h4>Quick Start</h4><pre># Download the TensorFlow Serving Docker image and repo<br>docker pull tensorflow/serving</pre><pre>git clone https://github.com/tensorflow/serving<br># Location of demo models<br>TESTDATA=&quot;$(pwd)/serving/tensorflow_serving/servables/tensorflow/testdata&quot;</pre><pre># Start TensorFlow Serving container and open the REST API port<br>docker run -t --rm -p 8501:8501 \<br>    -v &quot;$TESTDATA/saved_model_half_plus_two_cpu:/models/half_plus_two&quot; \<br>    -e MODEL_NAME=half_plus_two \<br>    tensorflow/serving &amp;</pre><pre># Query the model using the predict API<br>curl -d &#39;{&quot;instances&quot;: [1.0, 2.0, 5.0]}&#39; \<br>    -X POST http://localhost:8501/v1/models/half_plus_two:predict</pre><pre># Returns =&gt; { &quot;predictions&quot;: [2.5, 3.0, 4.5] }</pre><pre># Clean<br>$ docker rm -f serving-test</pre><blockquote>Note:</blockquote><ul><li>gRPC public port 8500</li><li>REST API public port 8501</li><li>Optional environment variable MODEL_NAME (default is model)</li><li>Optional environment variable MODEL_BASE_PATH (default is /models)</li></ul><h4>Create an image</h4><p>Create your own model image based on tensorflow/serving.</p><pre>$ docker run -d --name serving_base tensorflow/serving<br># Copy the model to the serving_base container<br>$ docker cp $TESTDATA/saved_model_half_plus_two_cpu serving_base:/models/half_plus_two<br># Set the model name environment variable, and submit the container after modifying the serving_base as half_plus_two<br>$ docker commit --change &quot;ENV MODEL_NAME half_plus_two&quot; serving_base half_plus_two<br>$ docker rm -f serving_base</pre><p>Run the image</p><pre>$ docker run --name=half_plus_two -d -p 8501:8501 half_plus_two</pre><pre># Request model predict API<br>$ curl -d &#39;{&quot;instances&quot;: [1.0, 2.0, 5.0]}&#39; \<br>    -X POST http://localhost:8501/v1/models/half_plus_two:predict<br># Returns =&gt; { &quot;predictions&quot;: [2.5, 3.0, 4.5] }</pre><pre># Clean<br>$ docker rm -f half_plus_two</pre><h3>Image segmentation Serving Docker image</h3><p>After introducing the basic usage of <a href="https://github.com/tensorflow/serving">TensorFlow Serving</a>, here is <strong>how to build a Serving Docker image</strong>.</p><h3>Create an image</h3><p><a href="https://makeoptim.com/deep-learning/yiai-image-segmentation#%E6%A8%A1%E5%9E%8B%E5%AF%BC%E5%87%BA">After the model is exported</a>, the following model files can be obtained.</p><pre>test-mask<br>├── exported-models<br>│   └── mask_rcnn_inception_resnet_v2_1024x1024_coco17_gpu-8<br>│       ├── checkpoint<br>│       │   ├── checkpoint<br>│       │   ├── ckpt-0.data-00000-of-00001<br>│       │   └── ckpt-0.index<br>│       ├── pipeline.config<br>│       └── saved_model<br>│           ├── assets<br>│           ├── saved_model.pb<br>│           └── variables</pre><blockquote>If it is not convenient for you to train the model, you can go to <a href="https://github.com/CatchZeng/object-detection-api/releases/tag/exported-models">https://github.com/CatchZeng/object-detection-api/releases/tag/exported-models</a> to download the model of test-mask and proceed to the next steps.</blockquote><p>Execute the following command to create a Serving Docker image.</p><pre>$ make serving<br>docker pull tensorflow/serving<br>Using default tag: latest<br>latest: Pulling from tensorflow/serving<br>Digest: sha256:6651f4839e1124dbde75ee531825112af0a6b8ef082c88ab14ca53eb69a2e4bb<br>Status: Image is up to date for tensorflow/serving:latest<br>docker.io/tensorflow/serving:latest<br>docker run -d --name serving_base tensorflow/serving<br>7239e7a1b83ba7b5c4244973f2b327ba703d19fcdfc451e52221179772a9e61b<br># https://stackoverflow.com/a/45552938/14785930<br>docker exec -it serving_base mkdir -p /models/test-mask/1<br>docker cp exported-models/mask_rcnn_inception_resnet_v2_1024x1024_coco17_gpu-8/saved_model/. serving_base:/models/test-mask/1<br>docker commit --change &quot;ENV MODEL_NAME test-mask&quot; serving_base test-mask<br>sha256:20a3d099a6ce03dad70003752c70b68aeda706c1e6d5434e6b9d945098ab692c<br>docker rm -f serving_base<br>serving_base</pre><pre>$ docker images<br>REPOSITORY                 TAG                  IMAGE ID       CREATED             SIZE<br>test-mask                  latest               20a3d099a6ce   10 seconds ago      663MB</pre><h3>Local debugging</h3><p>Start Serving</p><pre>$ docker run -d --name test-mask --rm -p 8500:8500 -p 8501:8501 test-mask</pre><p>Copy a test picture to images/test and name it test.jpg, then execute the following command to test Serving.</p><pre>$ make serving-test<br>python deployments/serving/client.py<br>start request<br>duration: 17.50s<br>......<br>annotated image is saved to /Users/catchzeng/Documents/Code/CatchZeng/object-detection-api/workspace/test-mask/images/test/test_annotated.jpg</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*jBNpaWJObCOtEQJ2.jpg" /></figure><h3>Flask</h3><p>After creating the model image, an <strong>ingress service</strong> is needed to do <strong>external API design</strong> and <strong>input data preprocessing</strong>, usually <a href="https://flask.palletsprojects.com%20/">Flask</a>.</p><p><a href="https://flask.palletsprojects.com/">Flask</a> is a <strong>lightweight</strong> customizable web application framework written in Python language, which is more <strong>flexible, lighter, and safer than other similar frameworks And easy to get started</strong>.</p><h3>Installation</h3><pre>$ conda activate od<br>$ pip install Flask</pre><h3>Usage</h3><p>Create app.py</p><pre># app.py<br>from flask import Flask</pre><pre>app = Flask(__name__)<br></pre><pre>@app.route(&quot;/&quot;)<br>def hello_world():<br>    return &quot;It works!&quot;</pre><p>Run</p><pre>$ python -m flask run</pre><pre>* Environment: production<br>   WARNING: This is a development server. Do not use it in a production deployment.<br>   Use a production WSGI server instead.<br> * Debug mode: off<br> * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)</pre><p>Request</p><pre>❯ curl http://127.0.0.1:5000<br>It works!</pre><blockquote>For more examples of getting started, please see <a href="https://flask.palletsprojects.com/en/2.0.x/quickstart/">https://flask.palletsprojects.com/en/2.0.x/quickstart/</a>.</blockquote><h3>Image segmentation ingress service</h3><h3>Create an image</h3><p>Execute the following command to build the Flask image segmentation ingress service image.</p><pre>$ make flask<br>cp annotations/label_map.pbtxt deployments/flask<br>cd deployments/flask &amp;&amp; make build<br>DOCKER_BUILDKIT=0 docker build --tag test-mask-flask .<br>Sending build context to Docker daemon  66.05kB<br>Step 1/6 : FROM python:3.8-slim-buster<br> ---&gt; 09c82f264230<br>Step 2/6 : WORKDIR /app<br> ---&gt; Using cache<br> ---&gt; 38fe51c7abd9<br>Step 3/6 : RUN pip3 install --no-cache-dir Flask pillow tensorflow==2.6.0<br> ---&gt; Using cache<br> ---&gt; 7d5da785bd60<br>Step 4/6 : COPY . .<br> ---&gt; Using cache<br> ---&gt; f65126d49639<br>Step 5/6 : RUN rm -rf .vscode README.md Dockerfile Makefile<br> ---&gt; Using cache<br> ---&gt; eb6dc93afc91<br>Step 6/6 : CMD [ &quot;python3&quot;, &quot;-m&quot; , &quot;flask&quot;, &quot;run&quot;, &quot;--host=0.0.0.0&quot;]<br> ---&gt; Using cache<br> ---&gt; 3991ff08b36f<br>Successfully built 3991ff08b36f<br>Successfully tagged test-mask-flask:latest</pre><pre>Use &#39;docker scan&#39; to run Snyk tests against images to find vulnerabilities and learn how to fix them</pre><blockquote>!!! workspace/test-mask/deployments/flask/object_detection is part of the code extracted from <a href="https://github.com/tensorflow/models/tree/master/research/object_detection">TensorFlow Object Detection API</a>. Benefits When create a Docker image, <strong>you don’t need to install the TensorFlow Object Detection API, which can reduce the size of the generated image (about 2G)</strong>.</blockquote><h3>Start service</h3><p>Start the ingress service</p><pre>$ docker run -d --name test-mask-flask --rm -p 5000:5000 --link test-mask:test-mask -e SERVER_URL=&quot;http://test-mask:8501/v1/models/test-mask:predict&quot; test-mask-flask</pre><pre>$ docker ps<br>CONTAINER ID   IMAGE             COMMAND                  CREATED         STATUS         PORTS                              NAMES<br>1c78f0e1f31e   test-mask-flask   &quot;python3 -m flask ru…&quot;   2 seconds ago   Up 2 seconds   0.0.0.0:5000-&gt;5000/tcp             test-mask-flask<br>c48d559ab6c5   test-mask         &quot;/usr/bin/tf_serving…&quot;   3 minutes ago   Up 3 minutes   0.0.0.0:8500-8501-&gt;8500-8501/tcp   test-mask</pre><p>Initiate a request</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JcxxW0-kMY3iCuJ7.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/0*Sa4C7PSuPxOHOGzA.jpg" /></figure><h3>Deploy</h3><p>If you use Nginx to deploy, you can refer to <a href="https://github.com/CatchZeng/object-detection-api/blob/master/scripts/workspace/mask/files/deployments/flask/nginx.conf">https://github.com/CatchZeng/object-detection-api/blob/master/scripts/workspace/mask/files/deployments/flask/nginx.conf</a>.</p><pre>server {<br>    listen 80;<br>    listen 443 ssl;<br>    server_name api.makeoptim.com;<br>    ssl_certificate      /etc/nginx/keys/api.makeoptim.com.pem;<br>    ssl_certificate_key  /etc/nginx/keys/api.makeoptim.com.key;</pre><pre>    location / {<br>            proxy_set_header Host $host;<br>            proxy_set_header X-Real-IP $remote_addr;<br>            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>            proxy_pass http://127.0.0.1:5000/;<br>    }<br>}</pre><h3>Summary</h3><p>This article describes how to deploy an image segmentation model service using <a href="https://github.com/tensorflow/serving">TensorFlow Serving</a> and <a href="https://flask.palletsprojects.com/">Flask</a>, here One step, the <strong>model</strong> is the <strong>real delivery</strong>, I hope it can help you apply the trained model <strong>to actual projects</strong>. That’s it for this article, see you next.</p><h3>Further reading</h3><ul><li><a href="https://makeoptim.com/en/deep-learning/yiai-image-segmentation">The easiest way to Train a Custom Image Segmentation Model Using TensorFlow Object Detection API Mask R-CNN</a></li><li><a href="https://makeoptim.com/en/deep-learning/yiai-object-detection">The easiest way to Train a Custom Object Detection Model Using TensorFlow Object Detection API</a></li></ul><h3>Reference</h3><ul><li><a href="https://github.com/tensorflow/serving">https://github.com/tensorflow/serving</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=808c308dc9bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The easiest way to Train a Custom Image Segmentation Model Using TensorFlow Object Detection API…]]></title>
            <link>https://catchzeng.medium.com/train-a-custom-image-segmentation-model-using-tensorflow-object-detection-api-mask-r-cnn-a8cbfd2321e0?source=rss-fa22b6cbf9d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8cbfd2321e0</guid>
            <category><![CDATA[object-detection-api]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[mask-r-cnn]]></category>
            <category><![CDATA[image-segmentation]]></category>
            <category><![CDATA[labelme]]></category>
            <dc:creator><![CDATA[Catch Zeng]]></dc:creator>
            <pubDate>Sat, 18 Sep 2021 10:12:19 GMT</pubDate>
            <atom:updated>2022-01-06T11:57:51.268Z</atom:updated>
            <content:encoded><![CDATA[<h3>The easiest way to Train a Custom Image Segmentation Model Using TensorFlow Object Detection API Mask R-CNN</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*6oJgZbaMFzmumHsG.jpeg" /></figure><p><strong><em>From: </em></strong><a href="https://makeoptim.com/en/deep-learning/yiai-image-segmentation"><strong><em>https://makeoptim.com/en/deep-learning/yiai-image-segmentation</em></strong></a></p><h3>Foreword</h3><p><a href="https://makeoptim.com/deep-learning/yiai-object-detection">The Previous article</a> introduces <strong>Object Detection</strong>. This article will introduce the concept of <strong>Image Segmentation</strong>, and explain how to train a <strong>custom image segmentation model</strong> using <a href="https://github.com/tensorflow/models/tree/master/research/object_detection">TensorFlow Object Detection API</a> through cases, including <strong>data set collection and processing, TensorFlow Object Detection API installation, and model training</strong>.</p><p>The case effect is shown in the figure below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*8g0Xx4BjBi1mJ-LK.jpg" /></figure><h3>Image Segmentation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/0*iCT3Wl9pYkRGv_Yj.jpg" /></figure><p>As shown in the figure above, <strong>Object Detection</strong> recognizes <strong>Objects</strong> in the image and detects their <strong>location</strong>, and <strong>Image Segmentation</strong> is divided into the following three types:</p><ul><li><strong>Semantic Segmentation</strong>: <strong>Tag each pixel in the image with a category label</strong>. As shown above, the image is divided into people (red), trees (dark green), grass (light green), and sky (blue) labels.</li><li><strong>Instance Segmentation</strong>: <strong>The combination of Object Detection and Semantic Segmentation</strong>, the object is detected in the image (Object Detection), and then each pixel is labeled (Semantic Segmentation). As shown in the figure above, people are the object, <strong>Semantic Segmentation does not distinguish different instances belonging to the same category</strong> (all are marked in red), <strong>Instance Segmentation distinguishes different instances of the same type</strong> (use different colors to distinguish different people).</li><li><strong>Panoptic Segmentation</strong>: <strong>The combination of Semantic Segmentation and Instance Segmentation</strong> means that all objects must be detected and different instances in the same category must be distinguished. As shown in the above figure, <strong>Instance Segmentation only detects the target in the image (such as the person in the image above) and segmentation by pixel</strong> to distinguish different instances (using different colors), while <strong>Panoptic Segmentation is for all objects in the image The background must be detected and segmented</strong> to distinguish between different instances (using different colors).</li></ul><p><a href="https://arxiv.org/abs/1703.06870">Mask R-CNN</a> to be used in this article is an <strong>Instance Segmentation</strong> model.</p><h3>TensorFlow Object Detection API</h3><p>The installation of <a href="https://github.com/tensorflow/models/tree/master/research/object_detection">TensorFlow Object Detection API</a> is consistent with the Object Detection, please refer to <a href="https://makeoptim.com/en/deep-learning/yiai-object-detection#tensorflow-object-detection-api">Previous</a>, so I won’t repeat it here.</p><h3>Create workspace</h3><blockquote>Note: !!! From here, please make sure to execute under the environment of conda od.</blockquote><pre>$ conda activate od<br>$ conda env list<br># conda environments:<br>#<br>od                    *  /Users/catchzeng/.conda/envs/od<br>tensorflow               /Users/catchzeng/.conda/envs/tensorflow<br>base                     /Users/catchzeng/miniconda3</pre><p>Go to the oda repo directory and execute the following command to create the workspace directory structure.</p><blockquote>Note: SAVE_DIR is the directory to save the workspace, and NAME is the name of the workspace.</blockquote><pre>$ make workspace-mask SAVE_DIR=workspace NAME=test-mask</pre><pre>└── workspace<br>    └── test-mask<br>        ├── COCO_Image_Viewer.ipynb: Used to verify the successful conversion to COCO format<br>        ├── Makefile<br>        ├── annotations: Store the labeled data set, including val.record, train.record, label_map.pbtxt<br>        ├── create_coco_tf_record.py: Convert COCO format files to TFRecord<br>        ├── deployments: deploy model service<br>        │   ├── flask：Flask ingress service<br>        │   └── serving: Tensorflow Serving<br>        ├── exported-models: Store the exported model after training<br>        ├── exporter_main_v2.py: the script to export model<br>        ├── images: Data set images and json annotations<br>        │   ├── test: Store manual verification images<br>        │   ├── train: Training set images and json annotations<br>        │   └── val: Evaluation set images and json annotations<br>        ├── labelme2coco.py: Convert labelme json file to COCO format<br>        ├── model_main_tf2.py: the script to train model<br>        ├── models: Custom model<br>        ├── pre-trained-models: pre-trained models<br>        └── test_images.py: the script to verify the image manually</pre><h3>Dataset</h3><h3>Images</h3><p>Here we still use a <strong>cup, teapot, and humidifier</strong> as examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*Fw_Y4dDGWyIzYMk0.jpg" /></figure><p>Put the collected pictures into the three subdirectories of images in the project directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/0*Oxi9hqzNBPwu1Q8D.jpg" /></figure><blockquote>Note: This case is just to show how to train the Object Detection model, so the dataset is relatively small. In the production, remember to <strong>collect as many datasets as possible</strong>.</blockquote><h3>Annotation</h3><p>After collecting the pictures, you need to annotate the images in the <strong>training</strong> and <strong>evaluation</strong> sets.</p><p>We choose <a href="https://github.com/wkentaro/labelme">labelme</a> as the annotation tool.</p><p>Install labelme according to the instructions of <a href="https://github.com/wkentaro/labelme#installation">installation</a>, then execute labelme to select the train and val folders for annotation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*_VZzr8hN6AAzzwKI.jpg" /></figure><p>After the annotation is completed, the json annotation file corresponding to the image will be generated, as shown below:</p><pre>workspace/test-mask/images<br>├── test<br>│   ├── 15.jpg<br>│   └── 16.jpg<br>├── train<br>│   ├── 1.jpg<br>│   ├── 1.json<br>│   ├── 10.jpg<br>│   ├── 10.json<br>│   ├── 2.jpg<br>│   ├── 2.json<br>│   ├── 3.jpg<br>│   ├── 3.json<br>│   ├── 4.jpg<br>│   ├── 4.json<br>│   ├── 5.jpg<br>│   ├── 5.json<br>│   ├── 6.jpg<br>│   ├── 6.json<br>│   ├── 7.jpg<br>│   ├── 7.json<br>│   ├── 8.jpg<br>│   ├── 8.json<br>│   ├── 9.jpg<br>│   └── 9.json<br>└── val<br>    ├── 11.jpg<br>    ├── 11.json<br>    ├── 12.jpg<br>    ├── 12.json<br>    ├── 13.jpg<br>    ├── 13.json<br>    ├── 14.jpg<br>    └── 14.json</pre><h3>Generate TFRecord and label_map</h3><p><a href="https://github.com/tensorflow/models/tree/master/research/object_detection">TensorFlow Object Detection API</a> only supports <a href="https://www.tensorflow.org/api_docs/python/tf/data/TFRecordDataset">TFRecord</a> format, therefore, the dataset needs to be converted.</p><p>Go to the workspace directory (cd workspace/test-mask), and then execute make gen-tfrecord, it will generate <a href="https://www.tensorflow.org/api_docs/python/tf/data/TFRecordDataset">TFRecord</a> format dataset in the annotations folder.</p><pre>$ make gen-tfrecord<br>python labelme2coco.py images/train --output images/train.json<br>save coco json<br>images/train.json<br>python labelme2coco.py images/val --output images/val.json<br>save coco json<br>images/val.json<br>python create_coco_tf_record.py --logtostderr \<br>        --train_image_dir=images/train \<br>        --val_image_dir=images/val \<br>        --train_annotations_file=images/train.json \<br>        --val_annotations_file=images/val.json \<br>        --include_masks=True \<br>        --output_dir=./annotations<br>......<br>python gen_label_map.py<br>item {<br>  id: 1<br>  name: &#39;cup&#39;<br>}<br><br>item {<br>  id: 2<br>  name: &#39;humidifier&#39;<br>}<br><br>item {<br>  id: 3<br>  name: &#39;teapot&#39;<br>}</pre><pre>annotations<br>├── label_map.pbtxt<br>├── train.record<br>└── val.record</pre><blockquote>Note: If you want to verify whether labelme json is successfully converted to COCO format, you can run COCO_Image_Viewer.ipynb to view the result.</blockquote><h3>Model training</h3><blockquote>Note: !!! From here, please make sure you have go to the workspace directory (cd workspace/test-mask).</blockquote><h3>Download the pre-trained model</h3><p>Select the appropriate model from <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/tf2_detection_zoo.md">Model Zoo</a>, download and unzip it, and put it in workspace/test/pre-trained-models.</p><p>The default selection here is mask_rcnn_inception_resnet_v2_1024x1024_coco17_gpu-8 You can execute the following commands to automatically download and decompress</p><pre>$ make dl-model</pre><p>The directory structure is as follows:</p><pre>└── test-mask<br>    └── pre-trained-models<br>        └── mask_rcnn_inception_resnet_v2_1024x1024_coco17_gpu-8<br>            ├── checkpoint<br>            ├── pipeline.config<br>            └── saved_model</pre><h3>Configure training pipeline</h3><p>Create a corresponding model folder in the models directory, such as: mask_rcnn_inception_resnet_v2_1024x1024_coco17_gpu-8, and copy pre-trained-models/mask_rcnn_inception_resnet_v2_1024x1024_coco17_gpu-8/pipeline.config.</p><pre>└── test-mask<br>    ├── models<br>    │   └── mask_rcnn_inception_resnet_v2_1024x1024_coco17_gpu-8<br>    │       └── pipeline.config<br>    └── pre-trained-models</pre><p>Among them, pipeline.config needs to be modified according to the project as follows</p><pre>model {<br>  faster_rcnn {<br>    num_classes: 3 # Modify to the number of objects that need to be identified.<br>    ......<br>    first_stage_max_proposals: 100 # Faster R-CNN has two networks, the first proposes regions where objects may be found and the second tries to detect objects in those. Increasing the number of proposals by the first network increases the accuracy but implies more computational work, because the second network has to search in more potential areas.<br>    second_stage_post_processing {<br>      batch_non_max_suppression {<br>        score_threshold: 0.0<br>        iou_threshold: 0.6<br>        max_detections_per_class: 2 # The maximum number of detections for each class, this can be adjusted according to your own model.<br>        max_total_detections: 6 # The maximum number of detections returned in total, this can be adjusted according to your own model.<br>      }<br>      score_converter: SOFTMAX<br>    }<br>    ......<br>}<br>train_config {<br>  batch_size: 8 # Here you need to adjust the size according to your own computer performance<br>  num_steps: 10000 # Modify to the total number of steps you want to train<br>  optimizer {<br>    momentum_optimizer {<br>      learning_rate {<br>        cosine_decay_learning_rate {<br>          learning_rate_base: 0.008<br>          total_steps: 10000 # Modify to the total number of steps you want to train<br>          warmup_learning_rate: 0.0<br>          warmup_steps: 50<br>        }<br>      }<br>      momentum_optimizer_value: 0.8999999761581421<br>    }<br>    use_moving_average: false<br>  }<br>  gradient_clipping_by_norm: 10.0<br>  fine_tune_checkpoint_version: V2 # Add this item and specify it as the V2 version<br>  fine_tune_checkpoint: &quot;pre-trained-models/mask_rcnn_inception_resnet_v2_1024x1024_coco17_gpu-8/checkpoint/ckpt-0&quot; # Modify the path to the pre-trained model<br>  fine_tune_checkpoint_type: &quot;detection&quot; # Add this item and set it to detection, because we are doing object detection<br>  data_augmentation_options {<br>    random_horizontal_flip {<br>    }<br>  }<br>}<br>train_input_reader {<br>  label_map_path: &quot;annotations/label_map.pbtxt&quot; # Add this item<br>  tf_record_input_reader {<br>    input_path: &quot;annotations/train.record&quot; # Modify the path to the training set<br>  }<br>  load_instance_masks: true<br>  mask_type: PNG_MASKS<br>}<br>eval_config {<br>  metrics_set: &quot;coco_detection_metrics&quot;<br>  metrics_set: &quot;coco_mask_metrics&quot;<br>  eval_instance_masks: true<br>  use_moving_averages: false<br>  batch_size: 1<br>  include_metrics_per_category: true<br>}<br>eval_input_reader {<br>  label_map_path: &quot;annotations/label_map.pbtxt&quot; # Modify to the annotations path<br>  shuffle: false<br>  num_epochs: 1<br>  tf_record_input_reader {<br>    input_path: &quot;annotations/val.record&quot; # Modify the path to the evaluation set<br>  }<br>  load_instance_masks: true<br>  mask_type: PNG_MASKS<br>}</pre><h3>Training model</h3><pre>$ make train</pre><blockquote>Note: If the following problems occur</blockquote><blockquote>ValueError: numpy.ndarray size changed, may indicate binary incompatibility. Expected 88 from C header, got 80 from PyObject</blockquote><blockquote>You can execute the following command to solve it.</blockquote><pre>pip uninstall numpy<br>pip install numpy</pre><h3>Model export</h3><pre>$ make export</pre><h3>Testing</h3><p>After executing make export to export the model, and put the test image in the images/test folder, and then execute python test_images.py to output the annotated image to images/test_annotated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*KPY3iJoL8314Ib_7.jpg" /></figure><h3>Summary</h3><p>This article has gone through the entire process of Image Segmentation through a case study, hoping to help you quickly master the ability to <strong>train a custom Image Segmentation model</strong>.</p><p>The code and dataset of the case have been placed in <a href="https://github.com/CatchZeng/object-detection-api">https://github.com/CatchZeng/object-detection-api</a>.</p><p>The following articles will bring you:</p><ul><li><a href="https://makeoptim.com/en/deep-learning/yiai-serving-flask-mask-rcnn">How to deploy an image segmentation model service</a></li><li><strong>the principle of image segmentation</strong></li><li><strong>common networks</strong></li></ul><p>That’s it for this article, see you next.</p><h3>Further reading</h3><ul><li><a href="https://makeoptim.com/en/deep-learning/yiai-object-detection">The easiest way to Train a Custom Object Detection Model Using TensorFlow Object Detection API</a></li><li><a href="https://makeoptim.com/en/deep-learning/yiai-serving-flask-mask-rcnn">How to deploy an image segmentation model service</a></li></ul><h3>Reference</h3><ul><li><a href="https://github.com/tensorflow/models/tree/master/research/object_detection">https://github.com/tensorflow/models/tree/master/research/object_detection</a></li><li><a href="https://tensorflow-object-detection-api-tutorial.readthedocs.io/en/latest/index.html">https://tensorflow-object-detection-api-tutorial.readthedocs.io/en/latest/index.html</a></li><li><a href="https://github.com/eric-erki/How-To-Train-an-Object-Detection-Classifier-for-Multiple-Objects-Using-TensorFlow-GPU-on-Windows-1">https://github.com/eric-erki/How-To-Train-an-Object-Detection-Classifier-for-Multiple-Objects-Using-TensorFlow-GPU-on-Windows-1</a></li><li><a href="https://my.oschina.net/u/876354/blog/3055850">https://my.oschina.net/u/876354/blog/3055850</a></li><li><a href="https://stackoverflow.com/questions/53382383/makefile-cant-use-conda-activate">https://stackoverflow.com/questions/53382383/makefile-cant-use-conda-activate</a></li><li><a href="https://stackoverflow.com/questions/66060487/valueerror-numpy-ndarray-size-changed-may-indicate-binary-incompatibility-exp">https://stackoverflow.com/questions/66060487/valueerror-numpy-ndarray-size-changed-may-indicate-binary-incompatibility-exp</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8cbfd2321e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The easiest way to Train a Custom Object Detection Model Using TensorFlow Object Detection API]]></title>
            <link>https://catchzeng.medium.com/train-a-custom-object-detection-model-using-tensorflow-object-detection-api-7e49841f9bcb?source=rss-fa22b6cbf9d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e49841f9bcb</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[ssd]]></category>
            <category><![CDATA[object-detection-api]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Catch Zeng]]></dc:creator>
            <pubDate>Sat, 18 Sep 2021 02:32:51 GMT</pubDate>
            <atom:updated>2022-01-06T11:56:49.279Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*lHSPeKPkusq6dTME.jpeg" /></figure><p><strong><em>From: </em></strong><a href="https://makeoptim.com/en/deep-learning/yiai-object-detection"><strong><em>https://makeoptim.com/en/deep-learning/yiai-object-detection</em></strong></a></p><h3>Foreword</h3><p>This article will introduce the concept of <strong>Object Detection</strong>, and explain how to use <a href="https://github.com/tensorflow/models/tree/master/research/object_detection">TensorFlow Object Detection API</a> to train a <strong>custom object detector</strong> through cases, including <strong>data set collection and processing</strong>, <strong>TensorFlow Object Detection API installation</strong>, and <strong>model training</strong>.</p><p>The case effect is shown in the figure below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*YgJbrK82w9G4MgQg.jpg" /></figure><h3>Object Detection</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*d739xJTKBjZEngV8.jpeg" /></figure><p>As shown in the figure above, the problem that <strong>Image Classification</strong> solves is <strong>what is the object in the picture</strong>, and <strong>Object Detection</strong> can identify <strong>what objects</strong> and <strong>the location(coordinate) of the object in the picture.</strong></p><h3>Location</h3><p>The location information of Object Detection generally has two formats:</p><ul><li>Polar coordinates (xmin, ymin, xmax, ymax): xmin,ymin: the minimum value of x,y coordinates; xmin,ymin: the maximum value of x,y coordinates</li><li>Center point: (x_center, y_center, w, h): x_center, y_center: the coordinates of the center point of the target detection frame; w,h: the width and height of the target detection frame</li></ul><blockquote>Note: The upper left corner of the picture is the origin (0,0)</blockquote><h3>Milestone</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oqtcRXeio6GT6m1P.jpg" /></figure><h3>Traditional method (region proposal + manual feature extraction + classifier)</h3><p>HOG+SVM、DPM</p><h3>Region Proposal+CNN（Two-stage）</h3><p>R-CNN, SPP-NET, Fast R-CNN, Faster R-CNN</p><h3>End-to-End（One-stage）</h3><p>YOLO、SSD</p><h3>TensorFlow Object Detection API</h3><p>The <a href="https://github.com/tensorflow/models/tree/master/research/object_detection">TensorFlow Object Detection API</a> is an open-source framework built on top of TensorFlow that makes it <strong>easy to construct, train and deploy object detection models</strong>. In addition, the <a href="https://github.com/tensorflow/models/tree/master/research/object_detection">TensorFlow Object Detection API</a> also provides <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/tf2_detection_zoo.md">Model Zoo</a> to facilitate our <strong>selection</strong> and <strong>switching of pre-trained models</strong>.</p><h3>Install dependencies</h3><ul><li><a href="https://docs.conda.io/en/latest/miniconda.html">conda</a></li><li><a href="https://github.com/protocolbuffers/protobuf">protoc</a></li></ul><p>Use the following command to check if the installation is successful.</p><pre>$ conda --version<br>conda 4.9.2<br>$ protoc --version<br>libprotoc 3.17.1</pre><h3>Install API</h3><p>The official installation steps provided by the <a href="https://github.com/tensorflow/models/tree/master/research/object_detection">TensorFlow Object Detection API</a> are more cumbersome. The author wrote a script to install directly in one step.</p><p>Execute git clone https://github.com/CatchZeng/object-detection-api.git to download the repo, then go to the directory of the repo (<strong>hereafter referred to as the </strong><strong>oda repo</strong>) and execute the following command, if you see the following output, indicating that the installation was successful.</p><pre>$ conda create -n  od python=3.8.5 &amp;&amp; conda activate od &amp;&amp; make install</pre><pre>......<br>----------------------------------------------------------------------<br>Ran 24 tests in 21.869s</pre><pre>OK (skipped=1)</pre><blockquote>Note: If you don’t want to use conda, you can install it directly with `make install` in your python environment, for example, use it in <a href="https://colab.research.google.com/">colab</a>.</blockquote><blockquote>Note: The update of cudaDNN and toolkit may not be as fast as TensorFlow. Therefore, if your machine has a GPU, after the installation is complete, you need to downgrade TensorFlow to the version supported by cudaDNN and toolkit in order to support GPU training. Take 2.4.1 as an example:</blockquote><pre>$ pip install --upgrade tf-models-official==2.4.0<br>$ pip install --upgrade tensorflow==2.4.1</pre><blockquote>Note: If the installation fails, you can refer to the detailed steps in the <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/tf2.md">official document</a>.</blockquote><h3>Create workspace</h3><blockquote>Note: !!! From here, please make sure to execute under the environment of conda od.</blockquote><pre>$ conda activate od<br>$ conda env list<br># conda environments:<br>#<br>od                    *  /Users/catchzeng/.conda/envs/od<br>tensorflow               /Users/catchzeng/.conda/envs/tensorflow<br>base                     /Users/catchzeng/miniconda3</pre><p>Go to the oda repo directory and execute the following command to create the workspace directory structure.</p><blockquote>Note: SAVE_DIR is the directory to save the workspace, and NAME is the name of the workspace.</blockquote><pre>$ make workspace-box SAVE_DIR=workspace NAME=test</pre><pre>└── workspace<br>    └── test<br>        ├── Makefile<br>        ├── annotations: Store the labeled data set, including val.record, train.record, label_map.pbtxt<br>        ├── convert_quant_lite.py: the script to quantize tflite model<br>        ├── export_tflite_graph_tf2.py: the script to export tflite model<br>        ├── exported-models: Store the exported model after training<br>        ├── exporter_main_v2.py: the script to export model<br>        ├── images: Data set images and xml annotations<br>        │   ├── test: Store manual verification images<br>        │   ├── train: Training set images and xml annotations<br>        │   └── val: Evaluation set images and xml annotations<br>        ├── model_main_tf2.py：the script to train model<br>        ├── models: Custom model<br>        ├── pre-trained-models: pre-trained models<br>        └── test_images.py: the script to verify the image manually</pre><h3>Dataset</h3><h3>Images</h3><p>I like to drink tea. Today I will use a <strong>cup, teapot, humidifier</strong> as examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*6CGn5enk5DzLorLm.jpg" /></figure><p>Put the collected pictures into the three subdirectories of images in the project directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*mT1tF9NWEgIiJP1h.jpg" /></figure><blockquote>Note: This case is just to show how to train the Object Detection model, so the dataset is relatively small. In the production, remember to <strong>collect as many datasets as possible</strong>.</blockquote><h3>Annotation</h3><p>After collecting the pictures, you need to annotate the images in the <strong>training</strong> and <strong>evaluation</strong> sets.</p><p>We choose <a href="https://github.com/tzutalin/labelImg">LabelImg</a> as the annotation tool.</p><p>Install LabelImg according to the instructions of <a href="https://github.com/tzutalin/labelImg#installation">installation</a>, then execute labelImg to select the train and val folders for annotation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*SrHbyQXnjXbgRl6x.jpg" /></figure><p>After the annotation is completed, the xml annotation file corresponding to the image will be generated, as shown below:</p><pre>workspace/test/images<br>├── test<br>│   ├── 15.jpg<br>│   └── 16.jpg<br>├── train<br>│   ├── 1.jpg<br>│   ├── 1.xml<br>│   ├── 10.jpg<br>│   ├── 10.xml<br>│   ├── 2.jpg<br>│   ├── 2.xml<br>│   ├── 3.jpg<br>│   ├── 3.xml<br>│   ├── 4.jpg<br>│   ├── 4.xml<br>│   ├── 5.jpg<br>│   ├── 5.xml<br>│   ├── 6.jpg<br>│   ├── 6.xml<br>│   ├── 7.jpg<br>│   ├── 7.xml<br>│   ├── 8.jpg<br>│   ├── 8.xml<br>│   ├── 9.jpg<br>│   └── 9.xml<br>└── val<br>    ├── 11.jpg<br>    ├── 11.xml<br>    ├── 12.jpg<br>    ├── 12.xml<br>    ├── 13.jpg<br>    ├── 13.xml<br>    ├── 14.jpg<br>    └── 14.xml</pre><h3>Create TFRecord</h3><p><a href="https://github.com/tensorflow/models/tree/master/research/object_detection">TensorFlow Object Detection API</a> only supports <a href="https://www.tensorflow.org/api_docs/python/tf/data/TFRecordDataset">TFRecord</a> format, therefore, the dataset needs to be converted.</p><p>Go to the workspace directory (cd workspace/test), and then execute make gen-tfrecord, it will generate label_map.pbtxt and <a href="https://www.tensorflow.org/api_docs/python/tf/data/TFRecordDataset">TFRecord</a> format dataset in the annotations folder.</p><pre>$ make gen-tfrecord<br>python gen_label_map.py<br>unsorted:  [&#39;cup&#39;, &#39;teapot&#39;, &#39;humidifier&#39;]<br>sorted:  [&#39;cup&#39;, &#39;humidifier&#39;, &#39;teapot&#39;]<br>item {<br>  id: 1<br>  name: &#39;cup&#39;<br>}<br><br>item {<br>  id: 2<br>  name: &#39;humidifier&#39;<br>}<br><br>item {<br>  id: 3<br>  name: &#39;teapot&#39;<br>}<br><br>python generate_tfrecord.py \<br>        -x images/train \<br>        -l annotations/label_map.pbtxt \<br>        -o annotations/train.record<br>Successfully created the TFRecord file: annotations/train.record<br>python generate_tfrecord.py \<br>        -x images/val \<br>        -l annotations/label_map.pbtxt \<br>        -o annotations/val.record<br>Successfully created the TFRecord file: annotations/val.record</pre><pre>annotations<br>├── label_map.pbtxt<br>├── train.record<br>└── val.record</pre><pre># label_map.pbtxt<br>item {<br>  id: 1<br>  name: &#39;cup&#39;<br>}<br><br>item {<br>  id: 2<br>  name: &#39;humidifier&#39;<br>}<br><br>item {<br>  id: 3<br>  name: &#39;teapot&#39;<br>}</pre><h3>Model training</h3><blockquote>Note: !!! From here, please make sure you have go to the workspace directory (cd workspace/test).</blockquote><h3>Download the pre-trained model</h3><p>Select the appropriate model from <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/tf2_detection_zoo.md">Model Zoo</a>, download and unzip it, and put it in workspace/test/pre-trained-models.</p><p>If you choose SSD MobileNet V2 FPNLite 320x320, you can execute the following command to automatically download and decompress</p><pre>$ make dl-model</pre><p>The directory structure is as follows:</p><pre>└── test<br>    └── pre-trained-models<br>        └── ssd_mobilenet_v2_fpnlite_320x320_coco17_tpu-8<br>            ├── checkpoint<br>            ├── pipeline.config<br>            └── saved_model</pre><h3>Configure training pipeline</h3><p>Create a corresponding model folder in the models directory, for example: ssd_mobilenet_v2_fpnlite_320x320, and copy pre-trained-models/ssd_mobilenet_v2_fpnlite_320x320_coco17_tpu-8/pipeline.config.</p><pre>└── test<br>    ├── models<br>    │   └── ssd_mobilenet_v2_fpnlite_320x320<br>    │       └── pipeline.config<br>    └── pre-trained-models</pre><p>Among them, pipeline.config needs to be modified according to the project as follows</p><pre>model {<br>  ssd {<br>    num_classes: 3 # Modify to the number of objects that need to be identified.<br>    ......<br>}<br>train_config {<br>  batch_size: 8 # Here you need to adjust the size according to your own computer performance<br>  ......<br>  optimizer {<br>    momentum_optimizer {<br>      learning_rate {<br>        cosine_decay_learning_rate {<br>          learning_rate_base: 0.07999999821186066<br>          total_steps: 10000 # Modify to the total number of steps you want to train<br>          warmup_learning_rate: 0.026666000485420227<br>          warmup_steps: 1000<br>        }<br>      }<br>      momentum_optimizer_value: 0.8999999761581421<br>    }<br>    use_moving_average: false<br>  }<br>  fine_tune_checkpoint: &quot;pre-trained-models/ssd_mobilenet_v2_fpnlite_320x320_coco17_tpu-8/checkpoint/ckpt-0&quot; # Modify the path to the pre-trained model<br>  num_steps: 10000 # Modify to the total number of steps you want to train<br>  startup_delay_steps: 0.0<br>  replicas_to_aggregate: 8<br>  max_number_of_boxes: 100<br>  unpad_groundtruth_tensors: false<br>  fine_tune_checkpoint_type: &quot;detection&quot; # Here needs to be modified to detection, because we are doing object detection<br>  fine_tune_checkpoint_version: V2<br>}<br>train_input_reader {<br>  label_map_path: &quot;annotations/label_map.pbtxt&quot; # Modify to the annotations path<br>  tf_record_input_reader {<br>    input_path: &quot;annotations/train.record&quot; # Modify the path to the training set<br>  }<br>}<br>eval_config {<br>  metrics_set: &quot;coco_detection_metrics&quot;<br>  use_moving_averages: false<br>}<br>eval_input_reader {<br>  label_map_path: &quot;annotations/label_map.pbtxt&quot; # Modify to the annotations path<br>  shuffle: false<br>  num_epochs: 1<br>  tf_record_input_reader {<br>    input_path: &quot;annotations/val.record&quot; # Modify the path to the evaluation set<br>  }<br>}</pre><h3>Training model</h3><pre>$ make train</pre><blockquote>Note: If the following problems occur</blockquote><blockquote>ValueError: numpy.ndarray size changed, may indicate binary incompatibility. Expected 88 from C header, got 80 from PyObject</blockquote><blockquote>You can execute the following command to solve it.</blockquote><pre>pip uninstall numpy<br>pip install numpy</pre><h3>Model export and conversion</h3><ul><li>Saved Model</li></ul><p>$ make export</p><ul><li>TFLite Model</li></ul><p>$ make export-lite</p><ul><li>Convert TFLite model</li></ul><p>$ make convert-lite</p><ul><li>Quantize TFLite Model</li></ul><p>$ make convert-quant-lite</p><blockquote>Note: For the above command, you can add -640 to indicate the use of the model of SSD MobileNet V2 FPNLite 640x640, for example: make train -&gt; make train-640</blockquote><h3>Testing</h3><p>After executing make export to export the model, and put the test image in the images/test folder, and then execute python test_images.py to output the annotated image to images/test_annotated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*RJc4MN9im4J1e_bb.jpg" /></figure><h3>Summary</h3><p>This article has gone through the entire process of Object Detection through cases, hoping to help you quickly master the ability to train custom Object Detectors.</p><p>The code and dataset of the case have been placed in <a href="https://github.com/CatchZeng/object-detection-api">https://github.com/CatchZeng/object-detection-api</a>.</p><p>The following articles will bring you the principles of <strong>Object Detection</strong>, <strong>Popular Object detection networks</strong>, and <strong>Image Segmentation</strong>. That’s it for this article, see you <a href="https://makeoptim.com/en/deep-learning/yiai-image-segmentation">next</a>.</p><h3>Further reading</h3><ul><li><a href="https://makeoptim.com/en/deep-learning/yiai-image-segmentation">The easiest way to Train a Custom Image Segmentation Model Using TensorFlow Object Detection API Mask R-CNN</a></li><li><a href="https://makeoptim.com/en/deep-learning/yiai-serving-flask-mask-rcnn">How to deploy an image segmentation model service</a></li></ul><h3>Reference</h3><ul><li><a href="https://github.com/tensorflow/models/tree/master/research/object_detection">https://github.com/tensorflow/models/tree/master/research/object_detection</a></li><li><a href="https://arxiv.org/pdf/1905.05055.pdf">https://arxiv.org/pdf/1905.05055.pdf</a></li><li><a href="https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/tf2_detection_zoo.md">https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/tf2_detection_zoo.md</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e49841f9bcb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apple Silicon Mac M1 natively supports TensorFlow 2.6]]></title>
            <link>https://catchzeng.medium.com/deep-learning-tensorflow-metal-pluggabledevice-jupyterlab-vscode-on-apple-silicon-m1-mac-b81bd6e956c8?source=rss-fa22b6cbf9d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b81bd6e956c8</guid>
            <category><![CDATA[metal]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[m1-mac]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[jupyter]]></category>
            <dc:creator><![CDATA[Catch Zeng]]></dc:creator>
            <pubDate>Thu, 24 Jun 2021 03:13:37 GMT</pubDate>
            <atom:updated>2021-10-26T05:54:23.986Z</atom:updated>
            <content:encoded><![CDATA[<h3>Apple Silicon Mac M1 natively supports TensorFlow 2.6 GPU acceleration (tensorflow-metal PluggableDevice)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*bi0oUv05tyQ0_H4f2Wl95A.jpeg" /></figure><p><strong><em>From: </em></strong><a href="https://makeoptim.com/en/deep-learning/tensorflow-metal"><strong><em>https://makeoptim.com/en/deep-learning/tensorflow-metal</em></strong></a></p><h3>Foreword</h3><p>A few days ago, I saw that <a href="https://github.com/apple/tensorflow_macos">https://github.com/apple/tensorflow_macos</a> has been <strong>archived</strong>, and the README stated <strong>that TensorFlow v2.5 natively supports M1</strong>.</p><blockquote>You can now leverage Apple’s tensorflow-metal PluggableDevice in TensorFlow v2.5 for accelerated training on Mac GPUs directly with Metal. Learn more <a href="https://developer.apple.com/metal/tensorflow-plugin/">here</a>.</blockquote><p>This article serves as an update of the <a href="https://makeoptim.com/deep-learning/mac-m1-tensorflow">Apple Silicon Mac M1 Machine Learning Environment (TensorFlow, JupyterLab, VSCode)</a>, and will give you a detailed introduction to how to install the latest supported GPU Accelerated TensorFlow.</p><h3>OS Requirements</h3><ul><li>macOS 12.0+</li></ul><h3>Currently Not Supported</h3><ul><li>Multi-GPU support</li><li>Acceleration for Intel GPUs</li><li>V1 TensorFlow Networks</li></ul><h3>Xcode</h3><p>Install Xcode from App Store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/0*BK_jBGXXi5dQ4C4y.png" /></figure><h3>Command Line Tools</h3><p>Install <a href="https://developer.apple.com/download/more/?=command%20line%20tools">Xcode Command Line Tools</a> by downloading it from <a href="https://developer.apple.com/">Apple Developer</a> or by typing:</p><pre>catchzeng@m1 ~ % xcode-select --install</pre><h3>Homebrew</h3><pre>catchzeng@m1 ~ % /bin/bash -c &quot;$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)&quot;</pre><h3>Miniforge</h3><blockquote>Anaconda cannot run on M1, Miniforge is used to replace it.</blockquote><p>Download the Miniforge3-MacOSX-arm64 from <a href="https://github.com/conda-forge/miniforge">https://github.com/conda-forge/miniforge</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/0*gZ14qt-VQElCDM4l.png" /></figure><p>Install Miniforge using the terminal.</p><pre>catchzeng@m1 ~ % bash Miniforge3-MacOSX-arm64.sh</pre><p><strong>Restart the terminal</strong> and check it.</p><pre>(base) catchzeng@m1 ~ % which python<br>/Users/catchzeng/miniforge3/bin/python<br>(base) catchzeng@m1 ~ % which pip<br>/Users/catchzeng/miniforge3/bin/pip</pre><h3>Create virtual environment</h3><p>Create and activate a conda virtual environment with python 3.9.5 (<a href="https://www.tensorflow.org/install/pip">as required for TensorFlow</a>).</p><pre>(base) catchzeng@m1 ~ % conda create -n tensorflow python=3.9.5<br>(base) catchzeng@m1 ~ % conda activate tensorflow<br>(tensorflow) catchzeng@m1 ~ %</pre><h3>Install Tensorflow dependencies</h3><h3>First installation</h3><pre>(tensorflow) catchzeng@m1 ~ % conda install -c apple tensorflow-deps</pre><blockquote>Note: tensorflow-deps versions are following base TensorFlow versions so:</blockquote><blockquote>For v2.5:</blockquote><pre>(tensorflow) catchzeng@m1 ~ % conda install -c apple tensorflow-deps==2.5.0</pre><blockquote>For v2.6:</blockquote><pre>(tensorflow) catchzeng@m1 ~ % conda install -c apple tensorflow-deps==2.6.0</pre><h3>Upgrade installation</h3><p>If you have installed v2.5 before and want to update v2.6, you can execute the following command to install.</p><pre># uninstall existing tensorflow-macos and tensorflow-metal<br>(tensorflow) catchzeng@m1 ~ % python -m pip uninstall tensorflow-macos<br>(tensorflow) catchzeng@m1 ~ % python -m pip uninstall tensorflow-metal<br># Upgrade tensorflow-deps<br>(tensorflow) catchzeng@m1 ~ % conda install -c apple tensorflow-deps --force-reinstall<br># or point to specific conda environment<br>(tensorflow) catchzeng@m1 ~ % conda install -c apple tensorflow-deps --force-reinstall -n tensorflow</pre><h3>Install Tensorflow</h3><pre>(tensorflow) catchzeng@m1 ~ % python -m pip install tensorflow-macos</pre><h3>Install metal plugin</h3><pre>(tensorflow) catchzeng@m1 ~ % python -m pip install tensorflow-metal</pre><h3>Install needed packages</h3><pre>(tensorflow) catchzeng@m1 ~ % brew install libjpeg<br>(tensorflow) catchzeng@m1 ~ % conda install -y matplotlib jupyterlab</pre><blockquote>Note: libjpeg is a required dependency for matplotlib.</blockquote><h3>Test</h3><p>TensorFlow</p><pre>(tensorflow) catchzeng@m1 ~ % python<br>Python 3.9.5 | packaged by conda-forge | (default, Oct 19 2021, 17:32:20)<br>[Clang 11.1.0 ] on darwin<br>Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information.<br>&gt;&gt;&gt; import tensorflow as tf<br>Init Plugin<br>Init Graph Optimizer<br>Init Kernel<br>&gt;&gt;&gt; print(tf.__version__)<br>2.6.0<br>&gt;&gt;&gt;</pre><h3>JupyterLab</h3><pre>(tensorflow) catchzeng@m1 ~ % jupyter lab</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*0gxIogeXa9eiaZ7d.png" /></figure><pre>from tensorflow.keras import layers<br>from tensorflow.keras import models<br>model = models.Sequential()<br>model.add(layers.Conv2D(32, (3, 3), activation=&#39;relu&#39;, input_shape=(28, 28, 1)))<br>model.add(layers.MaxPooling2D((2, 2)))<br>model.add(layers.Conv2D(64, (3, 3), activation=&#39;relu&#39;))<br>model.add(layers.MaxPooling2D((2, 2)))<br>model.add(layers.Conv2D(64, (3, 3), activation=&#39;relu&#39;))<br>model.add(layers.Flatten())<br>model.add(layers.Dense(64, activation=&#39;relu&#39;))<br>model.add(layers.Dense(10, activation=&#39;softmax&#39;))<br>model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*Bmy66bo4_k4flPKV.png" /></figure><pre>from tensorflow.keras.datasets import mnist<br>from tensorflow.keras.utils import to_categorical<br>(train_images, train_labels), (test_images, test_labels) = mnist.load_data()<br>train_images = train_images.reshape((60000, 28, 28, 1))<br>train_images = train_images.astype(&#39;float32&#39;) / 255<br>test_images = test_images.reshape((10000, 28, 28, 1))<br>test_images = test_images.astype(&#39;float32&#39;) / 255<br>train_labels = to_categorical(train_labels)<br>test_labels = to_categorical(test_labels)<br>model.compile(optimizer=&#39;rmsprop&#39;,<br>              loss=&#39;categorical_crossentropy&#39;,<br>              metrics=[&#39;accuracy&#39;])<br>model.fit(train_images, train_labels, epochs=5, batch_size=64)<br>test_loss, test_acc = model.evaluate(test_images, test_labels)<br>test_acc</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/0*fbN-UGnxqDReFCjY.png" /></figure><p>Open the Activity Monitor and you can see that Python is using GPU resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/0*Pyzc33Eua7lFpwDW.png" /></figure><h3>VSCode</h3><p>Install Python support</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/0*8vEFjZQoHutnOmt0.png" /></figure><p>Select virtualenv and trust the notebook</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*oydF04sAsVsf2K7h.png" /></figure><p>Run the notebook</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*C79OBJgjqVHwb2dY.png" /></figure><h3>Further reading</h3><ul><li><a href="https://makeoptim.com/en/deep-learning/mac-tensorflow">Deep Learning (TensorFlow, JupyterLab, VSCode) on Mac</a></li><li><a href="https://makeoptim.com/en/deep-learning/tensorflow-gpu-on-ubuntu">Installing TensorFlow GPU on Ubuntu with apt</a></li><li><a href="https://makeoptim.com/en/deep-learning/tensorflow-gpu-on-win10">Installing TensorFlow GPU on Win10</a></li><li><a href="https://makeoptim.com/en/deep-learning/mac-m1-tensorflow">Deep Learning (TensorFlow, JupyterLab, VSCode) on Apple Silicon M1 Mac</a></li></ul><h3>Reference</h3><ul><li><a href="https://developer.apple.com/metal/tensorflow-plugin/">https://developer.apple.com/metal/tensorflow-plugin/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b81bd6e956c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Installing TensorFlow GPU on Win10]]></title>
            <link>https://catchzeng.medium.com/installing-tensorflow-gpu-on-win10-6b0c027616d3?source=rss-fa22b6cbf9d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b0c027616d3</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[jupyter]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[nvidia-gpu]]></category>
            <category><![CDATA[win-10]]></category>
            <dc:creator><![CDATA[Catch Zeng]]></dc:creator>
            <pubDate>Fri, 07 May 2021 06:46:03 GMT</pubDate>
            <atom:updated>2021-05-28T06:06:12.344Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*SWo1jjvQ_n5Jc_qbv3La7A.jpeg" /></figure><blockquote>From <a href="https://makeoptim.com/en/deep-learning/tensorflow-gpu-on-win10">https://makeoptim.com/en/deep-learning/tensorflow-gpu-on-win10</a></blockquote><h3>Intro</h3><ul><li>Win10</li><li>GTX 1050ti</li><li>TensorFlow 2.4.1</li></ul><h3>Software requirements</h3><ul><li><a href="https://www.nvidia.com/drivers">NVIDIA® GPU drivers</a> — CUDA® 11.0 requires 450.x or higher.</li><li><a href="https://developer.nvidia.com/cuda-toolkit-archive">CUDA® Toolkit</a> — TensorFlow supports CUDA® 11 (TensorFlow &gt;= 2.4.0)</li><li>CUPTI ships with the <a href="https://developer.nvidia.com/cuda-toolkit-archive">CUDA® Toolkit</a>.</li><li><a href="https://developer.nvidia.com/cudnn">cuDNN SDK 8.0.4</a> <a href="https://developer.nvidia.com/rdp/cudnn-archive">cuDNN versions</a>.</li><li><em>(Optional)</em> <a href="https://docs.nvidia.com/deeplearning/sdk/tensorrt-install-guide/index.html">TensorRT 6.0</a> to improve latency and throughput for inference on some models.</li></ul><h3>NVIDIA GPU driver</h3><p>Go to <a href="https://www.nvidia.com/cn/download/index.aspx">https://www.nvidia.com/cn/download/index.aspx</a> download and install the corresponding GPU driver.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/0*5jIO6byLw_8_J5Bo.png" /></figure><p>Reboot and check that GPUs are visible using the following command.</p><pre>PS C:\Users\Administrator&gt; nvidia-smi.exe<br>Wed Apr 28 22:28:23 2021<br>+-----------------------------------------------------------------------------+<br>| NVIDIA-SMI 466.11       Driver Version: 466.11       CUDA Version: 11.3     |<br>|-------------------------------+----------------------+----------------------+<br>| GPU  Name            TCC/WDDM | Bus-Id        Disp.A | Volatile Uncorr. ECC |<br>| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |<br>|                               |                      |               MIG M. |<br>|===============================+======================+======================|<br>|   0  NVIDIA GeForce ... WDDM  | 00000000:01:00.0  On |                  N/A |<br>| 30%   34C    P0    N/A /  75W |    455MiB /  4096MiB |      1%      Default |<br>|                               |                      |                  N/A |<br>+-------------------------------+----------------------+----------------------+</pre><pre>+-----------------------------------------------------------------------------+<br>| Processes:                                                                  |<br>|  GPU   GI   CI        PID   Type   Process name                  GPU Memory |<br>|        ID   ID                                                   Usage      |<br>|=============================================================================|<br>|    0   N/A  N/A      1532    C+G   C:\Windows\System32\dwm.exe     N/A      |<br>|    0   N/A  N/A      2800    C+G   ...Central\Razer Central.exe    N/A      |<br>|    0   N/A  N/A      4576    C+G   C:\Windows\explorer.exe         N/A      |<br>|    0   N/A  N/A      5104    C+G   ...5n1h2txyewy\SearchApp.exe    N/A      |<br>|    0   N/A  N/A      6112    C+G   ...lPanel\SystemSettings.exe    N/A      |<br>|    0   N/A  N/A      7588    C+G   ...me\Application\chrome.exe    N/A      |<br>|    0   N/A  N/A      8568    C+G   ...arp.BrowserSubprocess.exe    N/A      |<br>|    0   N/A  N/A      9076    C+G   ...nputApp\TextInputHost.exe    N/A      |<br>|    0   N/A  N/A      9096    C+G   ... Host\Razer Synapse 3.exe    N/A      |<br>|    0   N/A  N/A     10152    C+G   ...y\ShellExperienceHost.exe    N/A      |<br>+-----------------------------------------------------------------------------+</pre><h3>CUDA ToolKit</h3><p>Go to <a href="http://developer.nvidia.com/cuda-downloads">http://developer.nvidia.com/cuda-downloads</a> to download <a href="https://developer.nvidia.com/cuda-%20downloads">CUDA Toolkit 11.3</a> and install.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kOMo8RRmjwvZZGo1.png" /></figure><h3>cuDNN</h3><p>Go to <a href="https://developer.nvidia.com/rdp/cudnn-archive">https://developer.nvidia.com/rdp/cudnn-archive</a> to download cuDNN and unzip it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uIS_HlB5BMZSXHKk.png" /></figure><p>Copy the decompressed lib, bin, include to the directory corresponding to C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/0*3I_bRDpf9_QwPT1K.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/0*ESQzcHIKn6vnjXbn.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/0*f9oyY_66P7QwrezQ.png" /></figure><p>Copy cusolver64_11.dll under C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.1\bin and rename it to cusolver64_10.dll.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*y41EXXafExoYlkIu.png" /></figure><h3>Environment variable</h3><pre>SET PATH=C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.1\bin;%PATH%<br>SET PATH=C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.1\extras\CUPTI\lib64;%PATH%<br>SET PATH=C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.1\include;%PATH%<br>SET PATH=C:\tools\cuda\bin;%PATH%</pre><h3>Miniconda</h3><p>Go to <a href="https://docs.conda.io/en/latest/miniconda.html">https://docs.conda.io/en/latest/miniconda.html</a> to download and install Miniconda.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/0*op7CD1Gf2SvermkV.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/0*UUVlPYHDKIBJEfgq.png" /></figure><h3>Virtual environment</h3><p>Open Anaconda Powershell Prompt。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/0*V2FIU5-7Jjd5BHQ5.png" /></figure><p>Create a virtual environment called tensorflow.</p><pre>$ conda create -n tensorflow python=3.8.5<br>$ conda activate tensorflow</pre><blockquote>Note: If you use Power Sehll, you need to execute conda init powershell and set-executionpolicy remotesigned, otherwise there will be a problem of failing to successfully activate activate, see <a href="https://stackoverflow.com/questions/62082873/conda-not-activate-in-power-shell">https://stackoverflow.com/questions/62082873/conda -not-activate-in-power-shell</a></blockquote><pre>PS C:\Users\Administrator&gt; conda init powershell<br>no change     D:\ProgramData\Miniconda3\Scripts\conda.exe<br>no change     D:\ProgramData\Miniconda3\Scripts\conda-env.exe<br>no change     D:\ProgramData\Miniconda3\Scripts\conda-script.py<br>no change     D:\ProgramData\Miniconda3\Scripts\conda-env-script.py<br>no change     D:\ProgramData\Miniconda3\condabin\conda.bat<br>no change     D:\ProgramData\Miniconda3\Library\bin\conda.bat<br>no change     D:\ProgramData\Miniconda3\condabin\_conda_activate.bat<br>no change     D:\ProgramData\Miniconda3\condabin\rename_tmp.bat<br>no change     D:\ProgramData\Miniconda3\condabin\conda_auto_activate.bat<br>no change     D:\ProgramData\Miniconda3\condabin\conda_hook.bat<br>no change     D:\ProgramData\Miniconda3\Scripts\activate.bat<br>no change     D:\ProgramData\Miniconda3\condabin\activate.bat<br>no change     D:\ProgramData\Miniconda3\condabin\deactivate.bat<br>modified      D:\ProgramData\Miniconda3\Scripts\activate<br>modified      D:\ProgramData\Miniconda3\Scripts\deactivate<br>modified      D:\ProgramData\Miniconda3\etc\profile.d\conda.sh<br>modified      D:\ProgramData\Miniconda3\etc\fish\conf.d\conda.fish<br>no change     D:\ProgramData\Miniconda3\shell\condabin\Conda.psm1<br>modified      D:\ProgramData\Miniconda3\shell\condabin\conda-hook.ps1<br>no change     D:\ProgramData\Miniconda3\Lib\site-packages\xontrib\conda.xsh<br>modified      D:\ProgramData\Miniconda3\etc\profile.d\conda.csh<br>modified      C:\Users\Administrator\Documents\WindowsPowerShell\profile.ps1</pre><pre>==&gt; For changes to take effect, close and re-open your current shell. &lt;==</pre><pre>PS C:\Users\Administrator&gt; set-executionpolicy remotesigned</pre><h3>Install TensorFlow</h3><pre>(tensorflow) PS C:\Users\Administrator&gt; pip install tensorflow==2.4.1</pre><p>Verify installation</p><pre>(tensorflow) PS C:\Users\Administrator&gt; python -c &quot;import tensorflow as tf;print(&#39;Num GPUs Available: &#39;, len(tf.config.list_physical_devices(&#39;GPU&#39;)))&quot;<br>2021-05-05 21:38:12.335369: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library cudart64_110.dll<br>2021-05-05 21:38:14.569229: I tensorflow/compiler/jit/xla_cpu_device.cc:41] Not creating XLA devices, tf_xla_enable_xla_devices not set<br>2021-05-05 21:38:14.571864: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library nvcuda.dll<br>2021-05-05 21:38:14.605855: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1720] Found device 0 with properties:<br>pciBusID: 0000:01:00.0 name: NVIDIA GeForce GTX 1050 Ti computeCapability: 6.1<br>coreClock: 1.392GHz coreCount: 6 deviceMemorySize: 4.00GiB deviceMemoryBandwidth: 104.43GiB/s<br>2021-05-05 21:38:14.606025: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library cudart64_110.dll<br>2021-05-05 21:38:14.682846: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library cublas64_11.dll<br>2021-05-05 21:38:14.682987: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library cublasLt64_11.dll<br>2021-05-05 21:38:14.721429: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library cufft64_10.dll<br>2021-05-05 21:38:14.732614: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library curand64_10.dll<br>2021-05-05 21:38:14.818913: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library cusolver64_10.dll<br>2021-05-05 21:38:14.842604: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library cusparse64_11.dll<br>2021-05-05 21:38:14.848834: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library cudnn64_8.dll<br>2021-05-05 21:38:14.849000: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1862] Adding visible gpu devices: 0<br>Num GPUs Available:  1</pre><h3>Install JupyterLab and matplotlib</h3><pre>(tensorflow) PS C:\Users\Administrator&gt; pip install jupyterlab matplotlib</pre><h3>Install pywin32</h3><pre>(tensorflow) PS C:\Users\Administrator&gt; cd &#39;C:\ProgramData\Miniconda3\Scripts\&#39;<br>(tensorflow) PS C:\ProgramData\Miniconda3\Scripts&gt; python pywin32_postinstall.py -install<br>Parsed arguments are: Namespace(destination=&#39;C:\\ProgramData\\Miniconda3\\envs\\tensorflow\\Lib\\site-packages&#39;, install=True, quiet=False, remove=False, silent=False, wait=None)<br>pywin32_postinstall.py:164: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module&#39;s documentation for alternative uses<br>  import imp<br>Copied pythoncom38.dll to C:\WINDOWS\system32\pythoncom38.dll<br>Copied pywintypes38.dll to C:\WINDOWS\system32\pywintypes38.dll<br>Registered: Python.Interpreter<br>Registered: Python.Dictionary<br>Registered: Python<br>-&gt; Software\Python\PythonCore\3.8\Help[None]=None<br>-&gt; Software\Python\PythonCore\3.8\Help\Pythonwin Reference[None]=&#39;C:\\ProgramData\\Miniconda3\\envs\\tensorflow\\Lib\\site-packages\\PyWin32.chm&#39;<br>Pythonwin has been registered in context menu<br>Creating directory C:\ProgramData\Miniconda3\envs\tensorflow\Lib\site-packages\win32com\gen_py<br>Can&#39;t install shortcuts - &#39;C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Python 3.8&#39; is not a folder<br>The pywin32 extensions were successfully installed.</pre><h3>Run TensorFlow in JupyterLab</h3><pre>jupyter lab</pre><p>JupyterLab will be automatically opened in a browser.</p><p>Download and import CNN notebook from <a href="https://www.tensorflow.org/tutorials/images/cnn">https://www.tensorflow.org/tutorials/images/cnn</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/0*32JupRNqW3bfO4rN.png" /></figure><p>Restart Kernel and Run All Cells</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/0*Lmpwalay-JIpYfTY.png" /></figure><p>When the train is running, check GPU processes, you can see ...nvs\tensorflow\python.exe, which means that the GPU is being used to train the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/0*kETL_JWqJsH5HP10.png" /></figure><pre>PS C:\Users\Administrator&gt; nvidia-smi.exe<br>Wed May  5 21:47:50 2021<br>+-----------------------------------------------------------------------------+<br>| NVIDIA-SMI 466.11       Driver Version: 466.11       CUDA Version: 11.3     |<br>|-------------------------------+----------------------+----------------------+<br>| GPU  Name            TCC/WDDM | Bus-Id        Disp.A | Volatile Uncorr. ECC |<br>| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |<br>|                               |                      |               MIG M. |<br>|===============================+======================+======================|<br>|   0  NVIDIA GeForce ... WDDM  | 00000000:01:00.0  On |                  N/A |<br>| 30%   39C    P0    N/A /  75W |   3695MiB /  4096MiB |     50%      Default |<br>|                               |                      |                  N/A |<br>+-------------------------------+----------------------+----------------------+</pre><pre>+-----------------------------------------------------------------------------+<br>| Processes:                                                                  |<br>|  GPU   GI   CI        PID   Type   Process name                  GPU Memory |<br>|        ID   ID                                                   Usage      |<br>|=============================================================================|<br>|    0   N/A  N/A      1008    C+G   C:\Windows\explorer.exe         N/A      |<br>|    0   N/A  N/A      3620    C+G   ...8bbwe\WindowsTerminal.exe    N/A      |<br>|    0   N/A  N/A      6936    C+G   ...nputApp\TextInputHost.exe    N/A      |<br>|    0   N/A  N/A      7024    C+G   ...5n1h2txyewy\SearchApp.exe    N/A      |<br>|    0   N/A  N/A      9648    C+G   ...me\Application\chrome.exe    N/A      |<br>|    0   N/A  N/A     12128    C+G   C:\Windows\System32\dwm.exe     N/A      |<br>|    0   N/A  N/A     12248    C+G   ...y\ShellExperienceHost.exe    N/A      |<br>|    0   N/A  N/A     14384      C   ...nvs\tensorflow\python.exe    N/A      |<br>+-----------------------------------------------------------------------------+</pre><h3>Install VSCode</h3><p>Go to the <a href="https://code.visualstudio.com/">Official Website</a> to download and install VSCode.</p><p>Open VSCode and install Python support.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ouxzxweg_XxAdFDY.jpg" /></figure><p>Open the created ~/tensorflow-notebook/01-hello/hello.ipynb, and select Python as the created virtual environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kvh0CKXwQQ8S1TqO.jpg" /></figure><h3>Run TensorFlow in VSCode</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6AWFNFlNpSXVhjsr.jpg" /></figure><h3>Summary</h3><p>At this point, the deep learning environment has been set up. You can choose to use the command line, JupyterLab or VSCode for development according to your own habits.</p><h3>Further reading</h3><ul><li><a href="https://makeoptim.com/en/deep-learning/mac-tensorflow">Deep Learning (TensorFlow, JupyterLab, VSCode) on Mac</a></li><li><a href="https://makeoptim.com/en/deep-learning/mac-m1-tensorflow">Deep Learning (TensorFlow, JupyterLab, VSCode) on Apple Silicon M1 Mac</a></li><li><a href="https://makeoptim.com/en/deep-learning/tensorflow-gpu-on-ubuntu">Installing TensorFlow GPU on Ubuntu with apt</a></li></ul><h3>Reference</h3><ul><li><a href="https://www.tensorflow.org/install">https://www.tensorflow.org/install</a></li><li><a href="https://www.tensorflow.org/guide/gpu">https://www.tensorflow.org/guide/gpu</a></li><li><a href="https://docs.nvidia.com/cuda/cuda-installation-guide-microsoft-windows/">https://docs.nvidia.com/cuda/cuda-installation-guide-microsoft-windows/</a></li><li><a href="http://developer.nvidia.com/cuda-downloads">http://developer.nvidia.com/cuda-downloads</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b0c027616d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Installing TensorFlow GPU on Ubuntu with apt]]></title>
            <link>https://catchzeng.medium.com/installing-tensorflow-gpu-on-ubuntu-with-apt-95373df8cfba?source=rss-fa22b6cbf9d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/95373df8cfba</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[jupyter]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[ubuntu]]></category>
            <category><![CDATA[nvidia-gpu]]></category>
            <dc:creator><![CDATA[Catch Zeng]]></dc:creator>
            <pubDate>Mon, 12 Apr 2021 01:39:08 GMT</pubDate>
            <atom:updated>2021-05-28T06:05:34.871Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tYm6g6JcuRr-OYuEWHEAhA.jpeg" /></figure><blockquote>From <a href="https://makeoptim.com/en/deep-learning/tensorflow-gpu-on-ubuntu">https://makeoptim.com/en/deep-learning/tensorflow-gpu-on-ubuntu</a></blockquote><h3>Intro</h3><ul><li>Ubuntu 18.04.5 LTS</li><li>GTX 1070</li><li>TensorFlow 2.4.1</li></ul><h3>Software requirements</h3><ul><li><a href="https://www.nvidia.com/drivers">NVIDIA® GPU drivers</a> — CUDA® 11.0 requires 450.x or higher.</li><li><a href="https://developer.nvidia.com/cuda-toolkit-archive">CUDA® Toolkit</a> — TensorFlow supports CUDA® 11 (TensorFlow &gt;= 2.4.0)</li><li><a href="https://developer.nvidia.com/cudnn">cuDNN SDK 8.0.4</a> <a href="https://developer.nvidia.com/rdp/cudnn-archive">cuDNN versions</a>.</li><li><em>(Optional)</em> <a href="https://docs.nvidia.com/deeplearning/sdk/tensorrt-install-guide/index.html">TensorRT 6.0</a> to improve latency and throughput for inference on some models.</li><li><a href="https://docs.conda.io/en/latest/miniconda.html">Miniconda</a> — Create a virtual environment.</li></ul><h3>Pre-installation Actions</h3><h4>GCC</h4><pre>$ gcc --version<br>Command &#39;gcc&#39; not found, but can be installed with:<br>sudo apt install gcc<br>$ sudo apt install gcc<br>$ gcc --version<br>gcc (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0<br>Copyright (C) 2017 Free Software Foundation, Inc.<br>This is free software; see the source for copying conditions.  There is NO<br>warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.</pre><h4>NVIDIA package repositories</h4><pre>$ wget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/cuda-ubuntu1804.pin<br>$ sudo mv cuda-ubuntu1804.pin /etc/apt/preferences.d/cuda-repository-pin-600<br>$ sudo apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/7fa2af80.pub<br>$ sudo add-apt-repository &quot;deb https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/ /&quot;<br>$ sudo apt-get update</pre><h3>NVIDIA machine learning</h3><pre>$ wget http://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64/nvidia-machine-learning-repo-ubuntu1804_1.0.0-1_amd64.deb</pre><pre>$ sudo apt install ./nvidia-machine-learning-repo-ubuntu1804_1.0.0-1_amd64.deb<br>$ sudo apt-get update</pre><h3>NVIDIA GPU driver</h3><pre>$ sudo apt-get install --no-install-recommends nvidia-driver-460</pre><blockquote><em>Note: You need to use version 460 here. The official website of TensorFlow writes 450. The actual test fails.</em></blockquote><p>Reboot and check that GPUs are visible using the following command.</p><pre>$ nvidia-smi<br>Mon Apr  5 16:17:17 2021<br>+-----------------------------------------------------------------------------+<br>| NVIDIA-SMI 460.32.03    Driver Version: 460.32.03    CUDA Version: 11.2     |<br>|-------------------------------+----------------------+----------------------+<br>| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |<br>| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |<br>|                               |                      |               MIG M. |<br>|===============================+======================+======================|<br>|   0  GeForce GTX 1070    On   | 00000000:01:00.0  On |                  N/A |<br>|  0%   48C    P8     9W / 180W |    351MiB /  8111MiB |      1%      Default |<br>|                               |                      |                  N/A |<br>+-------------------------------+----------------------+----------------------+</pre><pre>+-----------------------------------------------------------------------------+<br>| Processes:                                                                  |<br>|  GPU   GI   CI        PID   Type   Process name                  GPU Memory |<br>|        ID   ID                                                   Usage      |<br>|=============================================================================|<br>|    0   N/A  N/A       997      G   /usr/lib/xorg/Xorg                 18MiB |<br>|    0   N/A  N/A      1145      G   /usr/bin/gnome-shell               53MiB |<br>|    0   N/A  N/A      1353      G   /usr/lib/xorg/Xorg                108MiB |<br>|    0   N/A  N/A      1495      G   /usr/bin/gnome-shell               83MiB |<br>|    0   N/A  N/A      1862      G   ...AAAAAAAAA= --shared-files       82MiB |<br>+-----------------------------------------------------------------------------+</pre><h3>CUDA ToolKit and cuDNN</h3><pre>$ wget https://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1804/x86_64/libnvinfer7_7.1.3-1+cuda11.0_amd64.deb<br>$ sudo apt install ./libnvinfer7_7.1.3-1+cuda11.0_amd64.deb<br>$ sudo apt-get update</pre><pre># Install development and runtime libraries (~4GB)<br>$ sudo apt-get install --no-install-recommends \<br>    cuda-11-0 \<br>    libcudnn8=8.0.4.30-1+cuda11.0  \<br>    libcudnn8-dev=8.0.4.30-1+cuda11.0</pre><h3>TensorRT</h3><pre>$ sudo apt-get install -y --no-install-recommends libnvinfer7=7.1.3-1+cuda11.0 \<br>    libnvinfer-dev=7.1.3-1+cuda11.0 \<br>    libnvinfer-plugin7=7.1.3-1+cuda11.0</pre><h3>Miniconda</h3><p>Download Python 3.8 installation script from <a href="https://docs.conda.io/en/latest/miniconda.html">https://docs.conda.io/en/latest/miniconda.html</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2FzqedVG928b9FA9TjFO1Q.png" /></figure><p>Make the installation script executable</p><pre>$ chmod +x Miniconda3-latest-Linux-x86_64.sh</pre><p>Run the installation script</p><pre>$ ./Miniconda3-latest-Linux-x86_64.sh</pre><p>Restart the terminal and make conda activate.</p><h3>Virtual environment</h3><p>Create and activate a virtual environment.</p><pre>$ conda create -n tensorflow python=3.8.5<br>$ conda activate tensorflow</pre><h3>Install TensorFlow</h3><pre>$ pip install tensorflow==2.4.1</pre><p>Verify the install</p><pre>$ python -c &quot;import tensorflow as tf;print(&#39;Num GPUs Available: &#39;, len(tf.config.list_physical_devices(&#39;GPU&#39;)))&quot;<br>2021-04-05 16:20:00.426536: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcudart.so.11.0<br>2021-04-05 16:20:01.170305: I tensorflow/compiler/jit/xla_cpu_device.cc:41] Not creating XLA devices, tf_xla_enable_xla_devices not set<br>2021-04-05 16:20:01.170830: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcuda.so.1<br>2021-04-05 16:20:01.198917: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:941] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero<br>2021-04-05 16:20:01.199497: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1720] Found device 0 with properties:<br>pciBusID: 0000:01:00.0 name: GeForce GTX 1070 computeCapability: 6.1<br>coreClock: 1.7845GHz coreCount: 15 deviceMemorySize: 7.92GiB deviceMemoryBandwidth: 238.66GiB/s<br>2021-04-05 16:20:01.199519: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcudart.so.11.0<br>2021-04-05 16:20:01.201250: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcublas.so.11<br>2021-04-05 16:20:01.201278: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcublasLt.so.11<br>2021-04-05 16:20:01.201995: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcufft.so.10<br>2021-04-05 16:20:01.202159: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcurand.so.10<br>2021-04-05 16:20:01.203993: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcusolver.so.10<br>2021-04-05 16:20:01.204412: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcusparse.so.11<br>2021-04-05 16:20:01.204499: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library libcudnn.so.8<br>2021-04-05 16:20:01.204566: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:941] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero<br>2021-04-05 16:20:01.204897: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:941] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero<br>2021-04-05 16:20:01.205168: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1862] Adding visible gpu devices: 0<br>Num GPUs Available:  1</pre><h3>Install JupyterLab and matplotlib</h3><pre>$ pip install jupyterlab matplotlib</pre><h3>Run TensorFlow in JupyterLab</h3><pre>$ jupyter lab</pre><p>JupyterLab will be automatically opened in a browser.</p><p>Download and import CNN notebook from <a href="https://www.tensorflow.org/tutorials/images/cnn">https://www.tensorflow.org/tutorials/images/cnn</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*bq6ilvzcjfOt67haTcAXqg.png" /></figure><p>Restart Kernel and Run All Cells</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*MVB6AdoUF2C7FK4V0IKc4w.png" /></figure><p>When the train is running, check GPU processes, you can see ...nvs/tensorflow/bin/python, which means that the GPU is being used to train the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*mXGJZLl_KUkXUzyPJ9HLjQ.png" /></figure><pre>$ nvidia-smi<br>Mon Apr  5 16:36:28 2021<br>+-----------------------------------------------------------------------------+<br>| NVIDIA-SMI 460.32.03    Driver Version: 460.32.03    CUDA Version: 11.2     |<br>|-------------------------------+----------------------+----------------------+<br>| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |<br>| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |<br>|                               |                      |               MIG M. |<br>|===============================+======================+======================|<br>|   0  GeForce GTX 1070    On   | 00000000:01:00.0  On |                  N/A |<br>| 23%   54C    P2    72W / 180W |   7896MiB /  8111MiB |     55%      Default |<br>|                               |                      |                  N/A |<br>+-------------------------------+----------------------+----------------------+<br><br>+-----------------------------------------------------------------------------+<br>| Processes:                                                                  |<br>|  GPU   GI   CI        PID   Type   Process name                  GPU Memory |<br>|        ID   ID                                                   Usage      |<br>|=============================================================================|<br>|    0   N/A  N/A       997      G   /usr/lib/xorg/Xorg                 18MiB |<br>|    0   N/A  N/A      1145      G   /usr/bin/gnome-shell               73MiB |<br>|    0   N/A  N/A      1353      G   /usr/lib/xorg/Xorg                136MiB |<br>|    0   N/A  N/A      1495      G   /usr/bin/gnome-shell               53MiB |<br>|    0   N/A  N/A      1862      G   ...AAAAAAAAA= --shared-files       99MiB |<br>|    0   N/A  N/A      3181      C   ...nvs/tensorflow/bin/python     7507MiB |<br>+-----------------------------------------------------------------------------+</pre><h3>Further reading</h3><ul><li><a href="https://makeoptim.com/en/deep-learning/mac-tensorflow">Deep Learning (TensorFlow, JupyterLab, VSCode) on Mac</a></li><li><a href="https://makeoptim.com/en/deep-learning/mac-m1-tensorflow">Deep Learning (TensorFlow, JupyterLab, VSCode) on Apple Silicon M1 Mac</a></li></ul><h3>Reference</h3><ul><li><a href="https://www.tensorflow.org/install">https://www.tensorflow.org/install</a></li><li><a href="https://github.com/tensorflow/tensorflow/issues/39526">https://github.com/tensorflow/tensorflow/issues/39526</a></li><li><a href="https://www.tensorflow.org/guide/gpu">https://www.tensorflow.org/guide/gpu</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95373df8cfba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Learning (TensorFlow, Jupyterlab, VSCode) on Apple Silicon (M1) based Mac]]></title>
            <link>https://catchzeng.medium.com/deep-learning-tensorflow-jupyterlab-vscode-on-apple-silicon-m1-based-mac-c48881c49c22?source=rss-fa22b6cbf9d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/c48881c49c22</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[m1-mac]]></category>
            <category><![CDATA[jupyter]]></category>
            <dc:creator><![CDATA[Catch Zeng]]></dc:creator>
            <pubDate>Fri, 12 Mar 2021 08:24:28 GMT</pubDate>
            <atom:updated>2021-06-27T00:02:46.121Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deep Learning (TensorFlow, Jupyterlab, VSCode) on Apple Silicon M1 Mac</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8zoIsFB5dEiR_aSGgLDzqA.png" /></figure><p><em>Note: Since </em><a href="https://github.com/apple/tensorflow_macos"><em>https://github.com/apple/tensorflow_macos</em></a><em> has been archived, it is recommended that you follow </em><a href="https://makeoptim.com/en/deep-learning/tensorflow-metal"><em>Apple Silicon Mac M1 natively supports TensorFlow 2.5 GPU acceleration</em></a><em> and install the latest TensorFlow that supports GPU acceleration.</em></p><h3>Xcode</h3><p>Install Xcode from App Store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ItjGtZxZkrn8xHcj8paIBA.png" /></figure><h3>Command Line Tools</h3><p>Install <a href="https://developer.apple.com/download/more/?=command%20line%20tools">Xcode Command Line Tools</a> by downloading it from <a href="https://developer.apple.com/">Apple Developer</a> or by typing:</p><pre>$ xcode-select --install</pre><h3>Homebrew</h3><pre>$ /bin/bash -c &quot;$(curl -fsSL <a href="https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh">https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh</a>)&quot;</pre><h3>Miniforge</h3><p><strong><em>Anaconda cannot run on M1, Miniforge is used to replace it.</em></strong></p><p>Download the Miniforge3-MacOSX-arm64 from <a href="https://github.com/conda-forge/miniforge">https://github.com/conda-forge/miniforge</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*PxRLt_Z-aeTNsawDHST_qg.png" /></figure><p>Install Miniforge using the terminal.</p><pre>$ bash Miniforge3-MacOSX-arm64.sh</pre><p><strong>Restart</strong> the terminal and check it.</p><pre>$ which python<br>/Users/catchzeng/miniforge3/bin/python</pre><pre>$ which pip <br>/Users/catchzeng/miniforge3/bin/pip</pre><h3>Download Apple TensorFlow</h3><p>Download TensorFlow from <a href="https://github.com/apple/tensorflow_macos/releases">https://github.com/apple/tensorflow_macos/releases</a>, untar it, and go under the arm64 directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IbJkBQlEE5m7Ls4Fg8hV9g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*Pc8rkBbuH_fbXoRR8EXilw.png" /></figure><h3>Create virtual environment</h3><p>Create and activate a conda virtual environment with python 3.8 (as required for ATF 2.4).</p><pre>$ conda create -n tensorflow python=3.8<br>$ conda activate tensorflow</pre><h3>Install needed packages</h3><pre>$ brew install libjpeg</pre><pre>$ conda install -y pandas matplotlib scikit-learn jupyterlab</pre><blockquote>Note: libjpeg is a required dependency for matplotlib.</blockquote><h3>Install specific pip version and some other base packages</h3><pre>$ pip install --force pip==20.2.4 wheel setuptools cached-property six packaging</pre><blockquote>Note: Apple TensorFlow needs a specific pip version.</blockquote><h3>Install packages(numpy, grpcio, h5py) provided by Apple</h3><pre>$ pip install --upgrade --no-dependencies --force numpy-1.18.5-cp38-cp38-macosx_11_0_arm64.whl grpcio-1.33.2-cp38-cp38-macosx_11_0_arm64.whl h5py-2.10.0-cp38-cp38-macosx_11_0_arm64.whl</pre><h3>Install additional packages</h3><pre>$ pip install absl-py astunparse flatbuffers gast google_pasta keras_preprocessing opt_einsum protobuf tensorflow_estimator termcolor typing_extensions wrapt wheel tensorboard typeguard</pre><h3>Install TensorFlow</h3><pre>$ pip install --upgrade --no-dependencies --force tensorflow_macos-0.1a3-cp38-cp38-macosx_11_0_arm64.whl</pre><pre>$ pip install --upgrade --no-dependencies --force <br>tensorflow_addons_macos-0.1a3-cp38-cp38-macosx_11_0_arm64.whl</pre><p>Finally, upgrade the pip to give the developers the correct version.</p><pre>$ pip install --upgrade pip</pre><h3>Test</h3><p>TensorFlow</p><pre>$ python<br>Python 3.8.8 | packaged by conda-forge | (default, Feb 20 2021, 15:50:57)  <br>[Clang 11.0.1 ] on darwin <br>Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information. <br>&gt;&gt;&gt; import tensorflow as tf <br>&gt;&gt;&gt; print(tf.__version__) <br>2.4.0-rc0 <br>&gt;&gt;&gt;</pre><p>JupyterLab</p><pre>$ jupyter lab</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*KVok5RxGU0nGDGNJ9j4wfw.png" /></figure><pre>from tensorflow.keras import layers<br>from tensorflow.keras import models</pre><pre>model = models.Sequential()<br>model.add(layers.Conv2D(32, (3, 3), activation=&#39;relu&#39;, input_shape=(28, 28, 1)))<br>model.add(layers.MaxPooling2D((2, 2)))<br>model.add(layers.Conv2D(64, (3, 3), activation=&#39;relu&#39;))<br>model.add(layers.MaxPooling2D((2, 2)))<br>model.add(layers.Conv2D(64, (3, 3), activation=&#39;relu&#39;))</pre><pre>model.add(layers.Flatten())<br>model.add(layers.Dense(64, activation=&#39;relu&#39;))<br>model.add(layers.Dense(10, activation=&#39;softmax&#39;))</pre><pre>model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*JkGcieieEXW4poy_COVw-A.png" /></figure><pre>from tensorflow.keras.datasets import mnist<br>from tensorflow.keras.utils import to_categorical</pre><pre>(train_images, train_labels), (test_images, test_labels) = mnist.load_data()<br>train_images = train_images.reshape((60000, 28, 28, 1)) <br>train_images = train_images.astype(&#39;float32&#39;) / 255<br>test_images = test_images.reshape((10000, 28, 28, 1)) <br>test_images = test_images.astype(&#39;float32&#39;) / 255<br>train_labels = to_categorical(train_labels) <br>test_labels = to_categorical(test_labels)</pre><pre>model.compile(optimizer=&#39;rmsprop&#39;, <br>              loss=&#39;categorical_crossentropy&#39;,<br>              metrics=[&#39;accuracy&#39;])<br>model.fit(train_images, train_labels, epochs=5, batch_size=64)</pre><pre>test_loss, test_acc = model.evaluate(test_images, test_labels)<br>test_acc</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*Ybj0z7o3it3auU4XC8t92g.png" /></figure><h3>VSCode</h3><p>Install Python support</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*zziMmvWhcJGATeaMTmXV_w.png" /></figure><p>Select virtualenv and trust the notebook</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QROvGFhkD9AmSQu3b_rE1Q.png" /></figure><p>Run the notebook</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*YTV_wjYs5i4clbc1CX_d4g.png" /></figure><h3>Reference</h3><ul><li><a href="https://github.com/apple/tensorflow_macos">https://github.com/apple/tensorflow_macos</a></li><li><a href="https://github.com/apple/tensorflow_macos/issues/153">https://github.com/apple/tensorflow_macos/issues/153</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c48881c49c22" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>