<?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 Andrii Makarenko on Medium]]></title>
        <description><![CDATA[Stories by Andrii Makarenko on Medium]]></description>
        <link>https://medium.com/@andreymakarenko222?source=rss-b350f57c6941------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*anLedO7ec9Kc5WxsgHfg6g.jpeg</url>
            <title>Stories by Andrii Makarenko on Medium</title>
            <link>https://medium.com/@andreymakarenko222?source=rss-b350f57c6941------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 17:15:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andreymakarenko222/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[How I Improved My Diary Journaling Routine with AI]]></title>
            <link>https://medium.com/midform/how-i-improved-my-diary-journaling-routine-with-ai-c3842e95c5a7?source=rss-b350f57c6941------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3842e95c5a7</guid>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[diary]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[diary-writing]]></category>
            <dc:creator><![CDATA[Andrii Makarenko]]></dc:creator>
            <pubDate>Thu, 28 Sep 2023 17:37:40 GMT</pubDate>
            <atom:updated>2023-09-28T17:37:40.522Z</atom:updated>
            <content:encoded><![CDATA[<h4>How AI Reshaped My Self-Reflection</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GWaVI8Foz0ymzJidXPnIuA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@alejandroescamilla">Alejandro Escamilla</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Diary Writing: My Personal Journey</h3><p>Diary writing has been a part of my life for the past few years and now I definitely can say that it changed my life. It’s a practice that helps me to better understand my thoughts, mood, and the way I look at life. However, like many, I often fell behind in my diary-keeping, struggling to extract meaningful insights from my entries, and occasionally lacking the motivation to maintain this precious habit.</p><p>Yet, my greater challenge lay in the promises I made to myself. I always told myself that once a month, I would set aside time to review my diary-writing process and analyze my entries. It was a commitment I made to myself with the best intentions, but I consistently found myself postponing it for the future. This reluctance to engage in a comprehensive review prevented me from fully capitalizing on the potential benefits of my diary-writing practice. It left me with a sense of unfulfilled potential, as I missed out on the valuable self-reflection and growth that a regular review could offer.</p><p>I found a solution where I didn’t even expect it. It comes with a mobile Diary app named <a href="https://ecliso.web.app/">Ecliso</a>.</p><h3>Diary Writing in the Digital Age:</h3><p>Diaries have been a timeless method for people to record their thoughts and feelings. But in the digital age, why not harness the power of technology to enhance this age-old practice? Use the Diary App with AI Analyzer — a revolutionary tool designed to revolutionize the diary writing process. Here’s how it works:</p><h4>1. Intelligent Analysis:</h4><p>The AI Analyzer in Diary could read and analyze diary entries. It goes beyond simple text recognition by delving into the emotions and sentiments expressed in your words. This analysis forms the basis for a deeper understanding of your thoughts and feelings.</p><h4>2. Personalized Insights:</h4><p>Once your entries are analyzed, the AI generates a detailed rapport. This rapport provides you with valuable insights into your emotional state, patterns, and triggers. It’s like having a personal diary therapist at your fingertips!</p><h4>3. Answering Questions:</h4><p>My favorite part of this process starts at this point. After I answered myself to questions from AI I could ask questions that worried me and receive insightful answers.</p><p>AI helps me look at the situation from another perspective and it reminds me to consider different viewpoints, especially from those I care about, helping me become more understanding and accommodating.</p><h4>4. Inspiring Quotes:</h4><p>Sometimes, all we need is a little inspiration. The Diary Mobile App not only analyzes my entries but also suggests relevant famous quotes that align with my thoughts and emotions. These quotes can motivate, or inspire you, adding depth to your diary entries.</p><h4>5. Personalized Suggestions:</h4><p>AI Analyzer doesn’t stop at analysis, it offers personalized suggestions for self-improvement. Whether it recommends mindfulness exercises, journal prompts, or lifestyle changes, it adapts its advice to your unique needs.</p><h4>6. Monitoring Health and Mood:</h4><p>Your health and mood are closely intertwined with your diary entries. The AI Analyzer keeps track of trends in your mood and can provide you with insights on how your diary writing correlates with your overall well-being. This feature empowers you to make informed decisions for a healthier, happier life.</p><h3>Conclusion:</h3><p>Unlock the power of self-reflection and personal growth with the Diary Mobile App and its AI Analyzer. Say goodbye to traditional diary writing and welcome a new era of insightful, meaningful entries that lead to a better you.</p><p>Don’t wait any longer. Start your journey of self-discovery today by downloading the <a href="https://ecliso.web.app/">Ecliso Mobile App</a> from <a href="https://play.google.com/store/apps/details?id=com.andrushka.ecliso">Google Play Store</a> or <a href="https://apps.apple.com/app/id6451311931">Apple App Store</a>. For more information and updates, visit the app website <a href="https://ecliso.web.app/">here</a>.</p><p><a href="https://ecliso.web.app/">Join us</a> in the future of diary writing, where your words become a pathway to self-improvement, all with the help of AI: <a href="https://www.facebook.com/profile.php?id=100095329416647">Facebook</a> and <a href="https://www.instagram.com/ecliso.diary/?hl=en">Instagram</a>.</p><blockquote>Key Message: AI can improve our lives and help make our routines more enjoyable and efficient. Self-reflection is an important part of human life, and AI can bring new value to this process.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3842e95c5a7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/midform/how-i-improved-my-diary-journaling-routine-with-ai-c3842e95c5a7">How I Improved My Diary Journaling Routine with AI</a> was originally published in <a href="https://medium.com/midform">Midform</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bring Your Image Classification Model to Life with Flutter]]></title>
            <link>https://medium.com/geekculture/bring-your-image-classification-model-to-life-with-flutter-5148efbf3647?source=rss-b350f57c6941------2</link>
            <guid isPermaLink="false">https://medium.com/p/5148efbf3647</guid>
            <category><![CDATA[cnn]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[tensorflow-lite]]></category>
            <dc:creator><![CDATA[Andrii Makarenko]]></dc:creator>
            <pubDate>Sun, 26 Mar 2023 12:01:42 GMT</pubDate>
            <atom:updated>2023-03-26T12:01:42.404Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tEI2W78_5U8M7UivBrBNXA.png" /></figure><p>Welcome to the final article in my series on Conquering Rock-Paper-Scissors with Flutter and a Custom VGG16 Model for Image Classification. I’m excited to have you here with me to walk through the process of bringing image classification model to life in a Flutter app.</p><p>Throughout this series, I’ve covered everything from data preparation and training for custom CNNs using Keras, to integrating pre-trained models for improved performance. Now, in this final article, and I’ll guide you through the process of building a user interface and integrating your model with a Flutter app for real-time prediction of hand gestures.</p><h3>Series overview</h3><p>Before we get started, let’s recap what you have learned in the previous articles. In the first article <a href="https://medium.com/p/a81d3f671b94">Creating a Winning Model with Flutter and VGG16: A Comprehensive Guide</a>, we covered the basics of data preparation and training for a custom Convolutional Neural Network using the Keras framework. In the second article <a href="https://medium.com/p/ec185f763104">Boost Your Image Classification Model with pretrained VGG-16</a>, we integrated a pre-trained VGG-16 model into our custom detection task, which resulted in a significant performance boost, even with a small dataset.</p><p>Now, let’s dive into the final article and see how you can bring your image classification model to life in a Flutter app. I will use the Flutter framework to build a user interface that allows the user to use the camera of the device to detect their hand gesture (rock, paper, or scissors), and then use our image classification model to predict the correct gesture.</p><p>To get started, you will need to create a new Flutter project and import the necessary dependencies. We will also need to add code to handle the camera input and display the output on the screen.</p><p>Next, you will need to integrate your image classification model into the Flutter app. You will do this by loading the model into memory and then using it to make predictions on the camera stream.</p><p>So no more theory, just code.</p><p><strong>Model preparation</strong></p><p>Since you created and trained your model using the Keras framework, which is built on top of TensorFlow, you can convert your model to the TensorFlow format and run it on a Flutter app.</p><p>To convert the Keras model to TensorFlow format, you can use the tf.lite.TFLiteConverter.from_keras_model() function. This function creates a converter object for your model, which can then be used to convert the model to TensorFlow format.</p><p>Additionally, you can also convert the TensorFlow model to TensorFlow Lite format for optimized performance on mobile devices. TensorFlow Lite is a lightweight version of TensorFlow that is optimized for mobile and embedded devices. It enables faster inference times and smaller model sizes, making it ideal for mobile applications.</p><p>Here’s an example of how to convert a Keras model to TensorFlow Lite format using the from_keras_model() function:</p><pre>def convert(model):<br>    converter = tf.lite.TFLiteConverter.from_keras_model(model)<br>    tflite_model = converter.convert()<br><br>    with open(&#39;rock_paper_scissors_model.tflite&#39;, &#39;wb&#39;) as f:<br>        f.write(tflite_model)</pre><p>That’s it, now you have everything ready to start building your flutter app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/0*voyhx3H-2_1Rvh-c.png" /></figure><h3>Flutter Part</h3><p>To begin integrating your image classification model with a Flutter app, you need to create a new Flutter project and add some dependencies to our pubspec.yaml file. You will also need to create an assets folder at the root of our project and put our generated rock_paper_scissors_model.tflite file from the previous step into it.</p><p>Here are the steps to follow:</p><ol><li>Create a new Flutter project using your preferred IDE or running flutter create myapp it in the terminal.</li><li>Open the pubspec.yaml file and add the following dependencies:</li></ol><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  tflite_flutter: ^0.9.0<br>  tflite_flutter_helper: ^0.3.1<br>  camera: ^0.9.4+5</pre><p>The tflite_flutter and tflite_flutter_helper packages provide the tools for running your TensorFlow Lite model on mobile devices and the camera the package is used to access the device&#39;s camera for capturing frames from it.</p><p>3. Create an assets folder in the root of your project if it doesn’t already exist.</p><p>4. Put the rock_paper_scissors_model.tflite file that you generated in the previous step into the assets folder.</p><p>5. Do not forget to register assets in pubspec.yaml</p><pre>flutter:<br>  assets:<br>    - assets/rock_paper_scissors_model.tflite<br>  uses-material-design: true</pre><p>After you have it done you can start working on creating UI and running the model on camera.</p><p>Create StatefulWidget widget and initialize cameras in initState method</p><pre>class ScannerScreen extends StatefulWidget {<br>  @override<br>  _ScannerScreenState createState() =&gt; _ScannerScreenState();<br>}<br><br>class _ScannerScreenState extends State&lt;ScannerScreen&gt; {<br>  late CameraController cameraController;<br><br>  bool initialized = false;<br>  bool isWorking = false;<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    initialize();<br>  }<br><br>  Future&lt;void&gt; initialize() async {<br>    final cameras = await availableCameras();<br>    // Create a CameraController object<br>    cameraController = CameraController(<br>      cameras[0], // Choose the first camera in the list<br>      ResolutionPreset.medium, // Choose a resolution preset<br>    );<br><br>    // Initialize the CameraController and start the camera preview<br>    await cameraController.initialize();<br>    // Listen for image frames<br>    await cameraController.startImageStream((image) {<br>      // Make predictions only if not busy<br>      if (!isWorking) {<br>        processCameraImage(image);<br>      }<br>    });<br><br>    setState(() {<br>      initialized = true;<br>    });<br>  }</pre><p>After you should create Classifier a class that will be responsible for the classification process.</p><pre>enum DetectionClasses { rock, paper, scissors, nothing }<br><br>class Classifier {<br>  /// Instance of Interpreter<br>  late Interpreter _interpreter;<br><br>  static const String modelFile = &quot;rock_paper_scissors_model.tflite&quot;;<br><br>  /// Loads interpreter from asset<br>  Future&lt;void&gt; loadModel({Interpreter? interpreter}) async {<br>    try {<br>      _interpreter = interpreter ??<br>          await Interpreter.fromAsset(<br>            modelFile,<br>            options: InterpreterOptions()..threads = 4,<br>          );<br><br>      _interpreter.allocateTensors();<br>    } catch (e) {<br>      print(&quot;Error while creating interpreter: $e&quot;);<br>    }<br>  }<br><br>  /// Gets the interpreter instance<br>  Interpreter get interpreter =&gt; _interpreter;<br>}</pre><p>In loadModel the method I’m initializing Interpreter from tflite_flutter package and loading my model into it. You can also verify your model information using _interpreter . For example, you could check the input shape of your model using the following line:</p><pre>_interpreter.getInputTensor(0).shape // Will return [1, 150, 150, 3]</pre><p>Next, you can create an instance of Classifier in _ScannerScreenState and call loadModel into initialize method.</p><pre>class _ScannerScreenState extends State&lt;ScannerScreen&gt; {<br>  final classifier = Classifier();<br>  <br>  ...<br><br>  Future&lt;void&gt; initialise() async {<br>    await classifier.loadModel();<br>    ...</pre><p>So not you could add processCameraImage the method which will take images from the camera frame by frame and do prediction based on it.</p><pre>Future&lt;void&gt; processCameraImage(CameraImage cameraImage) async {<br>  setState(() {<br>    isWorking = true;<br>  });<br><br>  DetectionClasses results = await classifier.predict(convertedImage);<br><br>  if (detected != result) {<br>    setState(() {<br>      detected = results;<br>    });<br>  }<br><br>  setState(() {<br>    isWorking = false;<br>  });<br>}</pre><p>Clarifier should convert CameraImage to list of pixels values in shape [1, 150, 150, 3] and put them into Interpreter . To do it you first should convert the camera image to package:image/image.dart instanceImage . To do it you can use the following code:</p><pre>import &#39;package:camera/camera.dart&#39;;<br>import &#39;package:image/image.dart&#39; as imageLib;<br><br>/// ImageUtils<br>class ImageUtils {<br>  /// Converts a [CameraImage] in YUV420 format to [imageLib.Image] in RGB format<br>  static imageLib.Image convertYUV420ToImage(CameraImage cameraImage) {<br>    final int width = cameraImage.width;<br>    final int height = cameraImage.height;<br><br>    final int uvRowStride = cameraImage.planes[1].bytesPerRow;<br>    final int uvPixelStride = cameraImage.planes[1].bytesPerPixel!;<br><br>    final image = imageLib.Image(width, height);<br><br>    for (int w = 0; w &lt; width; w++) {<br>      for (int h = 0; h &lt; height; h++) {<br>        final int uvIndex =<br>            uvPixelStride * (w / 2).floor() + uvRowStride * (h / 2).floor();<br>        final int index = h * width + w;<br><br>        final y = cameraImage.planes[0].bytes[index];<br>        final u = cameraImage.planes[1].bytes[uvIndex];<br>        final v = cameraImage.planes[2].bytes[uvIndex];<br><br>        image.data[index] = ImageUtils.yuv2rgb(y, u, v);<br>      }<br>    }<br>    return image;<br>  }<br><br>  /// Convert a single YUV pixel to RGB<br>  static int yuv2rgb(int y, int u, int v) {<br>    // Convert yuv pixel to rgb<br>    int r = (y + v * 1436 / 1024 - 179).round();<br>    int g = (y - u * 46549 / 131072 + 44 - v * 93604 / 131072 + 91).round();<br>    int b = (y + u * 1814 / 1024 - 227).round();<br><br>    // Clipping RGB values to be inside boundaries [ 0 , 255 ]<br>    r = r.clamp(0, 255);<br>    g = g.clamp(0, 255);<br>    b = b.clamp(0, 255);<br><br>    return 0xff000000 |<br>    ((b &lt;&lt; 16) &amp; 0xff0000) |<br>    ((g &lt;&lt; 8) &amp; 0xff00) |<br>    (r &amp; 0xff);<br>  }<br>}</pre><p>After add predict method to Classifier .</p><pre>import &#39;dart:typed_data&#39;;<br><br>import &#39;package:image/image.dart&#39; as img;<br>import &#39;package:rock_paper_scissors_mobile/classes.dart&#39;;<br>import &#39;package:tflite_flutter/tflite_flutter.dart&#39;;<br><br>class Classifier {<br> <br>  ...<br><br>  Future&lt;DetectionClasses&gt; predict(img.Image image) async {<br>    img.Image resizedImage = img.copyResize(image, width: 150, height: 150);<br><br>    // Convert the resized image to a 1D Float32List.<br>    Float32List inputBytes = Float32List(1 * 150 * 150 * 3);<br>    int pixelIndex = 0;<br>    for (int y = 0; y &lt; resizedImage.height; y++) {<br>      for (int x = 0; x &lt; resizedImage.width; x++) {<br>        int pixel = resizedImage.getPixel(x, y);<br>        inputBytes[pixelIndex++] = img.getRed(pixel) / 127.5 - 1.0;<br>        inputBytes[pixelIndex++] = img.getGreen(pixel) / 127.5 - 1.0;<br>        inputBytes[pixelIndex++] = img.getBlue(pixel) / 127.5 - 1.0;<br>      }<br>    }<br><br>    // Reshape to input format specific for model. 1 item in list with pixels 150x150 and 3 layers for RGB<br>    final input = inputBytes.reshape([1, 150, 150, 3]);<br><br>    // Output container<br>    final output = Float32List(1 * 4).reshape([1, 4]); <br><br>    // Run data throught model<br>    interpreter.run(input, output);<br><br>    // Get index of maxumum value from outout data. Remember that models output means:<br>    // Index 0 - rock, 1 - paper, 2 - scissor, 3 - nothing.<br>    final predictionResult = output[0] as List&lt;double&gt;;<br>    double maxElement = predictionResult.reduce(<br>      (double maxElement, double element) =&gt;<br>          element &gt; maxElement ? element : maxElement,<br>    );<br>    return DetectionClasses.values[predictionResult.indexOf(maxElement)];<br>  }<br>}</pre><p>Now you can build Ui for your app:</p><pre>class _ScannerScreenState extends State&lt;ScannerScreen&gt; {<br>  <br>  ...<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&#39;Flutter Camera Demo&#39;),<br>      ),<br>      body: initialized<br>          ? Column(<br>              children: [<br>                SizedBox(<br>                  height: MediaQuery.of(context).size.width,<br>                  width: MediaQuery.of(context).size.width,<br>                  child: CameraPreview(cameraController),<br>                ),<br>                Text(<br>                  &quot;Detected: ${detected.label}&quot;,<br>                  style: const TextStyle(<br>                    fontSize: 28,<br>                    color: Colors.blue,<br>                  ),<br>                ),<br>              ],<br>            )<br>          : const Center(child: CircularProgressIndicator()),<br>    );<br>  }</pre><p>That’s it. But if you will run it you probably will notice that app is lagging. It’s because the running process is complex and resource-intensive in <strong>UI-Isolate. </strong>To have it work smoothly and fast you need to consider moving the calculation process to separate isolate.</p><h3>Calculation isolate</h3><p>First of all create IsolateUtils using the following code:</p><pre>/// Bundles data to pass between Isolate<br>class IsolateData {<br>  CameraImage cameraImage;<br>  int interpreterAddress;<br>  SendPort responsePort;<br><br>  IsolateData({<br>    required this.cameraImage,<br>    required this.interpreterAddress,<br>    required this.responsePort,<br>  });<br>}<br><br>class IsolateUtils {<br>  static const String DEBUG_NAME = &quot;InferenceIsolate&quot;;<br><br>  late Isolate _isolate;<br>  final ReceivePort _receivePort = ReceivePort();<br>  late SendPort _sendPort;<br><br>  SendPort get sendPort =&gt; _sendPort;<br><br>  Future&lt;void&gt; start() async {<br>    _isolate = await Isolate.spawn&lt;SendPort&gt;(<br>      entryPoint,<br>      _receivePort.sendPort,<br>      debugName: DEBUG_NAME,<br>    );<br><br>    _sendPort = await _receivePort.first;<br>  }<br><br>  static void entryPoint(SendPort sendPort) async {<br>    final port = ReceivePort();<br>    sendPort.send(port.sendPort);<br><br>    await for (final IsolateData isolateData in port) {<br>      Classifier classifier = Classifier();<br>      // Restore interpreter from main isolate<br>      await classifier.loadModel(interpreter: Interpreter.fromAddress(isolateData.interpreterAddress));<br><br>      final convertedImage = ImageUtils.convertYUV420ToImage(isolateData.cameraImage);<br>      DetectionClasses results = await classifier.predict(convertedImage);<br>      isolateData.responsePort.send(results);<br>    }<br>  }<br><br>  void dispose() {<br>    _isolate.kill();<br>  }<br>}</pre><p>It’s gets IsolateData from the port and initialize Classifier with Interpreter form main isolate using his address Interpreter.fromAddress(isolateData.interpreterAddress)</p><p>After it’s done the same preprocessing with CameraImage as before and puts it to Classifier . DetectionClasses the result sends back to the main isolate using isolateData.responsePort.send(results); .</p><p>After you have it done, you have to provide a few improvements to your _ScannerScreenState code.<br>Create IsolateUtils instance and call isolateUtils.start() in initialize method.</p><p>Add inference method</p><pre>Future&lt;DetectionClasses&gt; inference(CameraImage cameraImage) async {<br>  ReceivePort responsePort = ReceivePort();<br>  final isolateData = IsolateData(<br>    cameraImage: cameraImage,<br>    interpreterAddress: classifier.interpreter.address,<br>    responsePort: responsePort.sendPort,<br>  );<br><br>  isolateUtils.sendPort.send(isolateData);<br>  var result = await responsePort.first;<br><br>  return result;<br>}</pre><p>and call it in processCameraImage method:</p><pre>Future&lt;void&gt; processCameraImage(CameraImage cameraImage) async {<br>  setState(() {<br>    isWorking = true;<br>  });<br><br>  final result = await inference(cameraImage);<br><br>  if (detected != result) {<br>    setState(() {<br>      detected = result;<br>    });<br>  }<br><br>  setState(() {<br>    lastShot = DateTime.now();<br>    isWorking = false;<br>  });<br>}</pre><p>The full code of _ScannerScreenState is following:</p><pre>class ScannerScreen extends StatefulWidget {<br>  @override<br>  _ScannerScreenState createState() =&gt; _ScannerScreenState();<br>}<br><br>class _ScannerScreenState extends State&lt;ScannerScreen&gt; {<br>  late CameraController cameraController;<br>  late Interpreter interpreter;<br>  final classifier = Classifier();<br>  final isolateUtils = IsolateUtils();<br><br>  bool initialized = false;<br>  bool isWorking = false;<br>  DetectionClasses detected = DetectionClasses.nothing;<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    initialize();<br>  }<br><br>  Future&lt;void&gt; initialize() async {<br>    // Load main isolate Interpreter<br>    await classifier.loadModel();<br><br>    final cameras = await availableCameras();<br>    // Create a CameraController object<br>    cameraController = CameraController(<br>      cameras[0], // Choose the first camera in the list<br>      ResolutionPreset.medium, // Choose a resolution preset<br>    );<br><br>    // Start Inference isolate<br>    await isolateUtils.start();<br><br>    // Initialize the CameraController and start the camera preview<br>    await cameraController.initialize();<br>    // Listen for image frames<br>    await cameraController.startImageStream((image) {<br>      // Make predictions only if not busy <br>      if (!isWorking) {<br>        processCameraImage(image);<br>      }<br>    });<br><br>    setState(() {<br>      initialized = true;<br>    });<br>  }<br><br>  Future&lt;void&gt; processCameraImage(CameraImage cameraImage) async {<br>    setState(() {<br>      isWorking = true;<br>    });<br><br>    final result = await inference(cameraImage);<br><br>    if (detected != result) {<br>      detected = result;<br>    }<br><br>    setState(() {<br>      isWorking = false;<br>    });<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: const Text(&#39;Flutter Camera Demo&#39;),<br>      ),<br>      body: initialized<br>          ? Column(<br>              children: [<br>                SizedBox(<br>                  height: MediaQuery.of(context).size.width,<br>                  width: MediaQuery.of(context).size.width,<br>                  child: CameraPreview(cameraController),<br>                ),<br>                Text(<br>                  &quot;Detected: ${detected.label}&quot;,<br>                  style: const TextStyle(<br>                    fontSize: 28,<br>                    color: Colors.blue,<br>                  ),<br>                ),<br>              ],<br>            )<br>          : const Center(child: CircularProgressIndicator()),<br>    );<br>  }<br><br>  Future&lt;DetectionClasses&gt; inference(CameraImage cameraImage) async {<br>    ReceivePort responsePort = ReceivePort();<br>    final isolateData = IsolateData(<br>      cameraImage: cameraImage,<br>      interpreterAddress: classifier.interpreter.address,<br>      responsePort: responsePort.sendPort,<br>    );<br><br>    isolateUtils.sendPort.send(isolateData);<br>    var result = await responsePort.first;<br><br>    return result;<br>  }<br><br>  @override<br>  void dispose() {<br>    cameraController.dispose();<br>    isolateUtils.dispose();<br>    super.dispose();<br>  }<br>}</pre><p>By doing these steps you should have the following result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/173/1*y8N5Fsuhq1BQFQ9OpKih5A.gif" /></figure><h3>Summary</h3><p>In this final article, you have successfully integrated your custom image classification model into a Flutter app. By combining the power of machine learning with the user-friendly Flutter framework, you have created a real-time hand gesture detection app that is accurate, responsive, and easy to use.</p><p>Throughout this series, I have covered a range of topics, from the basics of building a custom CNN model to the more advanced techniques of transfer learning and model optimization. We have also explored the challenges of integrating machine learning models into mobile apps and provided practical solutions to overcome them.</p><p>By following this series, you now have the skills and knowledge to build your own custom image classification models, optimize them for performance, and deploy them in a mobile app using Flutter and TensorFlow Lite. I hope you have found this series useful and informative.</p><p>If you have any questions or feedback, feel free to leave a comment below or check out the code for this project on my <strong>GitHub</strong> repository:</p><p><a href="https://github.com/Andrushka1012/rock_paper_scissors">GitHub - Andrushka1012/rock_paper_scissors: CNN Network for detecting rock papier scissors with flutter client</a></p><p>Thank you for reading and see you soon :P</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5148efbf3647" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/bring-your-image-classification-model-to-life-with-flutter-5148efbf3647">Bring Your Image Classification Model to Life with Flutter</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boost Your Image Classification Model with pretrained VGG-16]]></title>
            <link>https://medium.com/geekculture/boost-your-image-classification-model-with-pretrained-vgg-16-ec185f763104?source=rss-b350f57c6941------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec185f763104</guid>
            <category><![CDATA[vgg16]]></category>
            <category><![CDATA[transfer-learning]]></category>
            <dc:creator><![CDATA[Andrii Makarenko]]></dc:creator>
            <pubDate>Sun, 26 Mar 2023 11:31:40 GMT</pubDate>
            <atom:updated>2023-03-26T11:31:40.912Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P2BZFAk2HZPeYAB6dmcHAw.png" /></figure><p>Welcome back to the article series on building an object detection model in Keras and running it on a Flutter mobile app. In the first article, <a href="https://medium.com/p/a81d3f671b94">Creating a Winning Model with Flutter and VGG16: A Comprehensive Guide</a>, covered the process of data preparation and training for your own Convolutional Neural Network using the Keras framework.</p><p>Now that your dataset is ready to use and all data is normalized for training, you can proceed with the next steps. If you need a refresher on how to prepare the dataset and normalize the data, feel free to review the previous article in this series or review the full code yourself in the <a href="https://github.com/Andrushka1012/rock_papier_scissors">project repository</a>.</p><p>In this second article, I’ll explore a powerful technique to improve the performance of your model even with a small dataset — integrating a pre-trained VGG-16 model for your custom detection task. By adding more generalizations of patterns, you can achieve significant gains in accuracy on real-life images.</p><p>In the final article of this series, <a href="https://medium.com/p/5148efbf3647">Bring Your Image Classification Model to Life with Flutter</a>, I’ll walk you through the process of bringing your image classification model to life in a Flutter app for Rock-Paper Scissors. By the end of this series, you’ll have a comprehensive understanding of how to build and deploy advanced image classification models, and how to integrate them with mobile applications.</p><p>So, let’s dive in and start building!</p><h3>Transfer learning</h3><p>Transfer learning is a technique in machine learning and deep learning where a pre-trained model is used as a starting point for a new related task. Instead of building a model from scratch and training it on a large dataset, transfer learning allows us to leverage the knowledge already gained by the pre-trained model.</p><p>The pre-trained model is typically trained on a large dataset, such as ImageNet, to solve a general computer vision problem. By using this pre-trained model, you can reuse the learned feature representations, which are general enough to be applied to a new related task, such as detecting Rock-Paper-Scissors gestures.</p><p>In transfer learning, you typically take the pre-trained model and replace the final layer with a new layer that is specific to the new task. This new layer is then trained on the smaller dataset specific to the new task, while the rest of the pre-trained model is frozen and its weights are fixed. This allows us to fine-tune the pre-trained model on the new task while avoiding overfitting and reducing training time.</p><p>Transfer learning has become an important technique in deep learning and has led to significant improvements in accuracy and speed for a wide range of computer vision tasks.</p><p><strong>VGG-16</strong></p><p>In this article, I will be using a custom pretrained VGG-16 Keras model. The VGG16 model is a popular image classification model that won the ImageNet competition in 2014. It has 16 layers, including 13 convolutional layers and 3 fully connected layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*4Q8Da2uTHSuyOU2yK3fD_A.jpeg" /><figcaption><a href="http://www.renom.jp/notebooks/image_processing/neural-style-transfer/notebook.html">Source</a></figcaption></figure><p>In Keras, you can copy the VGG-16 structure using the following code, or import from <strong><em>keras.applications.vgg16</em></strong><em>:</em></p><pre>from keras.models import Sequential<br>from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout<br><br># Define the model as a sequential sequence of layers<br>vgg16_custom = Sequential()<br><br># Define convolutional layers<br>vgg16_custom.add(Conv2D(64, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;, input_shape=(224, 224, 3)))<br>vgg16_custom.add(Conv2D(64, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;))<br>vgg16_custom.add(MaxPooling2D((2, 2)))<br><br>vgg16_custom.add(Conv2D(128, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;))<br>vgg16_custom.add(Conv2D(128, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;))<br>vgg16_custom.add(MaxPooling2D((2, 2)))<br><br>vgg16_custom.add(Conv2D(256, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;))<br>vgg16_custom.add(Conv2D(256, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;))<br>vgg16_custom.add(Conv2D(256, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;))<br>vgg16_custom.add(MaxPooling2D((2, 2)))<br><br>vgg16_custom.add(Conv2D(512, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;))<br>vgg16_custom.add(Conv2D(512, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;))<br>vgg16_custom.add(Conv2D(512, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;))<br>vgg16_custom.add(MaxPooling2D((2, 2)))<br><br>vgg16_custom.add(Conv2D(512, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;))<br>vgg16_custom.add(Conv2D(512, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;))<br>vgg16_custom.add(Conv2D(512, (3, 3), activation=&#39;relu&#39;, padding=&#39;same&#39;))<br>vgg16_custom.add(MaxPooling2D((2, 2)))<br><br># Define classification layers<br>vgg16_custom.add(Flatten())<br>vgg16_custom.add(Dense(4096, activation=&#39;relu&#39;))<br>vgg16_custom.add(Dropout(0.5))<br>vgg16_custom.add(Dense(4096, activation=&#39;relu&#39;))<br>vgg16_custom.add(Dropout(0.5))<br>vgg16_custom.add(Dense(3, activation=&#39;softmax&#39;))<br><br># Print a summary of the model architecture<br>vgg16_custom.summary()</pre><p>The pretrained VGG16 model is trained on a large dataset of images and can recognize a wide range of features. However, the output layer of the model is specific to the dataset it was trained on. In this case, you need to replace the output layer with a new layer that is specific to the Rock-Paper-Scissors dataset.</p><p>To do this, in the beginning, I load the pretrained VGG16 model using the Keras library in Python.</p><pre><br>from keras.applications.vgg16 import VGG16<br><br>vgg16 = VGG16(weights=&#39;imagenet&#39;, input_shape=self.input_shape, classes=self.classes, include_top=False)</pre><p>By setting <strong><em>weights=’imagenet’</em></strong> we will fetch the pretrained hyperparams. It could take some time, but you need to do it only once.</p><p>I freeze the weights of the remaining layers so that they are not retrained during the training process.</p><pre>for layer in vgg16.layers:<br>            layer.trainable = False</pre><p>Then, I remove the last layer of the model and add new hidden layers with 256 units and an output layer with three units at the end, one for each gesture.<br>Also, the <strong>Dropout</strong> layer is added to avoid overfitting by randomly dropping out neurons during training, thus forcing the network to learn more robust features.</p><pre>x = Flatten()(vgg16.output)<br>x = Dense(256, activation=&#39;relu&#39;)(x)<br>x = Dropout(0.5)(x)<br>predictions = Dense(self.classes, activation=&#39;softmax&#39;)(x)<br><br>self.model = Model(inputs=vgg16.input, outputs=predictions)</pre><p>The full code of the custom model class is following:</p><pre>class RockPaperScissorsVgg16:<br>    def __init__(self, input_width, input_height):<br>        self.input_shape = (input_width, input_height, 3)<br>        self.classes = 3<br>        self.model = None<br>        self.build_model()<br><br>    def build_model(self):<br>        vgg16 = VGG16(weights=&#39;imagenet&#39;, input_shape=self.input_shape, classes=self.classes, include_top=False)<br><br>        for layer in vgg16.layers:<br>            layer.trainable = False<br><br>        x = Flatten()(vgg16.output)<br>        x = Dense(256, activation=&#39;relu&#39;)(x)<br>        x = Dropout(0.5)(x)<br>        predictions = Dense(self.classes, activation=&#39;softmax&#39;)(x)<br><br>        self.model = Model(inputs=vgg16.input, outputs=predictions)<br>        self.model.compile(optimizer=&#39;adam&#39;, loss=&#39;categorical_crossentropy&#39;, metrics=[&#39;accuracy&#39;])</pre><p>Note that for this classification I’m using</p><pre>optimizer=&#39;adam&#39;, loss=&#39;categorical_crossentropy&#39;</pre><p>There are no hard and fast rules for choosing an optimizer or a loss function for training CNN models, as the best choice depends on the specific problem and the characteristics of the data. It is often a good practice to experiment with different optimizers and learning rates, as well as different loss functions, to find the combination that works best for a given problem.</p><p>For example, you can try using the <strong>RMSprop</strong> or <strong>SGD</strong> optimizer with different learning rates and momentum values, and see how they affect the training performance of your model. It’s also worth experimenting with different loss functions, such as <strong>mean squared</strong> error or <strong>mean absolute error</strong>, to see if they perform better for your particular problem.</p><p>However, it’s worth noting that for <strong>multi-class classification</strong> problems, the <strong>categorical cross-entropy</strong> loss function is commonly used and often gives a good performance. This loss function measures the difference between the predicted class probabilities and the true class labels for each input, and encourages the model to output high probabilities for the correct class and low probabilities for the incorrect classes.</p><h4>Training</h4><p>The training process is the same as in the <a href="https://medium.com/p/a81d3f671b94">previous article</a>, so you only need to provide a few changes:</p><pre>def train_vgg16(train_images, train_labels) -&gt; Model:<br>    vgg16 = RockPaperScissorsVgg16(INPUT_WIDTH, INPUT_HEIGHT)<br>    model = vgg16.model<br>    model.summary()<br><br>    train_generator, validation_generator = get_generators(train_images, train_labels)<br><br>    model.fit(<br>        train_generator,<br>        steps_per_epoch=40,<br>        epochs=50,<br>        validation_data=validation_generator,<br>        validation_steps=10,<br>        callbacks=[StopByAccuracyCallback()]<br>    )<br><br>    return model</pre><p>After training your CNN model on the first dataset containing real-life pictures on different backgrounds, you may see a significant improvement in accuracy compared to before, from <strong>15%</strong> to <strong>74%</strong>. This is a significant improvement and indicates that your model is better able to handle the complexity and variability of real-world images.</p><p>When evaluating the model’s performance on a second and third dataset, you may still see good accuracy, around <strong>95%,</strong> and <strong>98%</strong> respectively, which indicates that the model can generalize well to new and unseen data.</p><p>However, you should also consider other evaluation metrics such as precision, recall, and F1 score, as well as analyse the model’s confusion matrix to see which classes are most often confused with each other. This can help identify areas for improvement in the model’s architecture or training data.</p><p>You can have a look at these datasets in the <a href="https://github.com/Andrushka1012/rock_papier_scissors/tree/main/rock_papier_scissors/data">project repository</a>.</p><h3>Nothing detection</h3><p>Although achieving high accuracy on multiple datasets is a good indication that your model is robust, it’s important to note that the model’s predictions may not always be accurate in real-world scenarios. One reason for this is that the model may predict certain classes on inputs where they do not actually appear. This could be because the implementation only allows for three possible outputs, and the model does not consider the possibility that some inputs may not contain any of the proposed classes.</p><p>When I, for the first time, ran a model with my desktop camera, it predicted that my face looked like a rock. I guess it thinks I’m the next Dwayne Johnson!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*CahSNl6lEFCtszQO-cpuYg.gif" /></figure><p>To address this issue, you may consider adding a new class of images that could have everything except the other classes. This could include images of walls, sky, sports cars, or even kittens, depending on the context of the problem. This new class would act as a catch-all for inputs that do not belong to any of the other classes. <br>To create this set of images, I just used <a href="https://picsum.photos/">picsum photos</a> API to populate the set with random images, just for the sake of an example. In real-world problems, you should think about a better choice of an image set.</p><p>To fill all datasets with new images you could use the script with the following functions:</p><pre>def generate_noice(original_dir: str):<br>    url = f&quot;https://picsum.photos/{INPUT_WIDTH}/{INPUT_HEIGHT}&quot;<br><br>    # Send a GET request to the URL and receive the response<br>    response = requests.get(url)<br><br>    # Open the response content as an image using PIL<br>    image = Image.open(BytesIO(response.content))<br><br>    # Save the image to your local machine<br>    image.save(f&quot;{original_dir}/nothing/{str(uuid.uuid4())}.jpg&quot;)<br><br><br># Generate nothing dataset with random images<br>def generate_nothing_dataset():<br>    for i in range(100):<br>        generate_noice(TRAIN_DIR_1)<br>    for i in range(30):<br>        generate_noice(TEST_DIR_1)<br><br>    for i in range(500):<br>        generate_noice(TRAIN_DIR_2)<br>    for i in range(125):<br>        generate_noice(TEST_DIR_2)<br><br>    for i in range(400):<br>        generate_noice(TRAIN_DIR_3)<br>    for i in range(30):<br>        generate_noice(TEST_DIR_3)</pre><p>Remember that you also should update your model output shape for new class in <strong>RockPaperScissorsVgg16</strong>:</p><pre>self.classes = 4</pre><p>and add a new category to the list.</p><pre>CATEGORIES = [&quot;rock&quot;, &quot;paper&quot;, &quot;scissors&quot;, &quot;nothing&quot;]</pre><p>Label <strong>[0, 0, 0, 1] </strong>— will indicate that the detected category is <strong>nothing </strong>and no other categories were found.</p><h3>Summary</h3><p>In conclusion, I’ve demonstrated how to build an image classification app that can recognize Rock-Paper-Scissor&#39;s gestures using a custom VGG16 model. By leveraging the power of transfer learning and pre-trained models, you were able to significantly improve the accuracy of the model.</p><p>I hope this tutorial has been helpful in getting you started with building your own custom image classification models. With the knowledge and skills you’ve gained, you can apply these techniques to a wide range of computer vision tasks, from object detection to facial recognition.</p><p>If you have any questions or feedback, feel free to leave a comment below or check out the code for this project on my <strong>GitHub</strong> repository</p><p><a href="https://github.com/Andrushka1012/rock_paper_scissors">GitHub - Andrushka1012/rock_paper_scissors: CNN Network for detecting rock papier scissors with flutter client</a></p><p>In the last article from this series <a href="https://medium.com/p/5148efbf3647">Bring Your Image Classification Model to Life with Flutter</a><strong> </strong>you<strong> </strong>will finally bring your model to run on mobile devices.</p><p>Thank you for reading, and happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec185f763104" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/boost-your-image-classification-model-with-pretrained-vgg-16-ec185f763104">Boost Your Image Classification Model with pretrained VGG-16</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Winning Model with Flutter and VGG16: A Comprehensive Guide]]></title>
            <link>https://medium.com/geekculture/creating-a-winning-model-with-flutter-and-vgg16-a-comprehensive-guide-a81d3f671b94?source=rss-b350f57c6941------2</link>
            <guid isPermaLink="false">https://medium.com/p/a81d3f671b94</guid>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[cnn]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[rock-paper-scissors]]></category>
            <dc:creator><![CDATA[Andrii Makarenko]]></dc:creator>
            <pubDate>Sun, 26 Mar 2023 11:01:42 GMT</pubDate>
            <atom:updated>2023-03-30T10:14:50.326Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8QlebLgtbuPqEvHGiG1qeA.png" /></figure><p>Are you ready to take your image classification skills to the next level? In this article series, I’ll guide you through the complete process of building, training, and integrating a Keras CNN model with a Flutter app for detecting Rock-Paper-Scissors gestures. But we won’t stop there! I’ll also show you how to boost your model’s performance using transfer learning with a pre-trained VGG16 model.</p><ul><li>In the first article of the series, I’ll cover the process of data preparation and training for your own <strong>Convolutional Neural Network</strong> using the Keras framework.</li><li>In the second article <a href="https://medium.com/p/ec185f763104">Boost Your Image Classification Model with pretrained VGG-16</a> I’ll dive into the technique of integrating a pre-trained <strong>VGG-16</strong> model for our custom detection task, resulting in a significant improvement in performance, even with a small dataset.</li><li>Finally, in the last article <a href="https://medium.com/p/5148efbf3647">Bring Your Image Classification Model to Life with Flutter</a> I’ll walk you through the process of bringing your image classification model to life in a Flutter app for Rock-Paper-Scissors. By the end of this series, you’ll have a comprehensive understanding of how to build and deploy advanced image classification models, and how to integrate them with mobile applications.</li></ul><p>By the end of the series, you will have results like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/173/1*y8N5Fsuhq1BQFQ9OpKih5A.gif" /></figure><h3>Introduction</h3><p>Image classification is an important technique in computer vision that involves assigning labels to images based on their content. It has many applications, including object recognition, facial recognition, and medical image analysis. In this article, I will be discussing image classification of Rock-Paper-Scissors using our own <strong>Convolutional Neural Network</strong> (CNN for short) model from scratch.</p><p>We will start by preparing the data and building the model, then we will train the model and deploy it in a Flutter app for image classification.</p><h3>Few words about CNN</h3><p>A Convolutional Neural Network (CNN) is a type of deep learning model that is used for image classification, object detection, and other computer vision tasks. It works by taking an input image and passing it through several layers of convolution, pooling, and activation functions. The <strong>convolutional</strong> layers apply a set of filters to the input image, which detects different features/patterns on the image. The <strong>pooling</strong> layers reduce the dimensionality of the output from the convolutional layers, making the model more efficient. Finally, the activation functions add nonlinearity to the output of the model, allowing it to capture complex patterns in the input image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*Sszmk64qnrzY3QbyRm9Tpw.jpeg" /><figcaption>Introduction to Convolutional Neural Networks(Stanford University, 2018)</figcaption></figure><h3>Preparing the Data</h3><p>The first step in any image classification task is to collect and prepare the data. In this case, you will need a dataset of images of hands making the Rock-Paper-Scissors gestures. There are several ways to collect the data but for this example, I decided to use 3 different datasets to train and test the network.</p><p>The first dataset consisted of real photos captured by myself, with about 40 pictures for each class. Although this was the smallest dataset, it contained images captured on different backgrounds, which allowed us to test the performance of models on real-life videos and photos.<br>The second dataset contained about 800 images for each class, with all of them placed on a white background. This dataset helped us improve the generalization capability of models by training them on a diverse range of images.<br>Finally, the third dataset contained about 650 real photos for each class, all placed on a green background. This dataset was useful for training our models to distinguish between the different classes despite the presence of similar background colors.<br>You can have a look at them in the project <a href="https://github.com/Andrushka1012/rock_papier_scissors/tree/main/rock_papier_scissors/data">repository</a>.</p><p>Also to add more generality all images were processed using <a href="https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/image/ImageDataGenerator">ImageDataGenerator</a> from the TensorFlow package. More about it will be described in the training section.</p><h4>Train, Validation, and Test Sets in Machine Learning</h4><p>For better ML training best practice is to split your data into 3 datasets:</p><ul><li><strong>Train set — </strong>the sample of data used to fit the model</li><li><strong>Validation set</strong> — the sample of data used to provide an unbiased evaluation of a model fit on the training dataset while tuning model <a href="https://towardsdatascience.com/parameters-and-hyperparameters-aa609601a9ac">hyperparameters</a></li><li><strong>Test set</strong> — the sample of data used for unbiased estimation of the final model fit on the training dataset</li></ul><p>This entire set should contain unique data samples for better geneticism. If some elements are duplicated, it may lead to worse results and the model may not achieve the required geneticism in pattern detection.</p><p>You can read more about datasets in <a href="https://machinelearningmastery.com/difference-test-validation-datasets/">Jason Brownlee’s excellent article</a>.<br>In this project, I will have <strong>train</strong> and <strong>test</strong> sets, and <strong>validation</strong> will be taken from the training set.</p><p><strong>Labels</strong></p><p>Convolutional neural networks (CNNs) are widely used for image classification tasks, and they work by detecting features in the image at different levels of abstraction. In the final layer of the CNN, you need to specify the number of outputs equal to the number of classes you want to classify. In the case of our example of the game “Rock, Paper, Scissors,” you have three possible classes, so the output of the model will be a 1D array with a dimension of [1,3].</p><p>However, it is important to inform our model about which class each input image belongs to. This is done through labeling, where we associate each image with its corresponding class label. During training, we pass the model the expected output as a 1D array and highlight the neuron responsible for detecting the correct class label.</p><p>In the “Rock, Paper, Scissors” project, I will be using the following labels:</p><ul><li><strong>[1, 0, 0]</strong> for Rock</li><li><strong>[0, 1, 0]</strong> for Paper</li><li><strong>[0, 0, 1]</strong> for Scissors</li></ul><p>By using these labels during training, this CNN model will learn to associate specific features in the input image with each class label, improving its accuracy in predicting the correct class for new images.</p><h4>Image preprocessing</h4><p>Before feeding into the network all datasets should be normalized to the same size and converted to a pixels array. In this project, the network is trained to work with RGB images in dimensions 150x150 pixels. So the correct shape of the input entity is <strong>[N, 150, 150, 3]</strong> where <strong>N </strong>is the amount entities fitted into the network by the same time, <strong>150</strong> and <strong>150 </strong>are image dimensions and <strong>3</strong> is three layers of RGB image for each color. You also could try with one layer, but in this case, you should convert your image to grayscale format. Note that in this case performance will be much lower.</p><pre><br>INPUT_WIDTH = 150<br>INPUT_HEIGHT = 150<br><br>TARGET_SIZE = (INPUT_WIDTH, INPUT_HEIGHT)<br>NUM_CATEGORIES = 3<br><br>TRAIN_DIR_1 = &quot;data/Dataset/train&quot;<br>TEST_DIR_1 = &quot;data/Dataset/test/&quot;<br>TRAIN_DIR_2 = &quot;data/Dataset2/train&quot;<br>TEST_DIR_2 = &quot;data/Dataset2/test/&quot;<br>TRAIN_DIR_3 = &quot;data/Dataset3/train&quot;<br>TEST_DIR_3 = &quot;data/Dataset3/test/&quot;<br><br>CATEGORIES = [&quot;rock&quot;, &quot;paper&quot;, &quot;scissors&quot;]<br><br><br>def fetch_images(cat, directory):<br>    images_path = [f&quot;{directory}/{cat}/{f}&quot; for f in os.listdir(f&quot;{directory}/{cat}&quot;) if<br>                   f.endswith(&quot;.jpeg&quot;) or f.endswith(&quot;.jpg&quot;)]<br>    preprocessed = [preprocess_image(x) for x in images_path]<br>    return preprocessed<br><br><br>def preprocess_image(image_path):<br>    img = load_img(image_path, target_size=TARGET_SIZE)<br>    img = img.convert(&quot;RGB&quot;)<br><br>    img = img_to_array(img)<br>    img = np.expand_dims(img, axis=0)<br>    return img<br><br><br>def get_dataset(train, test):<br>    train_images = []<br>    train_labels = []<br>    test_images = []<br>    test_labels = []<br><br>    for i, category in enumerate(CATEGORIES):<br>        train_images_cat = fetch_images(category, train)<br>        test_images_cat = fetch_images(category, test)<br><br>        train_labels_cat = to_categorical(np.full(len(train_images_cat), i), NUM_CATEGORIES)<br>        test_labels_cat = to_categorical(np.full(len(test_images_cat), i), NUM_CATEGORIES)<br><br>        train_images.extend(train_images_cat)<br>        test_images.extend(test_images_cat)<br>        train_labels.extend(train_labels_cat)<br>        test_labels.extend(test_labels_cat)<br><br>    train_images = np.array(train_images)<br>    train_labels = np.array(train_labels)<br>    test_images = np.array(test_images)<br>    test_labels = np.array(test_labels)<br><br>    train_images = np.squeeze(train_images, axis=1)<br>    test_images = np.squeeze(test_images, axis=1)<br>    # shuffle elements in train dataset<br>    combined = list(zip(train_images, train_labels))<br>    shuffle(combined)<br>    train_images, train_labels = zip(*combined)<br><br>    return np.array(train_images), np.array(train_labels), test_images, test_labels<br><br></pre><h3><strong>Building the Model</strong></h3><p>Since you already have prepared data for training it’s a good time to create your model.<br>For this project I used the following model structure:</p><pre>class CnnModel(keras.Model):<br>    def __init__(self, num_classes=3):<br>        super().__init__()<br><br>        self.conv1 = Conv2D(32, (3, 3), activation=&#39;relu&#39;, input_shape=(INPUT_WIDTH, INPUT_HEIGHT, 3))<br>        self.pool1 = MaxPooling2D((2, 2))<br>        self.conv2 = Conv2D(64, (3, 3), activation=&#39;relu&#39;)<br>        self.pool2 = MaxPooling2D((2, 2))<br>        self.conv3 = Conv2D(128, (3, 3), activation=&#39;relu&#39;)<br>        self.pool3 = MaxPooling2D((2, 2))<br>        self.conv4 = Conv2D(256, (3, 3), activation=&#39;relu&#39;)<br>        self.pool4 = MaxPooling2D((2, 2))<br>        self.flatten = Flatten()<br>        self.d1 = Dense(512, activation=&#39;relu&#39;)<br>        self.d2 = Dense(256, activation=&#39;relu&#39;)<br>        self.d3 = Dense(num_classes, activation=&#39;softmax&#39;)<br><br>        self.build((None, INPUT_WIDTH, INPUT_HEIGHT, 3))<br>        self.compile(optimizer=&#39;adam&#39;, loss=&#39;categorical_crossentropy&#39;, metrics=[&#39;accuracy&#39;])</pre><p>Here is a quick explanation of the above code:</p><ul><li>The first layer consists of 32 filters, each with a size of 3, and an input shape of 150 x 150 pixels. The activation function used is ReLU (rectified linear unit).</li><li>Next, it has a 2 x 2 max-pooling layer. Max-pooling is a technique that helps to reduce overfitting by creating an abstract representation of the image features.</li><li>The same layers are then repeated, with an increase in the number of filters: 64, 128, and 256.</li><li>A flatten layer is used to convert the output of the convolutional layers into a 2D representation that can be passed to the fully connected layers.</li><li>Two dense hidden layers follow, with 512 and 256 neurons, respectively. The activation function used is again ReLU.</li><li>The final layer is the output layer, which contains 3 neurons, one for each class in the output. The activation function used for this layer is softmax, which converts the output of each neuron into a probability distribution across the classes.</li></ul><p>This CNN architecture is a common one used for simple image classification tasks. Its success depends on the quality of the training data, the complexity of the task, and the amount of regularization applied to prevent overfitting.</p><h4>Training</h4><p>For training, I decided to merge all my tree datasets into one and perform testing on each of them and together. Also as I already mentioned <a href="https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/image/ImageDataGenerator">ImageDataGenerator</a> was used to make images more general and help the model to learn not the position of the hand during detection, but the general patterns of each class.</p><p>Here is an example of using a generator to add random transformations for image</p><pre>train_datagen = ImageDataGenerator(<br>    rescale=1. / 255,<br>    rotation_range=20,<br>    horizontal_flip=True,<br>    shear_range=0.2,<br>    fill_mode=&#39;wrap&#39;,<br>    validation_split=0.2<br>)</pre><ul><li><strong>rescale</strong>: change the scale of each value in the matrix representation of the image by multiplying it by 1/255. This also saves us from the very impotent work of normalizing the input data. After this operation, all input values will be in the range from 0 to 1, whereas before they were in the range from 0 to 255 (pixel power).</li><li><strong>rotation_range</strong>: apply random rotations of 20 degrees.</li><li><strong>horizontal_flip</strong>: setting this argument to True means that a random horizontal flip will be applied to the inputs.</li><li><strong>shear_range</strong>:<strong> </strong>apply a shear intensity of 0.2. That is, the shear angle is counterclockwise.</li><li><strong>fill_mode</strong>: fill the empty area after rotation with the nearest pixel values.</li><li><strong>validation_split: </strong>allocate 20 percent of the training sample to the validation sample</li></ul><p>After you could create generators for train and validation sets</p><pre># Apply the augmentation to the training data<br>train_generator = train_datagen.flow(<br>    train_images,<br>    train_labels,<br>    batch_size=batch_size,<br>    shuffle=True,<br>    subset=&#39;training&#39;<br>)<br><br>validation_generator = train_datagen.flow(<br>    train_images,<br>    train_labels,<br>    batch_size=batch_size,<br>    shuffle=True,<br>    subset=&#39;validation&#39;<br>)</pre><p>Finally, you can fit your data into the model to train</p><pre>model = CnnModel()<br>model.summary() # print model summary with hyperparameters information<br><br>train_generator, validation_generator = ...<br>model.fit(<br>    train_generator,<br>    epochs=50,<br>    validation_data=validation_generator,<br>    callbacks=[StopByAccuracyCallback()]<br>)<br></pre><p>One more thing. I used <strong>StopByAccuracyCallback</strong> to prevent model overtraining. We want to stop training at the moment when the accuracy of the latest epoch reaches a value of 98%. That is why I added <br><em>metrics=[‘accuracy’]</em> to the model compilation. Callback implementation could be like the following:</p><pre>accuracy_threshold = 98e-2<br><br><br>class StopByAccuracyCallback(Callback):<br>    def on_epoch_end(self, epoch, logs=None):<br>        if logs.get(&#39;accuracy&#39;) &gt;= accuracy_threshold:<br>            print(&#39;Accuracy has reach = %2.2f%%&#39; % (logs[&#39;accuracy&#39;] * 100), &#39;training has been stopped.&#39;)<br>            self.model.stop_training = True</pre><p>Upon checking the test results, you can see that the model’s performance on the second and third datasets is acceptable, achieving an accuracy of <strong>95%</strong> and <strong>98%</strong>, respectively. However, when it comes to the first dataset, which contains real photos, the model’s performance leaves much to be desired(about <strong>15%</strong> of accuracy). This suggests that the model is overfitting to the synthetic data and not generalizing well to real-world images. Also second and third dataset contains images captured on the same background, whereas in real life it’s not always possible.</p><p>To improve the model’s performance on real-world data, you could consider collecting more real-world images to include in the training data. You could also try using transfer learning, where we leverage a pre-trained CNN model on a larger dataset and fine-tune it for the specific task. This process will be described in the <a href="https://medium.com/p/ec185f763104">next article</a> for the series.<br>Ultimately, improving the model’s performance on real-world data will require careful experimentation and analysis to determine the best approach.</p><h3>Thanks for reading</h3><p>Thank you for taking the time to read this article. I hope you found it informative and helpful in getting started with building your own image classification models.</p><p>In the next article of this series, <a href="https://medium.com/p/ec185f763104">Boost Your Image Classification Model with pretrained VGG-16</a> I will dive deeper into the technique of transfer learning and show you how to use the power of a pre-trained VGG-16 model for your custom tasks.</p><p>If you’re interested in exploring the code for this project in more detail, you can find the complete implementation on my GitHub repository at</p><p><a href="https://github.com/Andrushka1012/rock_paper_scissors">GitHub - Andrushka1012/rock_paper_scissors: CNN Network for detecting rock papier scissors with flutter client</a></p><p>Feel free to fork the repository and modify the code to suit your needs.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a81d3f671b94" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/creating-a-winning-model-with-flutter-and-vgg16-a-comprehensive-guide-a81d3f671b94">Creating a Winning Model with Flutter and VGG16: A Comprehensive Guide</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>