<?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 Sunny K. Tuladhar on Medium]]></title>
        <description><![CDATA[Stories by Sunny K. Tuladhar on Medium]]></description>
        <link>https://medium.com/@SunnyKTuladhar?source=rss-36012891cc8c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*senKSE9JOFToxf0NlfkpIQ.jpeg</url>
            <title>Stories by Sunny K. Tuladhar on Medium</title>
            <link>https://medium.com/@SunnyKTuladhar?source=rss-36012891cc8c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 21:21:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@SunnyKTuladhar/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[Data Augmentation on Ultralytics for training YOLOv5/YOLOv8]]></title>
            <link>https://medium.com/@SunnyKTuladhar/data-augmentation-on-ultralytics-for-training-yolov5-yolov8-97a8dab31fef?source=rss-36012891cc8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/97a8dab31fef</guid>
            <category><![CDATA[albumentations]]></category>
            <category><![CDATA[yolov8]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[data-augmentation]]></category>
            <category><![CDATA[ultralytics]]></category>
            <dc:creator><![CDATA[Sunny K. Tuladhar]]></dc:creator>
            <pubDate>Sat, 09 Mar 2024 04:33:02 GMT</pubDate>
            <atom:updated>2024-09-12T03:44:51.679Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to apply data augmentation for training YOLOv5/v8 in Ultralytics using the Albumentations library in Python?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*-8uhMDxBcEMCD7VD" /><figcaption>Data Augmentation Example (Source: <a href="https://ubiai.tools/what-are-the-advantages-anddisadvantages-of-data-augmentation-2023-update/">ubiai.com</a>)</figcaption></figure><blockquote>Disclaimer: This only works on Ultralytics version == 8.0.186 and models YoloV8, not on YoloV9. Works for Detection and not for segmentation.</blockquote><p>Augmentations are an important aspect of image data training for classification, detection, and segmentation tasks. They help add meaningful additions to the dataset by applying visual transformations to the existing images hence increasing the dataset with minimal costs.</p><p>The <a href="https://www.ultralytics.com/">Ultralytics </a>library is a handy framework for training YOLOv5 and YOLOv8 models. To implement augmentations they do have the <a href="https://docs.ultralytics.com/modes/train/#train-settings">hyperparameters in the “train settings”</a> but it offers very limited augmentations.</p><p><a href="https://albumentations.ai/">Albumentations</a> is a great library for this as it offers a variety of augmentations from rotations to weather conditions (Details about this are in the following chapters). Ultralytics has the code to integrate albumentations into their code but one has to edit the <a href="https://docs.ultralytics.com/fr/reference/data/augment/"><em>augment.py</em> </a>from the source code itself. This is tedious and hard to implement in automated scenarios.</p><p>Here’s a workaround using Python’s <a href="https://medium.com/r?url=https%3A%2F%2Fwww.lambdatest.com%2Fblog%2Fmonkey-patching-in-python%2F">Monkey Patch </a>to use the albumentations library in this framework by augmenting the function to augment the data without having to edit the source code <em>augment.py</em> file itself.</p><pre>#This is the train.py file<br><br>from ultralytics.data.augment import Albumentations<br>from ultralytics.utils import LOGGER, colorstr<br><br>def __init__(self, p=1.0):<br>        &quot;&quot;&quot;Initialize the transform object for YOLO bbox formatted params.&quot;&quot;&quot;<br>        self.p = p<br>        self.transform = None<br>        prefix = colorstr(&quot;albumentations: &quot;)<br>        try:<br>            import albumentations as A         <br><br>            # Insert required transformation here<br>            T = [<br>                A.RandomRain(p=0.1, slant_lower=-10, slant_upper=10, <br>                              drop_length=20, drop_width=1, drop_color=(200, 200, 200), <br>                              blur_value=5, brightness_coefficient=0.9, rain_type=None)<br>                A.Rotate(limit = 10, p=0.5),<br>                A.Blur(p=0.1),<br>                A.MedianBlur(p=0.1),<br>                A.ToGray(p=0.01),<br>                A.CLAHE(p=0.01),<br>                A.ImageCompression(quality_lower=75, p=0.0),<br>            ]<br>            self.transform = A.Compose(T, bbox_params=A.BboxParams(format=&quot;yolo&quot;, label_fields=[&quot;class_labels&quot;]))<br><br>            LOGGER.info(prefix + &quot;, &quot;.join(f&quot;{x}&quot;.replace(&quot;always_apply=False, &quot;, &quot;&quot;) for x in T if x.p))<br>        except ImportError:  # package not installed, skip<br>            pass<br>        except Exception as e:<br>            LOGGER.info(f&quot;{prefix}{e}&quot;)<br><br>Albumentations.__init__ = __init__<br><br>model = YOLO(&#39;yolov8n.yaml&#39;).load(&#39;yolov8n.pt&#39;)<br><br>results = model.train(data=&#39;coco128.yaml&#39;, epochs=100, imgsz=640, augment = True)</pre><p>To verify this works, the <strong>albumentations </strong>will show up in the logs in the console to show all the configurations once the code is running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FDm9R6Hwmckp5IdLaesavg.png" /><figcaption>Console Log taken from ClearML. It shows the different augmentations from the albumentations library being used while training.</figcaption></figure><p>Keep in mind the above example is a <a href="https://www.programiz.com/python-programming/generator">generator</a>-type augmentation. This does not save the augmented images. This helps in saving up memory as the augmentations are only created when required in the training run.</p><p>To save the augmented images you can use the approach from <a href="https://medium.com/red-buffer/apply-data-augmentation-on-yolov5-yolov8-dataset-958e89d4bc5d">this blog</a>.</p><h4>Albumentations</h4><p>This is an incredible library for image data augmentation. It offers a wide variety of augmentations for basic-level image augmentation as well as detection and segmentation tasks. It offers both pixel and spatial-level transformations. <br>Here is the <a href="https://albumentations.ai/docs/api_reference/full_reference/">full list of augmentation and its parameters</a>.<br>Here is the <a href="https://github.com/albumentations-team/albumentations_examples">list of examples of albumentations in Colab</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Pg3buJgDGMw2ezbI.jpg" /><figcaption>Augmentation Pipeline. (Source: <a href="https://albumentations.ai/docs/getting_started/image_augmentation/">Albumentations doc</a>)</figcaption></figure><p>Albumentations Documentations:<br>1. <a href="https://albumentations.ai/docs/getting_started/image_augmentation/">Basic Image Classification Augmentation classifications </a><br>2. <a href="https://albumentations.ai/docs/getting_started/bounding_boxes_augmentation/">Bounding Box level Augmentation</a></p><h4>Monkey Patching</h4><p>Monkey Patching allows users to augment existing functionality, and add custom methods on the go without having to modify the original source code. In our case, we modified the source code of the augment.py file from the Ultralytics library as per our needs. We patched it with the augmentations we require.</p><p>This technique is useful but you have to be careful with its usage, especially with library functions, as mentioned <a href="https://en.wikipedia.org/wiki/Monkey_patch#Pitfalls">here</a>. For example, we need to upgrade our library to use a new feature. If this upgraded version has a different version of our monkey patched function in the source code, it could lead to problems. Several other<a href="https://dev.to/napoleon039/monkey-patching-what-is-it-and-should-you-be-using-it-50db"> issues with Monkey Patching </a>exist because it involves modifying the functions of the source code without actually modifying the source code.</p><h4>Conclusion</h4><p>The method proposed in the blog is, as mentioned, a <strong>workaround </strong>for now. It does the job for me and I am able to train my model as required. However, for larger and automated ML pipelines this would not be ideal. Until Ultralytics provides us with a better solution these workarounds are what we have got.</p><p>Many thanks to <a href="https://medium.com/u/867e2478a502">Jenish Shrestha</a> for letting me know Monkey Patch even existed and helping me wrap my head around this technique.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97a8dab31fef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Two things ChatGPT can get wrong: math and facts. Why?]]></title>
            <link>https://medium.com/@SunnyKTuladhar/two-things-chatgpt-can-get-wrong-math-and-facts-why-b40e50dc68cd?source=rss-36012891cc8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b40e50dc68cd</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[hallucinations]]></category>
            <category><![CDATA[bard-vs-chatgpt]]></category>
            <category><![CDATA[aritificial-intelligence]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Sunny K. Tuladhar]]></dc:creator>
            <pubDate>Sat, 03 Feb 2024 03:19:10 GMT</pubDate>
            <atom:updated>2024-02-03T03:19:10.889Z</atom:updated>
            <content:encoded><![CDATA[<h4>How is one of the biggest AI Tools in the world making mistakes that even a normal person can figure out?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1HCB4-Ubt_RLMjFPFj778g.jpeg" /><figcaption>DALLE-3: Prompt: ChatGPT is a cute confused robot (Image by Author)</figcaption></figure><p>ChatGPT 3.5, and Large Language Models(LLMs) in general, are unlike anything we have ever seen. Why do they make these seemingly silly mistakes? Here we talk about ChatGPT getting two things wrong: the math and the facts.</p><h3>Math</h3><p>ChatGPT can get basic arithmetic wrong when the sequence is long enough. This is unprecedented. No computer in the world has ever gotten arithmetic wrong, no matter how long the equation. Our everyday calculator, the most basic form of a computer, will never get math wrong. So what is going on here?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*tQRncZzVLpJu0crQTfQTqQ.png" /><figcaption>The actual answer for this is 14 but ChatGPT says 18. Try this out with a different long sequence of numbers. (Image by Author)</figcaption></figure><p>ChatGPT is not our everyday AI tool. It was designed to tackle one of the most difficult problems for AI, <strong>language</strong>. Language has always eluded AI because of its irrational nature. The past tense of <em>walk </em>is <em>walked</em>, but <em>go </em>is <em>went?</em> ChatGPT was trained on so much language data that it was able to overcome all of this linguistic madness to give us coherent answers in proper English. ChatGPT was designed for language, <em>period. </em>When you introduce this <em>Language </em>model to math, problems arise.</p><p>There is no inherent “math logic” embedded into the fundamental model of ChatGPT (although <a href="https://www.wolframalpha.com/">plugins </a>might help). The model does not actually add numbers together when we write the above symbols. It has an idea of what math is. From all the corpus it has read, it “speculates” the answer. However, it does not do actual arithmetic operations behind the scenes when we type the symbols ‘+’ or ‘-’.</p><p>So next time you are dealing with numbers and numerical values with ChatGPT don&#39;t be surprised if it gets them wrong sometimes. Try to use <a href="https://techpilot.ai/ai-tools-to-solve-math-problems/">other AI tools for maths</a>. Also, read <a href="https://www.baeldung.com/cs/chatgpt-math-problems#:~:text=First%20of%20all%2C%20the%20primary,mathematical%20concepts%20and%20problem%2Dsolving.">this</a> if you want an in-depth explanation of this ChatGPT math mistake.</p><p>All this being said, this highlights a bigger underlying issue with ChatGPT and how it is being used today. ChatGPT functions by predicting the logical next word in a sentence. It is not bound by the traditional concept of computers using logic. Computers giving wrong output despite being given the right input is quite new.</p><h3>Facts</h3><p>ChatGPT has been notorious for <a href="https://www.businessinsider.com/chatgpt-may-make-up-facts-openai-cto-mira-murati-says-2023-2#:~:text=The%20bot%20%22may%20make%20up,bot%20may%20not%20always%20be">making up facts</a> while it answers your questions. This has been termed <a href="https://en.wikipedia.org/wiki/Hallucination_(artificial_intelligence)">hallucination</a> and it has always been a common problem in using AI in natural language. According to OpenAI’s CTO Mira Murati’s interview with Time magazine, “ChatGPT generates its responses by predicting the logical next word in a sentence, but what’s logical to the bot may not always be accurate”. To put it poorly, ChatGPT is a really powerful autocomplete <em>(It is a lot more than that, but just an analogy)</em></p><p>ChatGPT does not care about facts. Unlike Google, it does not search the internet for the information you asked for and return the answer. It gives you back the answer that “seems” sensible enough, based on its training data and the context it has seen. This is most visibly seen when it quotes <a href="https://teche.mq.edu.au/2023/02/why-does-chatgpt-generate-fake-references/#:~:text=ChatGPT%3A%20The%20fake%20references%20in,similar%20to%20the%20training%20data.">fake research papers from academia</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*c3mmBDfRCXeTiDZPYsMKrA.png" /><figcaption>Tweet by <a href="https://twitter.com/dsmerdon">David Smerdon</a> on a fake paper shown by ChatGPT when asked “What is the most cited economics paper of all time”. The paper ChatGPT is mentioning does not exist.</figcaption></figure><p>This is not limited to ChatGPT. Google’s Bard also made a <a href="https://www.theverge.com/2023/2/8/23590864/google-ai-chatbot-bard-mistake-error-exoplanet-demo">factual error on its launch day</a> which was quite unfortunate. It caused Google’s shares to lose $100 billion in value. Bard claimed that the James Webb Space Telescope took the very first image of a planet outside our solar system which was incorrect.</p><p>So what can be done about it? First of all, avoid ChatGPT for fact-based information. Google is always more reliable for this. Second, you can try this handy prompt I got from Vanderbilt University’s course on <a href="https://www.coursera.org/learn/prompt-engineering/supplement/3ebdR/format-of-the-fact-check-list-pattern">Prompt Engineering for ChatGPT</a>. It is called the Fact-list Pattern. An example is in the image shown below.</p><blockquote><strong>Fact-List Pattern</strong>: Whenever you output text, generate a set of facts that are contained in the output. The set of facts should be inserted at the end of the output. The set of facts should be the fundamental facts that could undermine the veracity of the output if any of them are incorrect.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mc8Jjhg-tcbXys7qUTEsjg.png" /><figcaption>Sample of the fact-list pattern. The pattern does not change the answer. It only makes ChatGPT list out the facts it used in the answer which we can check for credibility. (Image by Author)</figcaption></figure><p>You can also try <a href="https://www.perplexity.ai/">Perplexity.ai</a> a new AI-powered answer engine (as opposed to a search engine) backed up by notable investors including Nvdia and Jeff Bezos. It is designed not to hallucinate and gives all the references for its answers.</p><h3>Conclusion</h3><p>Given these limitations, ChatGPT is still an extremely powerful tool. If used well it provides very useful output and saves a lot of our time. A general recommendation would be to use ChatGPT for closed-world problems where you know all the facts and can verify the results. Two of my personal use cases for ChatGPT are <strong>writing </strong>and <strong>coding</strong>. Both of these results can be verified with little effort by the user. We will discuss in a future article why it is best for these two use cases. Until then use ChatGPT responsibly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b40e50dc68cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CAD Automation: Parametric Modeling and Custom CAD Tools]]></title>
            <link>https://medium.com/@SunnyKTuladhar/cad-automation-parametric-modeling-and-custom-cad-tools-c491d71181b4?source=rss-36012891cc8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c491d71181b4</guid>
            <category><![CDATA[parametric-design]]></category>
            <category><![CDATA[computer-aided-design]]></category>
            <category><![CDATA[mechanical-engineering]]></category>
            <category><![CDATA[application]]></category>
            <category><![CDATA[software]]></category>
            <dc:creator><![CDATA[Sunny K. Tuladhar]]></dc:creator>
            <pubDate>Mon, 10 Aug 2020 07:54:14 GMT</pubDate>
            <atom:updated>2020-08-10T08:04:16.477Z</atom:updated>
            <content:encoded><![CDATA[<h4>Computer Aided Design has been evolving over the past years. Read on about how parametric modeling and custom CAD Tools have helped shape this industry.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*o9-Uda7uH2naaKvP.jpg" /><figcaption>Source: <a href="https://favpng.com/png_view/design-computer-aided-design-solidworks-computer-aided-engineering-technical-drawing-png/NjEhx50n">favpng.com</a> by <a href="https://favpng.com/png_user/lanzilloduk6">lanzilloduk6</a></figcaption></figure><p>Computer Aided Design(CAD) is now the back bone of mechanical part design. A tool used so extensively that we tend to forget that all a CAD software is a computer program, which runs on code. And just like all other things that run on code, this can be automated. And the main purpose of automation is to save time and be more efficient. There are many hyperlinks(Underlined text) throughout the article and I encourage you to check all of them out while reading this.</p><p>More on CAD and Automation in this article of mine: <a href="https://tinyurl.com/wtq4ndv">https://tinyurl.com/wtq4ndv</a></p><p>Here we will talk about Custom CAD Tools and Parametric Modeling and how they help to save time and make a CAD user more efficient. We will mainly be talking about CAD through the perspective of a Mechanical Engineer but the core concept can be generalized into other fields where it is used. The software I will be giving examples are of <strong>SolidWorks </strong>and <a href="https://www.onshape.com/"><strong>Onshape</strong></a><strong> </strong>but the same features are available in most other B-rep CAD software (e.g. Creo Parametric,CATIA, Fusion 360, Siemens NX etc.)(<em>We will discuss what B-rep is in another article). </em>Also,<em> </em>I hear <a href="https://www.freecadweb.org/index.php"><strong>FreeCAD</strong></a><strong>(</strong>written in python)is an awesome example of customization as the entire software is open-source but for the time being the software is a little difficult to use for me. But it hasn’t even reached a version 1.0(as of this article being written) so I guess better things are in store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tE5TnCE_aCPLyRUjVlna5w.png" /><figcaption>Common B-rep CAD software (that I have used) which can be automated</figcaption></figure><h3><strong>Parametric Modeling</strong></h3><p>Parametric modeling is modeling done is such a way that the dimensions of a part are dependent on a few parameters. All the dimensions are assigned in manner that it changes according to the requirement of the model and the design. This is achieved by assigning some main parameters and then giving dimensions based on a relation to these parameters. This allows for small changes and adjustments to be made in the model very fast and accurately.</p><p>Here’s a small example of a parametric model made in SolidWorks. The cuboid shown below has three dimensions. “Width(Main)”, “height” and “T”. “Width(Main)” is its main parameter. The “height” and “T” are dependent on “Width(Main)” based on an equation(relation). The relation is shown below<em>(dimensions in mm)</em></p><p><em>Height = Width(main) — 20</em></p><p><em>T= Width(main) — 50</em></p><p>So to change the entire model you only need to change the “Width(Main)” dimension. Below you can see the examples with “Width(Main)” = 60 which changes the height = 60–20 = 40, T =60–50 =10. Similarly for “Width(Main)” = 100 : height = 100–20 = 80, T =100–50 =50</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*uM_PPbQrsAJwQYRbpcwOwQ.png" /><figcaption>Simple cuboid with “Width(MAIN)” dimension = 60. The rest of the dimensions are defined by the Width.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*3CgRqiR2xIKTVw2OKIoX0g.png" /><figcaption>Simple cuboid with “Width(MAIN)” dimension = 100. The rest of the dimensions are defined by the Width</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*5P40koSQmYrEzWOBjc2BoQ.png" /></figure><p>Here’s another example using legos. The main parameter of this model is marked in red box (NUMBER OF POSTS). Which is the number of posts on the topside i.e. 4. When its value is changed the whole model adjusts accordingly.</p><p>Shown below is the same model with the value of “NUMBER OF POSTS” (N) changed to 4 and 6. The length and the number of inner posts adjust accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*MiWCVOOV228ACWJqujTqIg.png" /><figcaption>The value of length (blue) and Inner posts(Red arrow) changes if we change the value of ’N’. They are all dependent on the value of ‘N’.</figcaption></figure><p>The tutorial for this Parametric Lego model in Solidworks can be found <a href="https://youtu.be/GdfhS5Md5wk">here</a>. It is also a simple and great example of ‘Configurations’ in the software.</p><p>A well made parametric model can be turned into tool in of itself. (<em>By well-made I mean being able to handle exceptions well. For example negative values have to give an error</em>). Below is an example of such a tool. It is the<a href="https://tinyurl.com/onshape-spurgear"> Spur Gear Tool</a> from Onshape. It creates a spur gear of the required size based only the dimensions of the required parameters you give it. You can also view the <a href="https://cad.onshape.com/FsDoc/">FeatureScript </a>code used in it. Featurescript is a coding language made by Onshape for building and working with 3D parametric models. All of its standard tools like “Extrude” are written in this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*4o1tsSJBbwFb_aEBONNZgg.png" /><figcaption>Instructions on how to use the Spur Gear tool in Onshape. It is a public tool and can be accessed by anyone with an Onshape account.</figcaption></figure><p>Below are two spur gears made from the above tool. It literally takes only a few seconds to create and modify them. But the limitation is that you can only modify as much as the tool allows you to. Extra modifications can be made manually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*YmcK03Eh8N-31c8ikfcxfQ.png" /><figcaption>Two different gears created within seconds using the Onshape Spur Gear tool</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/1*RNzZ7RW6kkck8oL3tTu5Rw.png" /><figcaption>Required parameters for a spur gear</figcaption></figure><p>The dialog box on the left show all the parameters that need to be defined to create a spur gear model. This also includes whether or not there needs to be a key way or even a center bore. The rest of the dimensions are adjusted based on relations to these parameters. While this tool is quite flexible if more modifications are required in the part we will have to do them manually.</p><p>Also, this tool can only create Spur gears. If,for example,you need to make a Bevel gear you will need another tool and if that is not available it can be a problem. Hence, for now knowing how to operate a CAD software helps. But slowly as new tools develop it will make our modeling lives easier.</p><h3><strong>Custom CAD Tools</strong></h3><p>All software have their own built in standard tools — the ones which were made by the developers with the intention that it will be generally applicable to as many types of common jobs as possible. The tools such as “Extrude” and “Extrude Cut” are as general as it gets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*K_LX3X05HCn9TQpYAitbpQ.png" /><figcaption>The extrude tool (named differently in other CAD) in SolidWorks which extrudes a 2D drawing into a 3D object. The most basic of CAD tools.</figcaption></figure><p>Custom CAD Tools, as opposed to the built in tools , are the ones that are suitable for a specific task for a company or a type of company. Its main aim is to be able to perform repetitive tasks (which are very specific) with very few manual inputs. These are usually created by the users themselves.</p><p>The tool shown below was made in <a href="https://www.onshape.com/">OnShape</a>. It was coded using <a href="https://cad.onshape.com/FsDoc/">Featurescript </a>code which is native to Onshape. This “<a href="https://tinyurl.com/wavespring">Wave Spring</a>” tool is available in its library for public use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*LLAz41likkwyTLv4xbYOrw.png" /><figcaption>2 variations created using an Onshape tool to create a Wave Spring. All you have to do is enter the dimensions shown in the top left box.</figcaption></figure><p>The above example is a Custom CAD Tool for a wave spring(Also an example of <em>Parametric Modeling</em> similar to the above ‘Spur Gear Tool’). This tool can create a wave spring ,just by entering dimensions in the top left box ,in less than a minute. Imagine you work in a company in which you have to deal with a lot of leaf springs in a assembly. If this had to modeled from scratch it would take an average CAD user around 30 minutes. If it is made by reusing models(changing dimensions) then still it could take around 7 minutes (for an average user) to make the spring. This is a significant amount of time compared to the custom tool’s <em>less-than-a-minute</em> time.</p><p>When this task is done repeatedly and by a number of workers the time saved by this tool reaches in the thousands of hours. This leaves more time for more “<em>human</em>” tasks like brainstorming, problem solving and design.</p><p>Below is another example of a custom CAD tool in Solidworks; made by <strong>Shashank Dewan</strong> from <a href="http://www.promechminds.com/"><strong>Pro-Mech minds</strong></a>, which properly arranges random dimensions in the drawing and also takes the datum(origin) at the center. This is a very specific requirement which might not be useful for all users but for the right user this saves a LOT of time while creating official 2D drawings. This tool was custom made using C# and the Solidworks API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ZDnWJ0QTHoiCejTQoXEgA.gif" /><figcaption>Auto-Dimension arranging tool with the center of the part as origin. Creator: Sashank Dewan</figcaption></figure><h3><strong>Application</strong></h3><p>While the above tools have obvious applications in the industry there is one in particular that I found useful to discuss. The parametric modeling tools are used to create standard part 3D model generators in a company’s website.</p><p>The image shown below is from the <a href="https://iai.partcommunity.com/">website of the company IAI</a>. The Panel on the right is where you input the parameters, on the right you can view the generated 3D model. All this happens in the browser, no CAD software required. The generated model can then be downloaded in the required formats. The shown image is of a <a href="https://iai.partcommunity.com/3d-cad-models">Cylinder (Robot Cylinder)</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oRshUH6Ig3F27EBhG3opoA.png" /><figcaption>A CAD model generator of the company “IAI” for a Cylinder (Robot Cylinder) with Slider Type &gt;RCP5 series &gt;Motor Reversing Type. Source : <a href="https://iai.partcommunity.com/3d-cad-models/">IAI Part Community</a></figcaption></figure><h3><strong>Advantages</strong></h3><p>A great advantage of the above tools is that it requires less skill to operate. Even a person with rudimentary CAD skills but sound engineering knowledge will be able to create that wave spring or a spur gear in a less than a minute. Hence, it really helps skilled engineers but beginner CAD users to create 3D models without having to learn the software in much detail.</p><p>The above tools also help to save time. Using the above shown “Dimension Organizer” tool saves a lot of time in arranging the dimensions to get a cleaner look. As the drawing gets more complex, this tool will save more time.</p><p>Taking the example of a spur gear tool. To create the spur gear an average CAD user will take around 45 minutes. Using a template it will take around 10 minutes. Using the tool it would take 1 minute. That time saved is staggering. As mentioned already, more time for human centered tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*LvbklvlZ9s25Tk1PfO9iFA.png" /></figure><p>The models made from a well-defined tool are also very accurate as it reduces the human element from the model. The chances of the dimensions being mistaken using the “Spur Gear Tool” are very low and thus this also improves the efficiency of the work.</p><h3><strong>Conclusion</strong></h3><p>In conclusion CAD has the ability to be automated by the use of parametric models and custom tools. The first one can be done directly in the CAD software while the to create the custom tool a certain level of programming skill is required along with CAD skills. These two combined help to create a less mundane and efficient work environment for users of CAD. Parametric modeling can also be used in company websites to display their products in various dimensions. Hence, this is an aspect of computer aided design the current generation of engineering students should definitely explore.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c491d71181b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI, Social Media and Meditation]]></title>
            <link>https://ai.plainenglish.io/ai-social-media-and-meditation-ea55f7aa3aaa?source=rss-36012891cc8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea55f7aa3aaa</guid>
            <category><![CDATA[self-awareness]]></category>
            <category><![CDATA[meditation]]></category>
            <category><![CDATA[social-media]]></category>
            <category><![CDATA[vipassana]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Sunny K. Tuladhar]]></dc:creator>
            <pubDate>Thu, 30 Jul 2020 06:42:21 GMT</pubDate>
            <atom:updated>2020-08-03T03:56:15.770Z</atom:updated>
            <content:encoded><![CDATA[<h3>Artificial Intelligence, Social Media and Meditation</h3><h4>If you’ve wondered how social media is able to show you such catered precise ads, then here are a few answers. This article is about how AI and social media appear to know you better than yourself and how meditation might help.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3zjhMA4TwLvb8ozZ.jpg" /><figcaption>Source: <a href="https://www.hackerearth.com/blog/developers/20-machine-learning-artificial-intelligence-influencers-to-follow-in-2020/">hackerearth</a></figcaption></figure><p>Artificial Intelligence has been quite the buzzword recently. “Artificial intelligence (AI), is broadly defined as the ability of a digital <a href="https://www.britannica.com/technology/computer">computer</a> or computer-controlled <a href="https://www.britannica.com/technology/robot-technology">robot</a> to perform tasks commonly associated with intelligent beings.” By intelligent beings it basically means humans … but maybe not all humans.</p><p>AI has many levels, from a simple line following robot to language translation. The level we are talking about is the Facebook’s targeted ads and Netflix’s recommendation systems. Right now we are concerned with the one the social media companies are using, broadly called the Recommendation System. Basically it takes your data (age, sex, address, interests etc.) and recommends you stuff like ads and posts(videos, statuses), etc. that you are most likely to react to or buy using AI.</p><p>Well how bad could a recommendation system be? After all, all it does is recommend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i4F76Hwq16lYIQMc.png" /><figcaption>Recommendation System example. Source: <a href="https://medium.com/@tomar.ankur287/user-user-collaborative-filtering-recommender-system-51f568489727">Medium article</a></figcaption></figure><p>Lets first break down the levels of AI and get to what we are talking about. If you loop deep enough , AI is just math. Statistics to be exact. But it is so complicated and the black box is so huge that it is considered a “mind of its own”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/0*JWrJQkI0T-byvqHl" /><figcaption>Source: <a href="https://xkcd.com/1838/">xkcd</a></figcaption></figure><p>First lets take an example of the AI which can predict whether an image is a cat or a dog. What the AI does is look at a huge number of cat and dog images and “learns” what a cat or a dog is. After that when you show it a picture it has never seen, it will predict whether the image is a cat or a dog. Here’s a <a href="https://machinelearningmastery.com/how-to-develop-a-convolutional-neural-network-to-classify-photos-of-dogs-and-cats/">link </a>to the code. This code gives results that are 97% accurate .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*MTGAG13K6ceM5z5IxDpP1Q.gif" /><figcaption>Source: <a href="https://becominghuman.ai/building-an-image-classifier-using-deep-learning-in-python-totally-from-a-beginners-perspective-be8dbaf22dd8">Article in becominghuman.ai </a>by <a href="https://becominghuman.ai/@venkateshtata9?source=post_page-----be8dbaf22dd8----------------------">Venkatesh Tata</a></figcaption></figure><p>The AI is able to do this because of all the data it has. In case of an image, each pixel is a data feature and the pattern in which these pixels are laid tell us what image it is.</p><p>Now we will look at a different type of data, our personal data, the ones with our age, our education, out interests, our location, etc which are all so readily available on Facebook. Shown below is a fictional neural network that takes in the personal data as input and predicts whether the person is interested in football or not. Once the social media AI figures this out it, can choose to show you football related stuff or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*XtHNu7e2KyCiWc_9txt39g.png" /><figcaption>A neural network predicting whether a person is interested in football or not. (Original Image: <a href="https://developer.oracle.com/databases/neural-network-machine-learning.html">developer.oracle.com</a>)</figcaption></figure><p>This is a small and simple example. When the AI is able to analyze hundreds of thousands of these data points(inputs/features) it is able to paint an accurate picture of the person. This is called psychographics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/0*3V5DPitRJYLqpgQ3.png" /><figcaption>Demographic vs Pyschographics. Source : <a href="https://blog.hurree.co/blog/psychographic-segmentation">Hurree</a></figcaption></figure><p>Psychographics is the study of <a href="https://visionone.co.uk/psychographic-profiling/">psychological attributes</a> like personality, values, attitudes, opinions, interests, and lifestyles. [1] It focuses less on standard things like gender, location age, income and more on psychological attributes and personality traits i.e. more on what kind of person he/she is.</p><p>Social media platforms use all this to send you targeted ads, posts and recommendations on your feed. Most people believe that all the posts on your Facebook feed are generated predetermined and don’t change as you scroll down. But the posts you see as you scroll down change depending on what you ‘liked’ or didn’t ‘like’ previously , in a way that gets you hooked to the feed. The AI is only concerned with making you use the app for longer, not your well being or even entertainment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_MffZTvqMs5TCeQs.jpg" /><figcaption>Source: <a href="http://enterprisetalk.ondot.media/featured/ai-framework-that-can-explain-social-media-feeds/">enterprisetalk.ondot.media</a></figcaption></figure><h3>Social media and Traditional Media</h3><p>By social media we mean Facebook, Twitter, etc. and by traditional media we mean TV, radio, newspapers, etc. The key difference being the information source and interactivity between the source of media and the audience. Since news is a common ground for both sources lets discuss about how it gets distributed in these two platforms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/0*vTYiNbhWvPWuvaHS.jpg" /><figcaption>(Left) Traditional Media vs. (Right) Social Media. Source: <a href="https://adlgmarketing.com/blog/5-reasons-why-social-media-advertising-is-better-than-traditional-advertising/">adlgmarketing.com</a></figcaption></figure><p>The news on the traditional media is (supposed to be) well researched by the journalists and is shown to a mass through devices such as TV, radio, newspapers. The audience who receive the information(news) cannot comment on the news. The voice of the listeners is not heard. The information flows one way; from the TV to the audience.</p><p>The news on social media platforms is quite different. It is usually shared through websites that are outside the social media platform itself (E.g. <a href="https://www.bbc.com/news">bbc.com</a>) but sometimes it could be a page within the platform (E.g <a href="https://www.facebook.com/officialroutineofnepalbanda">RONB</a>… yes, not kidding). But basically anyone can post anything on it. Extreme posts like nudity and violence are detected and removed BUT misleading lies disguised as news are very hard to detect. They slip through and can spread extremely quickly. This combined with targeted ads of these posts to people who are vulnerable to it can lead to trouble. People can also comment on the news, which can be the source of strange online disputes while oddly and rarely this also helps in verification.</p><h3>Social Media and “the Mind Hijack”</h3><p>So what is happening now is basically people’s data from social media is being used by other companies. Then these companies use this data to send out targeted ads to the user. These ads could be a harmless product ad or in some cases a malicious manipulative ad designed specifically to change your political views. This particular example is from the Hillary Clinton and Donald Trump campaign where posts like this were targeted to many US citizens so that they would change their minds about Hillary and vote for Trump. The imagery is such that it immediately and instinctively antagonizes Hillary regardless of what you have learned of her before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*F4u1PPnhOjUPscysY9x8pg.png" /><figcaption>Source : Facebook - <a href="https://www.facebook.com/Defeat-Crooked-Hillary-1739342232972780/">Defeat Crooker Hillary</a></figcaption></figure><p>There are many ways the social media platforms uses to “control” our minds. These article in <a href="https://listverse.com/2018/05/23/10-creepy-things-social-media-does-to-control-your-mind/">listverse.com</a> gives 10 good examples. There are two we are particularly concerned with within this article.</p><h4>Exploits Negative Emotions:</h4><p>“People are more likely to use social media when they’re experiencing a negative <a href="https://listverse.com/2013/07/23/10-odd-scientific-facts-about-emotions/">emotion</a>, such as boredom or vulnerability, because engaging with social media provides a distraction from these feelings. Researchers have found that depressed people check their emails more often as they need the small dopamine hit that is generated by receiving an email.</p><p>Social media companies want to make people use social media habitually when they’re experiencing negative emotions. They may do this by manipulating feedback so that people receive “likes” on posts when they may be feeling sad.</p><p>For example, Instagram may retain likes for an <a href="https://listverse.com/2017/11/24/top-10-intriguing-images-from-ancient-art/">image</a>, increasing feelings of vulnerability, and then release the likes in a sudden rush. An algorithm is continuously measuring which rates of information released under different circumstances will make people return to the platform the most.</p><p>This tactic is especially problematic as studies have repeatedly found that the heavy use of social media sites can worsen people’s emotional well-being” [2]</p><h4>Uses Psychography To Target You</h4><p>“Psychographics describes the method of examining an individual’s personality. Research has found that <a href="https://listverse.com/2017/11/25/10-times-computers-went-rogue/">computers</a> can predict someone’s personality better than that individual’s family or friends simply by analyzing 300 of the person’s Facebook ‘likes’. For example, the study found a high correlation between liking <em>Jersey Shore</em> star Snooki and extroversion.</p><p>Other studies have found high correlations between intelligence and liking ‘<a href="https://listverse.com/2017/11/11/top-10-striking-historical-facts-about-lightning/">thunderstorms</a>’ and ‘curly fries.’ Also, people who like Hello Kitty are generally high on openness and low on emotional stability.”[2]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/0*Gy1JSPyOS9PMUXUn.jpg" /><figcaption>Cambridge Analytica and Facebook. Source: <a href="https://www.motherjones.com/politics/2018/05/emerdata-cambridge-analytica-shutting-down-facebook-trump/">motherjones,com</a></figcaption></figure><h3>“Google knows you better than you know yourself”</h3><p>This part goes beyond social media and into most Internet of Things (IoT). There is this growing notion that Google knows you better than you know yourself.</p><p>“Search engines, online platforms, and mobile applications collect a tremendous amount of data about their users. Not only do these platforms collect information about the devices and applications you use, but also a lot of (real-time) personal information about you (e.g. voice and visual data, biometrics, personal characteristics) and the data stored on your mobile phone (e.g. phone numbers, call history, private messages, social media likes).” [3]</p><p>“They also monitor your behavior online, carefully tracking the time you spend on sites, the locations you have visited, the reviews you leave behind, and even the payments you make. The data it has about a single person is huge. The online collection of demographic data (e.g. gender, age, income, nationality) and behavioral data (e.g. online purchasing behavior, clicks, likes), together with psychographic profiling, provide these platforms with highly detailed insights about their users and razor-sharp abilities to accurately predict (predictive analytics) and influence behavior online (targeted actions). Digital platforms now not only know <em>‘who’</em> you are and <em>‘what’ </em>you do, but with psychographics can also explain <em>‘why’</em> you do it.” [3]</p><h3>Why is all this a problem?</h3><p>Based on the tone of the previous paragraph you might have gotten an ominous vibe but still the question remains “So what? It does not bother me if they take my data and recommend me stuff.” Here’s another excerpt from the <a href="https://listverse.com/2018/05/23/10-creepy-things-social-media-does-to-control-your-mind/">listverse.com</a></p><p>“Like Hannibal Lecter, the company Cambridge Analytica believed that you must understand what makes people tick to manipulate them effectively. Through alleged negligence, Facebook effectively allowed Cambridge Analytica to use psychographics to target people with political ads adapted to their personalities.</p><p>The actual effect of Cambridge Analytica’s targeted campaigning is in dispute, but the company believed that their method was adept at influencing minds. In fact, they claimed responsibility for the surprising outcomes of BREXIT and the 2016 US presidential election.”[2]</p><p>Thus it is believed that the company Cambridge Analytica had a hand in getting Trump elected. It targeted ads to people on the fence about the election (those who were most likely to change their minds about their candidate). The ads were designed to defame and ruin the image of Hillary Clinton in the minds of the voters. Images like the one shown above (“Defeat Crooked Hillary”) were created that were aimed to taint her image. [4]</p><p>So AI recommendation systems allegedly can swing elections. They seem to have a role in the US Elections AND the BREXIT vote. These are literally world changing events and the social media AI (Facebook in this case) had a role to play in that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*Wkf8hjw1WmMLF4RFRB2YUQ.png" /><figcaption>Meme taken from<a href="https://www.instagram.com/linuxtechtips/"> Linux Tech Tips</a></figcaption></figure><p>Social media platforms have a lot of data about its users which they just give away to their sponsors and advertisers because… money. These advertisers are then able to use this data to target specific people for specific ads and posts which can influence the people’s behavior in a way that benefits them. This seems to be possible because of current technology the AI can know the human mind better than the human himself.</p><p>“When infotech merges with biotech what you get is the ability to create algorithms that understand me better than I understand myself.” — Yuval Noah Harrari, Impact Theory Interview, 2018</p><p>So what can be done?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*15T601pVHQoUg1mN.jpg" /><figcaption>Source:<a href="http://blog.meraevents.com/2015/01/12/brain-hack-psychology-workshop/"> blog.meraevents.com</a></figcaption></figure><h3>Solution: Know thyself?</h3><p>While limiting social media use is obviously an option but google’s data goes beyond that. There have been claims that the mobile phone are listening to our conversations and showing us ads based on that. Here are related articles on <a href="https://www.foxnews.com/tech/youre-not-paranoid-your-phone-really-is-listening-in">Fox News</a> and <a href="https://www.vice.com/en_au/article/wjbzzy/your-phone-is-listening-and-its-not-paranoia">Vice</a>. As mobile phones and Wi-Fi have become a necessity it has become increasingly difficult to disconnect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I6hkmUgAdhaRqUTc.jpg" /><figcaption>Source: <a href="https://www.yesilscience.com/know-thyself-2/">yesilscience.com</a></figcaption></figure><p>So one idea seems to be to “Know thyself” which I became aware of from Yuval Noah Harrari. It means to know yourself, to reallllly know yourself would mean to have control over your desires and emotions. Many ancient philosophies want us to know ourselves but we often discard them as cliches. (Harrari explains it in this <a href="https://www.youtube.com/watch?v=AgiA53dhF_0">video</a>)</p><p>Now is a more important time than any to know yourself. Previously it was impossible for any one other than yourself to know you the best. But now the algorithms can know us better than we know ourselves. They can tell what decisions we might make and why. And then it can manipulate our thoughts and decisions[5]</p><h3>Meditation</h3><p>If a person were to know himself better than the AI systems then the person will have more control over his life and his emotions. Thus, these systems will not be able to influence his behaviour as much. One of the ways to do this seems to be meditation. As Yuval Noah Harrari points out, specifically Vipassana meditation. [6]</p><p>I also went for the 10 days meditation retreat in Vipassana here in Budhanilkantha, Kathmandu, Nepal. What it teaches does indeed seem to be helpful in this age of privacy-invading technology. The meditation teaches us to be in touch with reality. This meditation(Vipassana) is more than just an exercise for the mind, there are things we learn from it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rIXyUrsVIM3DRimC.jpg" /><figcaption>Dhammashringa Vipassana Meditation center at Budhanilkantha. Source: <a href="https://shringa.dhamma.org/en/">shringa.dhamma.org</a></figcaption></figure><p>The practice of Vipassana begins with <a href="https://www.youtube.com/watch?v=Oh5ii6R6LTM">Anapana</a>, which is basically observing the flow of breath. Breathing is among the core activities which keeps us alive and which reflects our state of being. Thus, observing this helps us keep in touch with the now, the present. This is harder than it seems as our mind wants to keep wandering in the past and the future. We can train our mind this way by teaching it to focus on the things we want it to focus on and not just wander off every now and then.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*1tiaq_1nj9a0-qMT.jpg" /><figcaption>Anapana meditation. Source: <a href="https://childrenmeditation.wordpress.com/anapana-meditation/what-is-anapana/">childrenmeditation.wordpress.com</a></figcaption></figure><p>When we practice this, as we keep trying to concentrate our mind on our breathe, it keeps getting distracted with its own things. Once we are able to train our mind we can focus intently on our breath for longer while meditating and consequently on any task we perform while not meditating, for longer.</p><p>A social media analogy would be when we are working we try to focus on the work at hand but our mind wants to check on Facebook. If our mind is trained we can at least be more purposeful with our social media interactions rather than mindlessly scrolling through content.</p><p>After Anapana is taught for 4 days, Vipassana is taught, which includes observing the entire body instead of just the breath. This really grounds us to the truth and keeps us in the present. It teaches us to be aware of our bodily sensations and how our mind and body are extremely interlinked with each other. It teaches us how our feelings are actually a product of bodily chemical processes rather than the outside world and this process can be observed and controlled.</p><p>For example when someones says something mean to you, the words enter your brain and then you get angry.. or at least that&#39;s what we think. But actually between the sound entering the brain and you reacting, there is a gap. What causes the anger is not the words themselves but chemicals released in the body after the words have been heard. Once we realize this and learn to observe this we get a better understanding of our emotions and thus learn how to control them better. Vipassana helps us do this and consequently help us be more purposeful with our actions rather than just reacting to what the outside world throws at us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*aIuBk2t8XZ9W2Ak7" /><figcaption>Emotions and their linked Hormone levels. Source: <a href="https://www.quora.com/Is-it-good-to-be-driven-by-your-emotions">Quora</a></figcaption></figure><p>A social media analogy would be the targeted ads that try to sell us stuff as they try to prey on our feelings and emotions. But once we know ourselves better we will not fall for it. We will be able to have a clearer presence of mind enough to know, to understand that what is being shown (ads, posts etc.) cannot influence us or our well being.</p><h3>Conclusion</h3><p>AI and algorithms with all the data they receive from social media and IoTs can hack humans. They can then target us in specific ways, show us targeted ads and influence our behaviour and decisions. So to counter this we should learn to know ourselves better than the algorithms and one way to do that seems to be meditation and more specifically Vipassana meditation.</p><p>References</p><p>[1] <a href="https://blog.hurree.co/blog/author/stevie-langford">S. Langford</a><a href="https://blog.hurree.co/blog/psychographic-segmentation">, How Psychographic Segmentation Can Improve your Marketing Strategy(</a>2019), Hurree</p><p>[1]<a href="https://towardsdatascience.com/@conrmcdonald">C. McDonald</a>, <a href="https://towardsdatascience.com/machine-learning-fundamentals-via-linear-regression-41a5d11f5220">Machine learning fundamentals (I): Cost functions and gradient descent(2017)</a>, Towards data science</p><p>[2]<a href="https://listverse.com/lvauthor/M.%20Poste">M. Poste</a>, <a href="https://listverse.com/2018/05/23/10-creepy-things-social-media-does-to-control-your-mind/">10 Creepy Things Social Media Does To Control Your Mind(</a>2018), Listverse</p><p>[3] <a href="https://www.hult.edu/blog/author/ali-fenwick/">A. Fenwick</a><a href="https://www.hult.edu/blog/psychographics-big-data-watching/">, </a><a href="https://www.hult.edu/blog/psychographics-big-data-watching/">Psychographics: How big data is watching you</a> (2018), HULT</p><p>[4]<a href="https://en.wikipedia.org/wiki/Jehane_Noujaim">J. Noujaim</a> <a href="https://en.wikipedia.org/wiki/Karim_Amer">,K. Amer</a>, The Great hack(2019), Documentary , Netflix</p><p><a href="https://www.youtube.com/watch?v=vC4FtajN_QY">[5] </a><a href="https://www.youtube.com/watch?v=vC4FtajN_QY">Yuval Noah Harari: “An algorithm that knows you better than you know yourself”,</a> <a href="https://www.youtube.com/channel/UCk0IuGzj0BUB-waVMpEm6ig">Carnegie Council for Ethics in International Affairs,</a> Youtube</p><p>[6]<a href="https://www.ynharari.com/about/">Yuval Noah harrari</a>, <a href="https://www.ynharari.com/book/21-lessons-book/">21 lessons for the 21st century(</a>2018)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea55f7aa3aaa" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/ai-social-media-and-meditation-ea55f7aa3aaa">AI, Social Media and Meditation</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Artificial Intelligence in  Mechanical Engineering]]></title>
            <link>https://medium.com/data-science/artificial-intelligence-in-mechanical-engineering-a9dd94adc492?source=rss-36012891cc8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9dd94adc492</guid>
            <category><![CDATA[mechanical-engineering]]></category>
            <category><![CDATA[mechanical-parts]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[classification]]></category>
            <dc:creator><![CDATA[Sunny K. Tuladhar]]></dc:creator>
            <pubDate>Mon, 06 Jul 2020 05:59:09 GMT</pubDate>
            <atom:updated>2020-07-13T03:07:42.929Z</atom:updated>
            <content:encoded><![CDATA[<h3>Artificial Intelligence in Mechanical Engineering</h3><h4>An example of Deep Learning implementations with very basic explanations for mechanical engineers who are beginners or enthusiasts in the field of data science and artificial intelligence. This project was conducted at <a href="http://www.promechminds.com/">Pro-mech Minds</a>, Nepal.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/0*G4WycT0SlVS3UBto" /><figcaption>Image by <a href="https://www.123rf.com/profile_andreysuslov">Andrey Suslov</a> from <a href="https://www.123rf.com/photo_110161039_stock-vector-concept-industry-4-0-artificial-intelligence-automation-of-product-manufacturing-on-smart-factory-ai.html">123rf.com</a></figcaption></figure><p>Artificial Intelligence and Machine Learning seems to be the current buzzword as everyone seems to be getting into this subject. Artificial Intelligence seems to have a role in all fields of science. According to Britannica<strong> , “Artificial intelligence (AI)</strong>, is broadly defined as the ability of a digital <a href="https://www.britannica.com/technology/computer">computer</a> or computer-controlled <a href="https://www.britannica.com/technology/robot-technology">robot</a> to perform tasks commonly associated with intelligent beings.” By intelligent beings it basically means humans … but maybe not all humans…so anyway,<br>It is usually classified into three subsets as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4d3bL-uKfyVZWBj6.png" /><figcaption>Artificial Intelligence and its subsets ( <a href="https://medium.com/www.edureka.co">Source: Edureka</a>)</figcaption></figure><p>Artificial Intelligence is a broader term which in cooperates Machine Learning. Machine learning uses statistical methods to allow machines to improve with experience.</p><p>Deep Learning, again, is the subset of Machine Learning which uses multi layer neural networks that mimic the human brain and can learn incredibly difficult tasks with enough data.</p><p>We are going to talk about Deep learning methods and its possible role in the field of Mechanical Engineering. Some common examples could be <em>Anomaly Detection(Machine Learning)</em> and<em> Image based Part Classification(Deep Learning)</em>. The focus will be on Image based part classifiers and why we need them.</p><p>Firstly, what is an image classifier? The ever famous AI which recognizes cat-dog pictures should come to mind. Here’s a <a href="https://machinelearningmastery.com/how-to-develop-a-convolutional-neural-network-to-classify-photos-of-dogs-and-cats/">link </a>to the code of such a program. The data-set used contains images of cats and dogs, the algorithm learns from it and then is able to guess with 97% accuracy whether a randomly shown image is a cat or a dog.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KJep_7TYQfatTDXP.jpeg" /><figcaption>Cat or Dog? (Source: <a href="https://medium.com/anubhav-shrimal/dogs-vs-cats-image-classification-using-resnet-d2ed7e6db2bb">medium article</a>)</figcaption></figure><p>We will attempt a similar code but using Nuts, Bolts, Washers and Locating Pins as our Cats and Dogs….. because mechanical engineering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*GnPh4FNzx-fVuuJivH_8Eg.png" /><figcaption>Bolt or Nut or Locating Pin or Washer? Will the AI be able to tell?</figcaption></figure><p>So how does it work? An algorithm is able to classify images(efficiently) by using a Machine Learning algorithm called Convolutional Neural Networks(CNN) a method used in Deep Learning. We will be using a simple version of this model called Sequential to let our model distinguish the images into four classes Nuts, Bolts, Washers and Locating Pins. The model will learn by “observing” a set of training images. After learning we will see how accurately it can predict what an image (which it has not seen) is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*KzxwzcMuXdR_GSn32cY98A.png" /><figcaption>A flowchart of a Machine Learning algorithm trained on Images of Nuts and Bolts using a Neural Network Model. (Original Image: <a href="https://www.pngfind.com/mpng/hooRJmb_7wdata-machine-learning-training-algorithm-hd-png-download/">pngfind</a>)</figcaption></figure><p><a href="https://github.com/Promech2020/Mech-parts-classification-seq-model">Go directly to the code in github</a></p><h3>Data-set</h3><p>We downloaded 238 parts each of the 4 classes (Total 238 x 4 = 952) from various part libraries available on the internet. Then we took 8 different isometric images of each part. This was done to augment the data available, as only 238 images for each part would not be enough to train a good neural network. A single class now has 1904 images(8 isometric images of 238 parts) a total of 7616 images. Each image is of 224 x 224 pixels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*prPQqWhgBTbeuCQ8halx4w.png" /><figcaption>Images of the 4 classes. 1 part has 8 images. Each image is treated as single data.</figcaption></figure><p>We then have our labels with numbers 0,1,2,3 each number corresponds to a particular image and means it belongs to certain class</p><pre>#Integers and their corresponding classes<br>{0: &#39;locatingpin&#39;, 1: &#39;washer&#39;, 2: &#39;bolt&#39;, 3: &#39;nut&#39;}</pre><p>After training on the above images we will then see how well our model predicts a random image it has not seen.</p><h3><strong>Methodology</strong></h3><p>The process took place in 7 steps. We will get to the details later. The brief summary is</p><ol><li><strong>Data Collection</strong> : The data for each class was collected from various standard part libraries on the internet.</li><li><strong>Data Preparation : </strong>8 Isometric view screenshots were taken from each image and reduced to 224 x 224 pixels.</li><li><strong>Model Selection : </strong>A Sequential CNN model was selected as it was simple and good for image classification</li><li><strong>Train the Model: </strong>The model was trained on our data of 7616 images with 80/20 train-test split</li><li><strong>Evaluate the Model: </strong>The results of the model were evaluated. How well it predicted the classes?</li><li><strong>Hyperparameter Tuning: </strong>This process is done to tune the hyperparameters to get better results . We have already tuned our model in this case</li><li><strong>Make Predictions: </strong>Check how well it predicts the real world data</li></ol><h4><strong>Data Collection</strong></h4><p>We downloaded the part data of various nuts and bolts from the different part libraries on the internet. These websites have numerous 3D models for standard parts from various makers in different file formats. Since we will be using FreeCAD API to extract the images we downloaded the files in neutral format (STEP).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/1*SeSzPBUQYjxQ2X-dajPrKA.png" /><figcaption>Flowchart of the CAD model download</figcaption></figure><p>As already mentioned earlier, 238 parts from each of the 4 class was downloaded, that was a total of 952 parts.</p><h4>Data Preparation</h4><p>Then we ran a program using FreeCAD API that automatically took 8 isometric screenshots of 224 x 224 pixels of each part. FreeCAD is a free and open-source general-purpose parametric 3D computer-aided design modeler which is written in Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*Nvp7kNsGQ1Pxs0X4b2kM9g.png" /><figcaption>A flowchart of how the data was created</figcaption></figure><p>As already mentioned above, each data creates 8 images of 224 x 224 pixels. So we now have a total of 1904 image from each of the 4 classes, thus a total of 7616 images. Each image is treated as a separate data even though 8 images come from the same part.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NQtkn0BpMBg5poZlWprpKQ.png" /><figcaption>8 isometric images of a 2 bolts. Each row represents a different part.</figcaption></figure><p>The images were kept in separated folders according to their class. i.e. we have four folders Nut,Bolt, Washer and Locating Pin.</p><p>Next, each of these images were converted into an array with their pixel values in grayscale. The value of the pixels range from 0 (black), 255 (white). So its actually 255 shades of gray.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*pGc9_twykMNhs09gTNlmWg.png" /><figcaption>Example of an Image converted to an array of pixel values. (Source: <a href="https://openframeworks.cc/ofBook/chapters/image_processing_computer_vision.html">openframeworks.cc</a>)</figcaption></figure><p>Now each of our image becomes a 224 x 224 array. So our entire dataset is a 3D array of 7616 x 224 x 224 dimensions.<br>7616 (<em>No. of images</em>) x 224 x 224 (<em>pixel value of each image</em>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*D3veCb5vTNCwzqkNgqqsNQ.png" /><figcaption>Visualization of our pixel array using matplot.lib</figcaption></figure><p>Similarly we create a the label dataset by giving the value of the following integers for the shown classes to corresponding indexes in the dataset. If our 5th(<em>index</em>) data in the dataset(X) is a locating pin , the 5th data in label set (Y) will have value 0.</p><pre>#integers and the corresponding classes as already mentioned above<br>{0: &#39;locatingpin&#39;, 1: &#39;washer&#39;, 2: &#39;bolt&#39;, 3: &#39;nut&#39;}</pre><h4>Model Selection</h4><p>Since this is an image recognition problem we will be using a Convolutional Neural Network (CNN). CNN is a type of Neural Network that handles image data especially well. A Neural Network is a type of Machine learning algorithm that learns in a similar manner to a human brain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/0*FPSAu-f6Tsod6ptT.jpeg" /><figcaption>A basic neural network. (Source: <a href="https://towardsdatascience.com/machine-learning-fundamentals-ii-neural-networks-f1e7b2cb3eef">Medium article</a> by <a href="https://towardsdatascience.com/@conrmcdonald">Conor McDonald</a>)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*MrA7Nml9Yac-IcTAuKcdCw.png" /><figcaption>A Convolutional Neural network. A basic visualization of how our algorithm will work (Original image source : <a href="https://adeshpande3.github.io/A-Beginner%27s-Guide-To-Understanding-Convolutional-Neural-Networks/">Article </a>by <a href="https://adeshpande3.github.io/adeshpande3.github.io/">Adit Deshpande</a>)</figcaption></figure><p>The following code is how our CNN looks like. Don’t worry about it if you don’t understand. The idea is the 224 x 224 features from each of our data will go through these network and spit out an answer. The model will adjusts its weights accordingly and after many iterations will be able to predict a random image’s class.</p><pre>#Model description<br>Model: &quot;sequential_1&quot;<br>_________________________________________________________________<br>Layer (type)                 Output Shape              Param #   <br>=================================================================<br>conv2d_1 (Conv2D)            (None, 222, 222, 128)     1280      <br>_________________________________________________________________<br>activation_1 (Activation)    (None, 222, 222, 128)     0         <br>_________________________________________________________________<br>max_pooling2d_1 (MaxPooling2 (None, 111, 111, 128)     0         <br>_________________________________________________________________<br>conv2d_2 (Conv2D)            (None, 109, 109, 128)     147584    <br>_________________________________________________________________<br>activation_2 (Activation)    (None, 109, 109, 128)     0         <br>_________________________________________________________________<br>max_pooling2d_2 (MaxPooling2 (None, 54, 54, 128)       0         <br>_________________________________________________________________<br>flatten_1 (Flatten)          (None, 373248)            0         <br>_________________________________________________________________<br>dense_1 (Dense)              (None, 64)                23887936  <br>_________________________________________________________________<br>dense_2 (Dense)              (None, 4)                 260       <br>_________________________________________________________________<br>activation_3 (Activation)    (None, 4)                 0         <br>=================================================================<br>Total params: 24,037,060<br>Trainable params: 24,037,060<br>Non-trainable params: 0</pre><p><a href="https://www.youtube.com/watch?v=PmlRbfSavbI">Here </a>is a YouTube video of Mark Rober (a NASA mechanical engineer) explaining how neural networks work with very little coding involved.</p><h4>Model Training</h4><p>Now finally the time has come to train the model using our dataset of 7616 images. So our [X] is a 3D array of 7616 x 224 x224 and [y] label set is a 7616 x 1 array. For all training purposes a data must be split into at least two parts: Training and Validation (Test) set (test and validation are used interchangeably when only 2 sets are involved).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/0*ASmO0vQKrdSd5BJC.png" /><figcaption>Data being split into training and test set. (Source: <a href="https://www.researchgate.net/figure/Train-Test-Data-Split_fig6_325870973">researchgate.net</a>)</figcaption></figure><p>The training set is the data the model sees and trains on. It is the data from which it adjusts its weights and learn. The accuracy of our model on this set is the training accuracy. It is generally higher than the validation accuracy.</p><p>The validation data usually comes from the same distribution as the training set and is the data the model has not seen. After the model has trained from the training set, it will try to predict the data of the validation set. How accurately it predicts this, is our validation accuracy. This is more important than the training accuracy. It shows how well the model generalizes.</p><p>In real life application it is common to split it even into three parts. Train, Validation and Test.</p><p>For our case we will only split it into a training and test set. It will be a 80–20 split. 80 % of the images will be used for training and 20% will be used for testing. That is train on 6092 samples, test on 1524 samples from the total 7616.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*MmhfAw5Fke6O1styNoMg_w.png" /><figcaption>Visualization of the model training. (Original Image Source : <a href="https://towardsdatascience.com/the-7-steps-of-machine-learning-2877d7e5548e">Medium article</a> by <a href="https://towardsdatascience.com/@yufengg">Yufeng G</a>)</figcaption></figure><p>For our model we trained for 15 epochs with a batch-size of 64.</p><p>The number of epochs is a hyperparameter that defines the number times that the learning algorithm will work through the entire training dataset.</p><p>One epoch means that each sample in the training dataset has had an opportunity to update the internal model parameters. An epoch is comprised of one or more batches.</p><p>You can think of a for-loop over the number of epochs where each loop proceeds over the training dataset. Within this for-loop is another nested for-loop that iterates over each batch of samples, where one batch has the specified “batch size” number of samples. [2]</p><p>That is our model will go through our entire 7616 samples 15 times (epoch) in total and adjust its weights each time so the prediction is more accurate each time. In each epoch, it will go through the 7616 samples, 64 samples (batch size) at a time.</p><h4>Evaluate the model</h4><p>The model keeps updating its weight so as to minimize the cost(loss), thus giving us the best accuracy. Cost is a measure of inaccuracy of the model in predicting the class of the image. Cost functions are used to estimate how badly models are performing. Put simply, a cost function is a measure of how wrong the model is in terms of its ability to estimate the relationship between X and y. [1]</p><p>If the algorithm predicts incorrectly the cost increases, if it predicts correct the cost decreases.</p><p>After training for 15 epochs we can see the following graph of loss and accuracy. (Cost and loss can be used interchangeably for our case)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*SIeP7ZJlWr2vBl2n3NBVbQ.png" /><figcaption>Graph generated from matplot.lib showing Training and Validation loss for our model</figcaption></figure><p>The loss decreased as the model trained more times. It becomes better at classifying the images with each epoch. The model is not able to improve the performance much on the validation set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*ejz6tyazlrGQNVARMmXD_w.png" /><figcaption>Graph generated from matplot.lib showing Training and Validation accuracy for our model</figcaption></figure><p>The accuracy increased as the model trains for each epoch. It becomes better at classifying the images. The accuracy is for the validation set is lower than the training set as it has not trained on it directly. The final value is 97.64% which is not bad.</p><h4>Hyperparameter Tuning</h4><p>The next step would to be change the hyperparameters, the learning rate,number of epochs, data size etc. to improve our model. In <a href="https://en.wikipedia.org/wiki/Machine_learning">machine learning</a>, a <strong>hyperparameter</strong> is a <a href="https://en.wikipedia.org/wiki/Parameter">parameter</a> whose value is used to control the learning process. By contrast, the values of other parameters (typically node weights) are derived via training.[3]</p><p>For our purpose we have already modified these parameters before this article was written, in a way to obtain an optimum performance for display on this article. We increased the dataset size and number of epochs to improve the accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*esuF16aAjZ-S2SLIV9xmow.png" /><figcaption>Hyperparameters affect parameters and eventually the final score (accuracy). ( Source: <a href="https://deepai.org/machine-learning-glossary-and-terms/hyperparameter">deepai.org</a>)</figcaption></figure><h4>Make Predictions</h4><p>The final step after making the adjustments on the model is to make predictions using actual data that will be used on this model. If the model does not perform well on this further hyperparameter tuning can commence.</p><p>Machine Learning is a rather iterative and empirical process and thus the tuning of hyperparameters is often compared to an art rather than science as although we have an idea of what changes will happen by changing certain hyperparameters, we cannot be certain of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*XOgXnRYRxVexdCZDE_dndA.png" /><figcaption>The machine learning algorithm flowchart(Original Image: <a href="https://www.pngfind.com/mpng/hooRJmb_7wdata-machine-learning-training-algorithm-hd-png-download/">pngfind</a>)</figcaption></figure><h3>Applications</h3><p>This ability to classify mechanical parts could enable us to recommend parts from a standard library based only on an image or a CAD model provided by the customer. Currently to search for a required part from a standard library you have to go through a catalogue and be able to tell which part you want based on the available options and your knowledge of the catalogue. There are serial codes to remember as a change in a single digit or alphabet might mean a different type of part.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/0*0nVBJFjj5afrQK1F.png" /><figcaption>Example of a part number from the website of <a href="https://www.torexsemi.com/products/part-numbers/">TOREX</a>.</figcaption></figure><p>If an image can be used to get the required part from the standard library, all we will need to do is to make a rough CAD model of it and send it through our algorithm. The algorithm will decide which parts are best and help narrow down our search significantly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*9QAYabOwtxnPbHI7gxrEAw.png" /><figcaption>Visualisation of how the recommendation algorithm would work</figcaption></figure><p>If the classification method gets detailed and fine-tuned enough it should be able to classify with much detail what type of part you want. The narrowed search saves a lot of time. This is especially useful in a library where there are thousands of similar parts.</p><h3>Conclusion</h3><p>Deep Learning (Artificial Intelligence) is a field of study that has immense possibilities as it enables us to extract a lot of knowledge from raw data. At its core it is merely data analysis. In this age of the internet, data is everywhere and if we are able to extract it efficiently, a lot can be accomplished.</p><p>This field has a lot of possible applications in the domain of Mechanical Engineering as well. Since almost all studies in Deep Learning need a domain expert it would be advisable for all engineers with interest in Data Analytics, even though they haven’t majored in Computer Sciences, to learn about data science, machine learning and examine its possibilities. The knowledge of the domain plus the skills of data analysis will really help us excel in our own fields.</p><h3>Acknowledgements</h3><p>I am thankful to Pro-Mech Minds for letting me do this and specially to its data science team which includes Gopal Kisi, Bishesh Shakya and Series Chikanbanjar for their immense help with this project. Pro-Mech Minds &amp; Engineering Services is one of the companies in Nepal working with both mechanical and IT solutions in engineering. This idea popped as an attempt to combine design engineering with Data Science. Last but not the least I would like to offer my special thanks to Saugat K.C. for acting as a mentor for our Data Science team.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*unCbNOGCSYz5fUUS.png" /><figcaption><a href="http://www.promechminds.com/">Source</a></figcaption></figure><p><a href="https://github.com/Promech2020/Mech-parts-classification-seq-model">Link to the code in github</a></p><p>References</p><p>[1]<a href="https://towardsdatascience.com/@conrmcdonald">Conor McDonald</a>, <a href="https://towardsdatascience.com/machine-learning-fundamentals-via-linear-regression-41a5d11f5220">Machine learning fundamentals (I): Cost functions and gradient descent(2017)</a>, Towards data science</p><p>[2]<a href="https://machinelearningmastery.com/author/jasonb/">Jason Brownlee,</a> <a href="https://machinelearningmastery.com/difference-between-a-batch-and-an-epoch/">Difference Between a Batch and an Epoch in a Neural Network(</a>2018), machinelearningmastery.com</p><p>[3] <a href="https://en.wikipedia.org/wiki/Hyperparameter_(machine_learning)">Hyperparameter_(machine_learning),</a> Wikipedia</p><p>[4] Andrew Ng, Convolutional Neural Networks of the Deep Learning Specialization by deeplearning.ai. (n.d.). Retrieved from <a href="https://www.coursera.org/specializations/deep-learning">Coursera</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9dd94adc492" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/artificial-intelligence-in-mechanical-engineering-a9dd94adc492">Artificial Intelligence in  Mechanical Engineering</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[K-means and PCA for Image Clustering: a Visual Analysis]]></title>
            <link>https://medium.com/data-science/k-means-and-pca-for-image-clustering-a-visual-analysis-8e10d4abba40?source=rss-36012891cc8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e10d4abba40</guid>
            <category><![CDATA[plotly]]></category>
            <category><![CDATA[principal-component]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[image]]></category>
            <category><![CDATA[k-means]]></category>
            <dc:creator><![CDATA[Sunny K. Tuladhar]]></dc:creator>
            <pubDate>Wed, 03 Jun 2020 03:26:00 GMT</pubDate>
            <atom:updated>2020-06-10T08:12:37.847Z</atom:updated>
            <content:encoded><![CDATA[<h4>We can use K-means and Principle Component Analysis(PCA) for clustering images on the Fashion MNIST dataset. We will also visually analyze the results using <a href="https://matplotlib.org/">matplotlib </a>and <a href="https://plotly.com/">plotly</a>.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*ogbAotjStIKLG4TyLzzDtQ.png" /><figcaption>The Fashion MNIST data set. Image from <a href="https://www.researchgate.net/figure/Examples-from-the-Fashion-MNIST-dataset_fig6_333997546">researchgate.net</a></figcaption></figure><p>What we will be doing here is train a K-means clustering model on the f-MNIST data so that it is able to cluster the images of the data-set with relative accuracy and the clusters have some logic to them which we can understand and interpret. We will then visually analyze the results of the clustering using matplotlib and plotly with reference to the actual labels (y) and draw a rough conclusion on how k-means clustering performs on an image data-set. The final code is available on the link at the end.</p><p>The words <em>features </em>and <em>components </em>have been used interchangeably in this article.</p><p><a href="https://github.com/sunman91/Data-Science-stuff/blob/master/k-means-and-pca-on-f-mnist-dataset.ipynb"><strong><em>Get straight to the code on Github.</em></strong></a></p><h3>Introduction</h3><p><strong>Clustering </strong>is an unsupervised machine learning algorithm and it recognizes patterns without specific labels and clusters the data according to the features. In our case, we will see if a clustering algorithm (k-means) can find a pattern between different images of the apparel in f-MNIST without the labels (y).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*JUm9BrH21dEiGpHg76AImw.gif" /><figcaption>A gif illustrating how K-means works. Each red dot is a centroid and each different color represents a different cluster. Every frame is an iteration where the centroid is relocated. (Source: <a href="https://gfycat.com/softenragedhypsilophodon">gyfcat</a>)</figcaption></figure><p><strong>K-means</strong> clustering works by assigning a number of centroids based on the number of clusters given. Each data point is assigned to the cluster whose centroid is nearest to it. The algorithm aims to minimize the squared Euclidean distances between the observation and the centroid of cluster to which it belongs.</p><p><strong>Principal Component Analysis or PCA </strong>is a method of reducing the dimensions of the given dataset while still retaining most of its variance. Wikipedia defines it as, “<em>PCA is defined as an orthogonal linear transformation that transforms the data to a new coordinate system such that the greatest variance by some scalar projection of the data comes to lie on the first coordinate (called the first principal component), the second greatest variance on the second coordinate, and so on.”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*UpFltkN-kT9aGqfLhOR9xg.gif" /><figcaption>PCA visualisation. The best PC (black moving line) is when the total length of those red lines are minimum. It will be used instead of the horizontal and vertical components (Source: <a href="https://giphy.com/gifs/pca-Lyejb62QjQepG">giphy </a>)</figcaption></figure><p>Basically PCA reduces the dimensions of the dataset while conserving most of the information. For e.g. if a data-set has 500 features, it gets reduced to 200 features depending on the specified amount of variance retained. Higher the variance retained,more information is conserved, but more the resulting dimensions will be.</p><p>Less dimensions means less time to train and test the model. In some cases models which use data-set with PCA perform better than the original dataset. The concept of PCA and the changes it causes on images by changing the retained variance is shown brilliantly <a href="https://towardsdatascience.com/pca-using-python-scikit-learn-e653f8989e60">here</a>.</p><h3>The plan</h3><p>So the plan is to perform k-means on the data-set but only after applying PCA on it.</p><ol><li>Load the data-set from keras</li><li>Pre-process the data, flatten the data (from 60000 x 28 x 28 array to 60000 x 784 array)</li><li>Apply PCA on it to reduce the dimensions (784 to 420 using 0.98 variance)</li><li>Apply K-means clustering on the PC data-set (10 clusters)</li><li>Observe and Analyze the results using matplotlib and plotly</li></ol><h3>The data-set</h3><p>The f-MNIST dataset is a slightly advanced dataset compared to the MNIST numbers dataset and it consists of 28 x 28 pixel images of different variety of clothing with the numbers representing the following type of clothing.</p><pre>#Loading required libraries<strong><br>import keras<br>from keras.datasets import fashion_mnist <br>import numpy as np<br>import matplotlib.pyplot as plt<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.cluster import KMeans</strong><br></pre><pre><strong>#Loading the dataset<br>(X_train,y_train), (X_test,y_test) = fashion_mnist.load_data()</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*ogbAotjStIKLG4TyLzzDtQ.png" /><figcaption>The Fashion MNIST data set</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iLss7dBAEt9zgNWB.png" /><figcaption>Each image is 28 x 28 pixel with different variety of clothing, shoes and bags</figcaption></figure><h3><strong>Data pre-processing</strong></h3><p>We reshape the data into 2D array from a 3D array by flattening the features into 1 dimension. Each image of 28 x 28 array is now a single array of 784 features. So our dataset becomes 60000, 784 array from the previous 60000,28,28.</p><pre>#Reshaping X to a 2D array for PCA and then k-means<br><strong>X = X_train.reshape(-1,X_train.shape[1]*X_train.shape[2])</strong> #We will only be using X for clustering. No need of y.</pre><pre><strong>print (&quot;The shape of X is &quot; + str(X.shape))<br>print (&quot;The shape of y is &quot; + str(y.shape))</strong> #We will be using y only to check our clustering</pre><pre><br><strong>Output:</strong><br>The shape of X is (60000, 784)<br>The shape of y is (60000,)</pre><h3>PCA (Principle Component Analysis)</h3><p>We will now use PCA on our dataset to reduce our dimensions. We will pick our retained variance of 0.98 (value selected through trial and error) and use it on our dataset.</p><pre><strong>from sklearn.decomposition import PCA</strong><br># Make an instance of the Model</pre><pre><strong>variance = 0.98</strong> #The higher the explained variance the more accurate the model will remain, but more dimensions will be present</pre><pre><strong>pca = PCA(variance)<br></strong><br><strong>pca.fit(Clus_dataSet)</strong> #fit the data according to our PCA instance</pre><pre><strong>print(&quot;Number of components before PCA  = &quot; + str(X.shape[1]))<br>print(&quot;Number of components after PCA 0.98 = &quot; + str(pca.n_components_))</strong> <br>#dimension reduced from 784</pre><pre><strong>Output:</strong><br>Number of components before PCA  = 784<br>Number of components after PCA 0.98 = 420</pre><p>We now transform the data according to the PCA instance</p><pre><strong>Clus_dataSet = pca.transform(Clus_dataSet)</strong></pre><pre><strong>print(“Dimension of our data after PCA = “ + str(Clus_dataSet.shape))</strong></pre><pre><strong>Output:</strong><br>Dimension of our data after PCA  = (60000, 420)</pre><p>We can also inverse transform the data to view how the data changes because of the PCA.</p><pre><strong>approximation = pca.inverse_transform(Clus_dataSet)</strong></pre><pre>#image reconstruction using the less dimensioned data<br><strong>plt.figure(figsize=(8,4));</strong></pre><pre>n = 500 #index value, change to view different data</pre><pre># Original Image<br><strong>plt.subplot(1, 2, 1);<br>plt.imshow(X[n].reshape(X_train.shape[1], X_train.shape[2]),<br> cmap = plt.cm.gray,);<br>plt.xlabel(str(X.shape[1])+’ components’, fontsize = 14)<br>plt.title(‘Original Image’, fontsize = 20);</strong></pre><pre># 196 principal components<br><strong>plt.subplot(1, 2, 2);<br>plt.imshow(approximation[n].reshape(X_train.shape[1], X_train.shape[2]),<br> cmap = plt.cm.gray,);<br>plt.xlabel(str(Clus_dataSet.shape[1]) +’ components’, fontsize = 14)<br>plt.title(str(variance * 100) + ‘% of Variance Retained’, fontsize = 20);</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*CPby1PT9kCFLkkwjCkyrPw.png" /><figcaption>The data on the left is the original (784 components) , the one on the right is inverse transformed from the PCA (420 components) . Both have 28 x 28 dimensions.</figcaption></figure><h3>K-Means Clustering</h3><p>Building the k-means models we need values for the following parameters.</p><p><strong>init</strong>: Initialization method of the centroids. Value will be: “k-means++”. k-means++: Selects initial cluster centers for k-mean clustering in a smart way to speed up convergence.</p><p><strong>n_clusters</strong>: The number of clusters to form as well as the number of centroids to generate. Value will be: 10 ( we have 10 classes according to INDEX, might not be best but good enough for our context)</p><p><strong>n_init</strong>: Number of time the k-means algorithm will be run with different centroid seeds. The final results will be the best output of n_init consecutive runs in terms of inertia. Value will be: 35 based on our inertia results (might not be the best but good enough for our context)</p><p>So now we have our model and we fit it to our dataset. Try using the mentioned parameters first to check the results with this article. You can change them later and see different results.</p><pre><strong>k_means = KMeans(init = “k-means++”, n_clusters = 10, n_init = 35)<br>k_means.fit(Clus_dataSet)</strong></pre><p>Now the model has been fit on our Image dataset on which we had performed PCA . The data is now divided into 10 clusters. Now we have to check what type of image ended up in each of these clusters and see if there is any pattern to it. Remember the distribution will be similar but the number(label) of the clusters might be different when you execute this.</p><h3>Visualization and analysis</h3><p>After the fit, we use the following code to visualize our clusters.</p><pre><strong>G = len(np.unique(k_means_labels)) </strong>#Number of labels</pre><pre>#2D matrix  for an array of indexes of the given label<br><strong>cluster_index= [[] for i in range(G)]<br>for i, label in enumerate(k_means_labels,0):<br>    for n in range(G):<br>        if label == n:<br>            cluster_index[n].append(i)<br>        else:<br>            continue</strong></pre><pre>#Visualisation for clusters = clust</pre><pre><strong>plt.figure(figsize=(20,20));<br>clust = 3 #</strong>enter label number to visualise<strong><br>num = 100 </strong>#num of data to visualize from the cluster<strong><br>for i in range(1,num): <br>    plt.subplot(10, 10, i); </strong>#(Number of rows, Number of column per row, item number)<strong><br>    plt.imshow(X[cluster_index[clust][i+500]].reshape(X_train.shape[1], X_train.shape[2]), cmap = plt.cm.binary);<br>    <br>plt.show()</strong></pre><p>As you can see below this particular cluster ( 3 in my case) does a great job of clustering Ankle Boots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*NGXCrG_zt_cWUbBe2QS4Gg.png" /><figcaption>Cluster 3 seems to hold Ankle Boots (slightly short ones) , Sneakers and some sandals</figcaption></figure><p>The code for the following bar-graph visualization is available on the link at the end. This uses the category labels from the <em>y_train </em>of the dataset and checks the quantity of a certain category in a given cluster. The graph will be same (if you used the same parameters) while the number(label) of the clusters might be different when you execute it. <em>E.g. in mine a cluster labelled 0 seems to be a cluster of Sandals, in yours this cluster might be labelled 4.</em></p><p><em>Note: Cluster Names are </em><strong>ABOVE </strong><em>the bargraph.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*HaIGwi5H9Qlyn4tOFkaGnA.png" /><figcaption>Bar graph of clusters 0~ 3</figcaption></figure><p><strong>Cluster 0</strong> seems to have mostly Sandals.</p><p><strong>Cluster 1 </strong>seems random but mostly has only upper body clothes. <em>(T-shirt, Pullover, Dress, Coat and Shirt)</em></p><p><strong>Cluster 2</strong> also has upper body clothes but less varied.<em>(Pullover,Shirt and Coat)</em></p><p><strong>Cluster 3</strong> seems to have mostly Ankle Boots few Sneakers and sandals. Basically all are shoes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*TlJbr7t6ii6OE5EymHelgQ.png" /><figcaption>Bar graph of clusters 4 ~ 7. Cluster 6 and 7 both seems to have bags.</figcaption></figure><p>Similarly we can observe clusters 4 ~7.In both the clusters 6 and 7 (in my case) there seem to be majority of Bags . But upon using the visualization of the above clusters (shown below) we see a sensible pattern. One cluster has the bag handles lifted (among other things), the other does not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*8myhP794EK4WVt1cqEULgw.png" /><figcaption>Cluster 6 seems to have bags with handles up.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*GSpkG9taEYjJZ4noDQUhgQ.png" /><figcaption>Cluster 7 seems to have bags with handles downs.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*katGtNTrzkiUaVr71W9vJQ.png" /><figcaption>Bar graph of clusters 8 and 9 which seem to have shoes.</figcaption></figure><p>The clusters 8 and 9 shown below seem to be shoes. Cluster 8 has a few sandals and mostly Sneakers, Cluster 9 seems to have a few sandals and mostly Ankle Boots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*XNDNW3RdV0frCtRmltmj5Q.png" /><figcaption>Cluster 8 seems to have Sneakers and Sandals. Both are shoes.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*9j4xVxlR59bldB8-mgpLxw.png" /><figcaption>Cluster 9 seems to have mainly Ankle Boots and a few Sandals. Both are shoes.</figcaption></figure><h3>3D Visualization of the clusters</h3><p>We will be visualizing the clusters in 3D using <a href="https://plotly.com/">plotly.</a> Plotly is an advanced visualization library for python. Use the following code to obtain a 3D scatter plot of the clustered data. We will using only be 3 features from the 420 features in our dataset. This visualization helps to understand how well the clusters have formed and how far out a single cluster is spread into other clusters.</p><pre>#install these if you haven’t<br><strong>!pip install chart_studio <br>!pip install plotly</strong></pre><pre><strong>import plotly as py<br>import plotly.graph_objs as go<br>import plotly.express as px</strong></pre><pre>#3D Plotly Visualization of Clusters using go</pre><pre><strong>layout = go.Layout(<br>    title=&#39;&lt;b&gt;Cluster Visualisation&lt;/b&gt;&#39;,<br>    yaxis=dict(<br>        title=&#39;&lt;i&gt;Y&lt;/i&gt;&#39;<br>    ),<br>    xaxis=dict(<br>        title=&#39;&lt;i&gt;X&lt;/i&gt;&#39;<br>    )<br>)</strong></pre><pre><strong>colors = [&#39;red&#39;,&#39;green&#39; ,&#39;blue&#39;,&#39;purple&#39;,&#39;magenta&#39;,&#39;yellow&#39;,&#39;cyan&#39;,&#39;maroon&#39;,&#39;teal&#39;,&#39;black&#39;]<br>trace = [ go.Scatter3d() for _ in range(11)]<br>for i in range(0,10):<br>    my_members = (k_means_labels == i)<br>    index = [h for h, g in enumerate(my_members) if g]<br>    trace[i] = go.Scatter3d(<br>            x=Clus_dataSet[my_members, 0],</strong># 0 is a component among the 420 components. Feel free to change it<strong><br>            y=Clus_dataSet[my_members, 1],</strong># 1 is a component among the 420 components. Feel free to change it<strong><br>            z=Clus_dataSet[my_members, 2],</strong># 2 is a component among the 420 components. Feel free to change it<strong><br>            mode=&#39;markers&#39;,<br>            marker = dict(size = 2,color = colors[i]),<br>            hovertext=index,<br>            name=&#39;Cluster&#39;+str(i),<br>   <br>            )</strong></pre><pre><strong>fig = go.Figure(data=[trace[0],trace[1],trace[2],trace[3],trace[4],trace[5],trace[6],trace[7],trace[8],trace[9]], layout=layout)<br>    <br>py.offline.iplot(fig)</strong></pre><p><strong><em>Output:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*AnZKU8pp9AnLBKGhzfDJhw.png" /><figcaption>3D plotly scatter plot Visualization of the k-means clustered f-MNIST dataset with PCA. Each color represents a different cluster.</figcaption></figure><p>Since the data-set (with PCA) actually has 420 dimensions, this visualization only shows 3 of those features in the scatter plot. The component to be plotted can be changed in the code to get an idea of this in term of different components.</p><p><em>(A further PCA can be done to reduce all the 784 components to 3 components to fully represent it in a 3D plot but a lot of the information will be lost while doing so)</em></p><h3><strong>Conclusion</strong></h3><p>The clustering does seem to group similar items together. A cluster either contains upper-body clothes<em>(T-shirt/top, pullover, Dress, Coat, Shirt)</em> or shoes <em>(Sandals/Sneakers/Ankle Boots) </em>or Bags. The clustering however performs poorly on trousers and seems to group it together with dresses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*OL-ca_Ln74IF7zeloeNMfQ.png" /><figcaption>A cluster with trousers and dresses</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*OOkz3E0TCOCJqu4ApNTqlw.png" /><figcaption>The data visualization of the dresses and trousers in the aforementioned cluster</figcaption></figure><p>But it distinguishes these two types of bags quite well. The pattern can be interpreted by us. One cluster has bags with raised handles, the other has the bags with unraised handles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*Pp7By9MTvaY7wzEovgbW4A.png" /><figcaption>2 clusters both with bags. But the algorithm was able to distinguish between the handle being raised and not raised</figcaption></figure><p>Similarly in the two clusters shown below both have a majority of Ankle boots. But the ankle boots seems to be of different sizes and the smaller ones do look similar to the sneakers which are in the same cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*TIJvZZDvDil_UM54CvEpdg.png" /><figcaption>Two clusters both with maximum ankle boots . The one on the left has shorter ones compared to the one on the right</figcaption></figure><p>Looking at the above results we can see the k -means algorithm distinguishes its clusters based on a reasonable pattern. Thus we can draw a rough conclusion that K-means clustering method after performing a Principal Component Analysis can get a decent result on classifying images without labels.</p><p><a href="https://github.com/sunman91/Data-Science-stuff/blob/master/k-means-and-pca-on-f-mnist-dataset.ipynb"><strong><em>Click here for the link to the code</em></strong></a></p><p><em>References</em></p><p>[1] A. Ng, Machine Learning by Stanford University. (n.d.). Retrieved from <a href="https://www.coursera.org/learn/machine-learning">https://www.coursera.org/learn/machine-learning</a></p><p>[2] <a href="https://medium.com/@joel_34096?source=post_page-----a648f28bdc47----------------------">S Joel Franklin</a> , <a href="https://medium.com/@joel_34096/k-means-clustering-for-image-classification-a648f28bdc47">K-Means Clustering for Image Classification</a>(2020), <a href="https://medium.com/">Medium</a></p><p>[3] <a href="https://github.com/mGalarnyk">Michael Galarnyk</a>, <a href="https://github.com/mGalarnyk/Python_Tutorials/blob/master/Sklearn/PCA/PCA_Image_Reconstruction_and_such.ipynb">PCA + Logistic Regression (MNIST)</a>(2018), <a href="https://github.com/">github</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e10d4abba40" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/k-means-and-pca-for-image-clustering-a-visual-analysis-8e10d4abba40">K-means and PCA for Image Clustering: a Visual Analysis</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CAD Automation: Feature Recognition]]></title>
            <link>https://medium.com/@SunnyKTuladhar/cad-automation-feature-recognition-fba74b7cde27?source=rss-36012891cc8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/fba74b7cde27</guid>
            <category><![CDATA[3d-design]]></category>
            <category><![CDATA[cad]]></category>
            <category><![CDATA[mechanical-engineering]]></category>
            <category><![CDATA[3d-modeling]]></category>
            <category><![CDATA[solidworks]]></category>
            <dc:creator><![CDATA[Sunny K. Tuladhar]]></dc:creator>
            <pubDate>Tue, 10 Dec 2019 10:51:39 GMT</pubDate>
            <atom:updated>2019-12-10T10:51:39.031Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>CAD automation is basically the automation of tasks performed by a CAD software. It involves the creation of programs or macros that automatically perform certain repetitive and mundane tasks. These tasks would otherwise require lots of manual input and consume a lot of time. In the engineering design process, this helps save the designer’s time and encourages focus on other creative aspects of the process that have to be thought through by humans and cannot be automated. Feature recognition is one of those aspects of CAD automation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cI7fysZ8AJoMerjH" /><figcaption>Feature Recognition is analogous to this shape filter. It can distinguishes between different types of parts using a filter that recognizes the part’s features.</figcaption></figure><p>Feature Recognition, in the case of Computer Aided Design, is basically the computer recognizing what type of feature is the selected <em>entity </em>and combining these recognized features to tell what kind of part the model is. An <em>entity </em>could be anything from a Body, Surface, a Line, a Vertex etc. that constitutes a CAD file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/0*mhvxHuv1AZjhwRgN" /><figcaption>The basic entities in a CAD 3D model.</figcaption></figure><p>For example, if there is a model of a Shaft how can the <em>computer</em> know it is a Drive Shaft or a Linear Shaft? It can recognize that the model has a cylindrical faces with adjacent flat faces and some key grooves. By recognizing all this in one model it is able to tell that this particular model is a Drive Shaft. Below is an image of a linear shaft (top) and a drive shaft(bottom).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/0*GB-ro0UhUzOzCS9S.jpg" /><figcaption>A linear shaft that is used for support</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/0*10M7913qkCsPIdt0" /></figure><p>The main idea is to be able to distinguish different types of parts from each other based on their 3D models and then be able to categorize them into different groups.</p><p>A simple application would be an online Part Recommendation System. Before a user orders a mechanical part online he will first view the catalog, download its 3D file and check if it is compatible for his application by placing it in his assembly. To check for the best part he can either start searching for the serial code of the required part OR use a feature recognition (FR) system. In the FR system the user will enter create a rough 3D model of the required part in a CAD software and then input it into the system. The system will then use various feature recognition algorithms on the input model to give a list of closest matching parts from the catalog. The user can just select from this list instead of the entire catalog or having to search for the correct part number.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/0*1N3wH5KZ9uYk5a4p" /><figcaption>A flowchart of the workings of a feature recognition based recommendation system</figcaption></figure><p>This is especially helpful if you have sextillion parts and configurations in the catalog. Yes, that’s right. Sextillion is 10 raised to power of 21. A company called the ‘Misumi group’ claims to have 80 Sextillion possible part configurations in its complete catalog.</p><p>Below is an image from the website of the multinational Misumi Group. Here’s the link to their US website :<a href="https://us.misumi-ec.com/">https://us.misumi-ec.com/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*LH90WYs-SvKPsXD2" /><figcaption>Misumi group’s website</figcaption></figure><p>Here, we will discuss a very basic Condition-based feature recognition (Using if-then based algorithms). It uses the API of the CAD software to detect various entities (surfaces, vertexes,edges etc.) of a 3D model and classifies parts using condition based (e.g. if -then) algorithms depending on the detected features in the model.</p><h3><strong>The process</strong></h3><p>Firstly to explain feature recognition, suppose we have a simple algorithm/function that can distinguish the type of face a surface of the CAD data contains and count of its frequency. <em>(These can be achieved using various CAD software APIs that usually come built-in with the software system.) </em>It can tell whether a surface is a Cylindrical, Planar, Spherical, Conical etc.</p><p>How can we make a program that can classify if an object is a <strong>cylinder</strong>, a <strong>cuboid</strong> or a <strong>pyramid</strong>? Here are a few classification conditions based on no. of plane faces and no. of cylindrical faces of the presented model.</p><p>It is a <strong>Cylinder </strong>if it has 2 plane faces and 1 Cylindrical faces.</p><p>It is a <strong>Cuboid </strong>if it has 6 plane faces and 0 Cylindrical Faces.</p><p>It is a <strong>Pyramid </strong>if it has 4 Plane faces and 0 Cylindrical faces.</p><p>(These conditions are considering there are the only three types of parts in the domain.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/0*DfH9qCCM1txQgZQQ" /><figcaption>Shape classification of primitives</figcaption></figure><p>This could be further simplified considering the above three part domain.</p><p>If it has 1 Cylindrical face, it is a <strong>Cylinder</strong>.</p><p>If it has 4 Plane faces, it is a <strong>Pyramid </strong>.</p><p>Else, it is a <strong>Cuboid</strong>.</p><p>Now lets look at a (slightly) more practical approach to this part classification algorithm using Feature recognition. Consider we have 3 variations of the same part. Part A is a basic shaft, a cylindrical body with no fillets or chamfers. Part B is the same shaft but with a chamfer at one end. Part C is the same shaft but with a fillet at one end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/0*brsBaN5poUIzhhsC" /><figcaption>Categorization of 3 types of shafts</figcaption></figure><p>The distinguishing features among these parts are the Conical face of Part B and Torus(Doughnut shape) face of Part C. The complete face type list count is shown below the images. Since the Flat face and Cylindrical Face count is the same in all three, it is not a useful distinguishing feature. Here’s the basic algorithm.</p><p>If it has 1 Conical Face, it is Part B</p><p>If it has 1 Torus Face, it is Part C</p><p>Else, it is Part A</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/0*wBXYzlgBJbjN5Tcn" /><figcaption>A flowchart for the algorithm categorizing the 3 types of shafts</figcaption></figure><p>In this way we can distinguish the parts A, B and C. To the left is the flowchart for categorization of the parts on the condition that the domain only consists of the three parts A, B and C. Here we are creating a kind of filter for each proceeding part, removing the wrong options.</p><p>Note that this method completely ignores the Cylindrical and flat faces in the algorithm.</p><p>Note that this method completely ignores the Cylindrical and flat faces in the algorithm.</p><p>In addition to different surface types most CAD software have other types of functions that detect/count vertices, detect/count types of edges, detect adjacent edges, measure distance/angle between two points or planes, measure area of a surface, check for geometric conditions between entities such as tangency, coincidence, concentricity and many many more.</p><p>Here is the link to Solidworks API Help which has documentation on <em>all </em>of the functions that are available in Solidworks in languages of VBA, VB.NET, Visual C#, Visual C++ 6.0, or Visual C++/CLI. <a href="https://help.solidworks.com/2019/English/api/sldworksapiprogguide/Welcome.htm">https://help.solidworks.com/2019/English/api/sldworksapiprogguide/Welcome.htm</a></p><h3><strong>Coding Stuff</strong></h3><p>The Solidworks API is the one I have experience with and we will discuss it briefly here. For us to make the program the required tasks the API is required. It is a list of built-in functions and data types in the API that can be used to make other complex functions and ultimately make the program do the required tasks.</p><p>Broadly speaking, there are two main types of API. The object and the function. The object is the data type (entity). It could be a body, an edge, a vertex, a surface, a vector etc. A single object can have different parameters within itself. For example the surface type object will have the following parameters depending on its type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/0*uC9E70swUj0VRA9i" /><figcaption>Description of the different parameters in the different face types.</figcaption></figure><p>For a surface of type Cone will have parameters arranged in an array in the following order. Parameters:<em> origin.x origin.y origin.z axis.x axis.y axis.z radius half angle. </em>So if we need to find the radius of the cone we can use conicalFace[6].</p><p>A <strong>function </strong>API on the other hand will help to either create, remove, edit or analyse these objects. An example could be the IsCylinder() method. It is a boolean function that returns whether the surface selected is a Cylinder or not.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fba74b7cde27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CAD and Automation]]></title>
            <link>https://medium.com/@SunnyKTuladhar/cad-and-automation-e0368cd28b30?source=rss-36012891cc8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0368cd28b30</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[cad]]></category>
            <category><![CDATA[code]]></category>
            <dc:creator><![CDATA[Sunny K. Tuladhar]]></dc:creator>
            <pubDate>Thu, 26 Sep 2019 05:48:49 GMT</pubDate>
            <atom:updated>2019-09-26T07:31:16.973Z</atom:updated>
            <content:encoded><![CDATA[<h3>Computer Aided Design(CAD) and Automation</h3><p>When we talk about Mechanical Engineering, CAD(Computer Aided Design) is something we associate with design and creativity and thus do not consider it a process that be automated.</p><p>This article tries to explain why CAD automation is needed ,how its done and why Mechanical engineers or CAD users in general, need to get acquainted with programming.</p><p>We associate CAD with modeling and designing complex products with regards to minute details that a customer might require, using simulations to test the design ,make changes and finally using the best design to actually manufacture the product.</p><p>We associate CAD with custom made designs, designs that have been specifically tailored for that specific product. <br>How then, can such a practice be automated and WHY should it be automated? <em>(Some people might link automation with AI or Machine Learning, that is not what we are talking about for now. )</em></p><p>The answer to “CAN it be automated?” is obviously “yes”(this article wouldn’t exist otherwise), using software APIs and code. What is an API? It stands for Application Programming Interface. Here’s a short description.</p><blockquote>“….. an API lists a bunch of operations that developers can use, along with a description of what they do. The developer doesn’t necessarily need to know how, for example, an operating system builds and presents a “Save As” dialog box. They just need to know that it’s available for use in their app.” <a href="https://www.howtogeek.com/343877/what-is-an-api/">https://www.howtogeek.com/343877/what-is-an-api/</a></blockquote><p><em>(Basically ,for CAD it could be a function in the code that inputs a face of the model and returns whether it is a “Cylinder, Sphere , Conical, Flat” Surface. We don’t know how it is done and we don’t need to know. We are concerned with the inputs and outputs of the API. )</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*bF-0c4N7Br2pVV3i35dpWQ.png" /><figcaption>The image shows the loop of the tasks before and after automation. Before automation the person is involved in the entire task loop. After automation the person only gives a certain number of input, the rest of the task loop is handled by the computer. <em>Source: Shashank Dewan’s presentation on CAD Automation.</em></figcaption></figure><p>Design is a long and intense process and not all of the included tasks involve creativity. Most are repetitive and can be easily automated. The key is to automate these tasks to save more time for the creative processes.</p><p>E.g. Modeling of gears. Gears are mostly a standard part so having to model them every time is tedious. You can make an app to auto-generate the gear of required dimensions.</p><p>Taking the above image as an example. The number of input to make a gear from scratch (using sketches, extrude etc.) would a take lot more time than to just input its parameters(dimensions and getting the result). See another image below for the <strong>OnShape </strong>parametric gear tool.</p><p>The answer to “WHY we need automation?” is: to save time. A lot of time can be saved using automation. This saved time can be used by the designer to focus on more person-oriented decisions and creativity.</p><p>To understand CAD automation it helps to have a basic knowledge of coding and how computer algorithms work. CAD Automation goes hand in hand with Customization as most companies have extremely specific repetitive tasks that are often simplified by Custom Tools on that software.</p><p>Here are a few examples of CAD Automation.</p><p><strong>Parametric Modeling</strong>: One of the things you have to understand is a product is made from the assembly of many parts and most of these parts are standard parts (as opposed to custom parts) and to be able to generate these standard parts instantly without having to actually model them saves a lot of time. This is called Parametric Modeling. In this you only have to enter a select number of dimensions of a part and you get an output model of the specified dimensions. The software generates the model directly based on the dimensions only.</p><figure><img alt="The gear tool in OnShape that creates a Spur gear by only giving the dimensions. There is no need for Modeling." src="https://cdn-images-1.medium.com/max/756/1*Jdw8KyLy_4xGPL_UahDunw.png" /><figcaption>The gear tool in <strong><em>Onshape </em></strong>creates a gear using only the dimensions shown at the left. No need for sketching or modeling.</figcaption></figure><p><em>For Example</em> : Suppose you need a standard spur gear for your product. In the above image, you have to enter the required dimensions(The Parameters) i.e. Number of teeth, Module, Pitch circle diameter etc. and the required gear model will be automatically generated.</p><p><strong>Custom CAD Tools:</strong> All companies have their own share of repetitive tasks. Each has its own requirements. If a tool can be created for that specific task in the software that is to be used then it reduces the job time from days to hours and even minutes. Now almost all CAD software have a certain degree of customizing ability in them. Using their APIs you can create tools to automate extremely specific tasks.</p><p><em>OnShape</em><strong><em> </em></strong>has built its own language called <em>FeatureScript </em>which is designed specific for CAD users with no previous knowledge of programming. The actual features(Tools) in the Software are made using this script so you can copy the codes from the original tools and use it in your custom tool. The above mentioned Gear Tool is also a custom tool made using <em>FeatureScript</em>.<br><em>More on </em>FeatureScript : <a href="https://cad.onshape.com/FsDoc/">https://cad.onshape.com/FsDoc/</a></p><p><em>Here is the </em>FeatureScript <em>code for the above mentioned Gear Tool</em>. <a href="https://cad.onshape.com/documents/5742c8cde4b06c68b362d748/v/d9a567ca70312617baeb64e8/e/01a666571e625f8b819fd75b">https://cad.onshape.com/documents/5742c8cde4b06c68b362d748/v/d9a567ca70312617baeb64e8/e/01a666571e625f8b819fd75b</a></p><p>Other softwares also have built their API in the required languages. For example Solidworks has its API in VBA, VB.NET, Visual C#, Visual C++ 6.0, or Visual C++/CLI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*eRXGBDYWXAswGKO-Kwaoug.png" /><figcaption>The “Structural Member” tool in the “Weldments” workbench of Solidworks could be considered an example of a custom tool. It converts a straight line into a structural member directly. We only have specify the parameters of the member.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*B18NHvsKUKWt3BgKT02lOw.png" /><figcaption>This custom tool arranges the dimensions in SolidWorks drawing. The drawing in the initial state is converted into the final state as shown automatically. Developed by Shashank Dewan from Pro-Mech Minds. <em>Source: Shashank Dewan’s presentation on CAD Automation.</em></figcaption></figure><p>The image shown above is the dimension arranger tool developed by Shashank Dewan for SolidWorks. It arranges haphazard dimensions into a clean looking non-intersecting dimensions drawing. This simple tool saves time as the drafter can just give dimensions randomly for confirmation and the API will automatically create the clean presentable version.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rOVOE81FsBisIcTB80pvEg.gif" /><figcaption>A gif demonstrating the actual functioning of the Dimension Arrangement Tool.</figcaption></figure><p><strong>Feature Recognition: </strong>Suppose you want to search for an available standard part based on a part you just modeled or for you assembly. Previously, you would have to go to a company website and search for the part based on serial numbers and part names. Now it is possible to input a 3D model of the part you modeled and get a list of recommended parts based on your 3D model. Of course this has not been implemented in all websites but this is a lot easier than the previous process. This is all possible due to <em>Feature Recognition.</em></p><p>Feature Recognition in 3D CAD, is basically a software’s ability to distinguish shapes and tell what the 3D model is. It basically works by knowing this circular shaped thing is a “Cylinder”. By combining basic shapes (cylinders, cuboids, holes) a software can be made to correctly classify parts to a given list of part types. E.g. a Bearing, Screw, plate , Shaft</p><p>Another use for Feature Recognition is to evaluate, measure dimensions of a part. This is particularly useful when you have to model tens of thousands of parts and have to confirm(check) the dimensions of each. If a person takes 5 minutes to check the dimensions, the computer can do it within 3 seconds. Multiply that by 10000 and you can imagine why Automation saves time.</p><p><strong>In conclusion</strong>, automation in CAD has really changed the way we approach design and manufacturing. It has simplified tasks that would have been extremely tedious and time-consuming to do manually. At the same time it has created a small black-box of mystery of how the tasks in the software are actual performed. So for CAD users today it really helps to have a basic understanding of programming and computer algorithms to understand how a software works. Once we can do that it becomes easier to understand what can be automated and how it can be automated and hence make our lives easier.</p><p>P.S. A personal anecdote:<br>Working as a CAD Engineer there were times when we were asked by a Japan-based company to rename files. As mundane as the task it may sound, all CAD engineers must have experienced this. When old part drawings and models are reused for other products the file names have to be changed.</p><p><em>For example</em>: When a parts of PSG 666 are going to be used for PSG 648 then file names PSG -666- 001.cad ,PSG -666- 002.cad…. will have to be turned to PSG-648 -001.cad , PSG -666- 002.cad…. There were 600 files to be renamed!!<br>There were many methods using Python or C# code to rename all the files at once, but that would need installing the language in the PC. Since the PCs are licensed you cannot install any extra programs. Fortunately I discovered a batch file code that could be used to rename multiple files at once.</p><p>The script file shown below runs by default on windows and does not require any extra installations. I used this code and the job that would have required 1 hour was finished in 2 seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4VZym6NJMGBgMuN6eEf_Ew.png" /><figcaption>A batch file to rename multiple files simultaneously.</figcaption></figure><p>This is a very simple and not a direct example of a CAD automation but still you get the basic idea. If you think a task can be automated, it is always worth it to find out how it can be done. Automation saves time, use it!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MW4KS8AsHiYX5XEK.png" /><figcaption>A task that would take hours to do manually can be reduced into a few minutes or even seconds using automation.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0368cd28b30" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>