{"id":22,"date":"2024-10-11T12:51:54","date_gmt":"2024-10-11T12:51:54","guid":{"rendered":"https:\/\/kindsonthegenius.com\/pytorch\/?p=22"},"modified":"2024-10-18T21:39:55","modified_gmt":"2024-10-18T21:39:55","slug":"pytorch-tutorials-build-the-model","status":"publish","type":"post","link":"https:\/\/kindsonthegenius.com\/pytorch\/pytorch-tutorials-build-the-model\/","title":{"rendered":"PyTorch Tutorial &#8211; Build the Model"},"content":{"rendered":"<p>In this tutorial, we would now have to create a neural network model. To do this in Pytorch we do the following:<\/p>\n<ul>\n<li>create a class that extends the nn.Module class<\/li>\n<li>\u00a0define the layers of the network in the <strong>init<\/strong> method<\/li>\n<li>specify how data would pass through the network in the forward function<\/li>\n<li>define a device which could be a gpu, cpu or mps<\/li>\n<\/ul>\n<p>&nbsp;<\/p>\n<ol>\n<li><a href=\"#t1\"> Declare the Device<\/a><\/li>\n<li><a href=\"#t2\"> Create the Neural Network Model<\/a><\/li>\n<li><a href=\"#t3\"> Understanding the Model<\/a><\/li>\n<\/ol>\n<p>&nbsp;<\/p>\n<h4 id=\"t1\"><strong>Declare the Device<\/strong><\/h4>\n<p>Here we use GPU if it exists, else we use the CPU.<\/p>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #888888;\"># Declare the device: cuda or mps or cpu<\/span>\r\ndevice <span style=\"color: #333333;\">=<\/span> (\r\n    <span style=\"background-color: #fff0f0;\">\"cuda\"<\/span>\r\n    <span style=\"color: #008800; font-weight: bold;\">if<\/span> torch<span style=\"color: #333333;\">.<\/span>cuda<span style=\"color: #333333;\">.<\/span>is_available()\r\n    <span style=\"color: #008800; font-weight: bold;\">else<\/span> <span style=\"background-color: #fff0f0;\">\"mps\"<\/span>\r\n    <span style=\"color: #008800; font-weight: bold;\">if<\/span> torch<span style=\"color: #333333;\">.<\/span>backends<span style=\"color: #333333;\">.<\/span>mps<span style=\"color: #333333;\">.<\/span>is_available()\r\n    <span style=\"color: #008800; font-weight: bold;\">else<\/span> <span style=\"background-color: #fff0f0;\">\"cpu\"<\/span>\r\n)\r\n<span style=\"color: #007020;\">print<\/span>(f<span style=\"background-color: #fff0f0;\">\"Using device {device}\"<\/span>)\r\n<\/pre>\n<p>&nbsp;<\/p>\n<h4 id=\"t2\"><strong>2. Create the Neural Network Model<\/strong><\/h4>\n<ul>\n<li>create a class that extends the nn.Module class<\/li>\n<li>define the layers of the network in the init method<\/li>\n<li>specify how data would pass through the network in the forward function<\/li>\n<\/ul>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #008800; font-weight: bold;\">class<\/span> <span style=\"color: #bb0066; font-weight: bold;\">NeuralNetwork<\/span>(nn<span style=\"color: #333333;\">.<\/span>Module):\r\n    <span style=\"color: #008800; font-weight: bold;\">def<\/span> <span style=\"color: #0066bb; font-weight: bold;\">__init__<\/span>(<span style=\"color: #007020;\">self<\/span>):\r\n        <span style=\"color: #007020;\">super<\/span>()<span style=\"color: #333333;\">.<\/span>__init__()\r\n        \r\n        <span style=\"color: #888888;\"># create the input layer<\/span>\r\n        <span style=\"color: #007020;\">self<\/span><span style=\"color: #333333;\">.<\/span>flatten <span style=\"color: #333333;\">=<\/span> nn<span style=\"color: #333333;\">.<\/span>Flatten()\r\n        \r\n        <span style=\"color: #888888;\"># create the 2 hidden layers<\/span>\r\n        <span style=\"color: #007020;\">self<\/span><span style=\"color: #333333;\">.<\/span>linear_relu_stack <span style=\"color: #333333;\">=<\/span> nn<span style=\"color: #333333;\">.<\/span>Sequential(\r\n            nn<span style=\"color: #333333;\">.<\/span>Linear(<span style=\"color: #0000dd; font-weight: bold;\">28<\/span><span style=\"color: #333333;\">*<\/span><span style=\"color: #0000dd; font-weight: bold;\">28<\/span>, <span style=\"color: #0000dd; font-weight: bold;\">512<\/span>),\r\n            nn<span style=\"color: #333333;\">.<\/span>ReLU(),\r\n            nn<span style=\"color: #333333;\">.<\/span>Linear(<span style=\"color: #0000dd; font-weight: bold;\">512<\/span>, <span style=\"color: #0000dd; font-weight: bold;\">512<\/span>),\r\n            nn<span style=\"color: #333333;\">.<\/span>ReLU(),\r\n            nn<span style=\"color: #333333;\">.<\/span>Linear(<span style=\"color: #0000dd; font-weight: bold;\">512<\/span>, <span style=\"color: #0000dd; font-weight: bold;\">10<\/span>)\r\n        )\r\n        \r\n    <span style=\"color: #008800; font-weight: bold;\">def<\/span> <span style=\"color: #0066bb; font-weight: bold;\">forward<\/span>(<span style=\"color: #007020;\">self<\/span>, x):\r\n        x <span style=\"color: #333333;\">=<\/span> <span style=\"color: #007020;\">self<\/span><span style=\"color: #333333;\">.<\/span>flatten(x)\r\n        logits <span style=\"color: #333333;\">=<\/span> <span style=\"color: #007020;\">self<\/span><span style=\"color: #333333;\">.<\/span>linear_relu_stack(x)\r\n        <span style=\"color: #008800; font-weight: bold;\">return<\/span> logits\r\n    \r\nmodel <span style=\"color: #333333;\">=<\/span> NeuralNetwork()<span style=\"color: #333333;\">.<\/span>to(device)\r\n<span style=\"color: #007020;\">print<\/span>(model)\r\n<\/pre>\n<p>&nbsp;<\/p>\n<h4 id=\"t3\"><strong>3. Understanding the Model<\/strong><\/h4>\n<p>Now I will take some time to explain the model we created.<\/p>\n<p><strong>nn.Flatten()<\/strong> &#8211; this layer is used to flatten the input tensor from a 2D image (28 by 28 pixels) to a 1-d tensor (size 784) before feeding it into the fully connected layers.<\/p>\n<p><strong>nn.Sequential()<\/strong> &#8211; this is used to create a sequence of layers.<\/p>\n<p><strong>nn.ReLU()<\/strong> &#8211; this applies the activation function (<em>Rectified Linear Unit<\/em>) which introduces non-linearity to the model by zeroing out negative values<\/p>\n<p>In the forward() function, we do the following:<\/p>\n<ul>\n<li><strong>flattening<\/strong> &#8211; the input x, which is a batch of 2d images is flattened to a 1d tensor<\/li>\n<li>the flattened input layer is passed through the sequence of layers to produce the output logits (<\/li>\n<\/ul>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, we would now have to create a neural network model. To do this in Pytorch we do the following: create a class &hellip; <\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"footnotes":""},"categories":[78],"tags":[],"class_list":["post-22","post","type-post","status-publish","format-standard","hentry","category-pytorch-tutorial"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.9 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>PyTorch Tutorial - Build the Model - PyTorch Simplified Tutorial<\/title>\n<meta name=\"description\" content=\"In this PyTorch tutorial, we would build the NeuralNetwork and try to understand the Neural Network creation process\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/kindsonthegenius.com\/pytorch\/pytorch-tutorials-build-the-model\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"PyTorch Tutorial - Build the Model - PyTorch Simplified Tutorial\" \/>\n<meta property=\"og:description\" content=\"In this PyTorch tutorial, we would build the NeuralNetwork and try to understand the Neural Network creation process\" \/>\n<meta property=\"og:url\" content=\"https:\/\/kindsonthegenius.com\/pytorch\/pytorch-tutorials-build-the-model\/\" \/>\n<meta property=\"og:site_name\" content=\"PyTorch Simplified Tutorial\" \/>\n<meta property=\"article:published_time\" content=\"2024-10-11T12:51:54+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-10-18T21:39:55+00:00\" \/>\n<meta name=\"author\" content=\"Kindson Munonye\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Kindson Munonye\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"2 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/kindsonthegenius.com\\\/pytorch\\\/pytorch-tutorials-build-the-model\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/kindsonthegenius.com\\\/pytorch\\\/pytorch-tutorials-build-the-model\\\/\"},\"author\":{\"name\":\"Kindson Munonye\",\"@id\":\"https:\\\/\\\/kindsonthegenius.com\\\/pytorch\\\/#\\\/schema\\\/person\\\/2b1e3e1f9e5335a8493d437c3c835c66\"},\"headline\":\"PyTorch Tutorial &#8211; Build the Model\",\"datePublished\":\"2024-10-11T12:51:54+00:00\",\"dateModified\":\"2024-10-18T21:39:55+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/kindsonthegenius.com\\\/pytorch\\\/pytorch-tutorials-build-the-model\\\/\"},\"wordCount\":260,\"commentCount\":0,\"articleSection\":[\"PyTorch Tutorial\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/kindsonthegenius.com\\\/pytorch\\\/pytorch-tutorials-build-the-model\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/kindsonthegenius.com\\\/pytorch\\\/pytorch-tutorials-build-the-model\\\/\",\"url\":\"https:\\\/\\\/kindsonthegenius.com\\\/pytorch\\\/pytorch-tutorials-build-the-model\\\/\",\"name\":\"PyTorch Tutorial - Build the Model - PyTorch Simplified Tutorial\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/kindsonthegenius.com\\\/pytorch\\\/#website\"},\"datePublished\":\"2024-10-11T12:51:54+00:00\",\"dateModified\":\"2024-10-18T21:39:55+00:00\",\"author\":{\"@id\":\"https:\\\/\\\/kindsonthegenius.com\\\/pytorch\\\/#\\\/schema\\\/person\\\/2b1e3e1f9e5335a8493d437c3c835c66\"},\"description\":\"In this PyTorch tutorial, we would build the NeuralNetwork and try to understand the Neural Network creation process\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/kindsonthegenius.com\\\/pytorch\\\/pytorch-tutorials-build-the-model\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/kindsonthegenius.com\\\/pytorch\\\/pytorch-tutorials-build-the-model\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/kindsonthegenius.com\\\/pytorch\\\/pytorch-tutorials-build-the-model\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/kindsonthegenius.com\\\/pytorch\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"PyTorch Tutorial &#8211; Build the Model\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/kindsonthegenius.com\\\/pytorch\\\/#website\",\"url\":\"https:\\\/\\\/kindsonthegenius.com\\\/pytorch\\\/\",\"name\":\"PyTorch Simplified Tutorial\",\"description\":\"Learn how to build deep learning models with Pytorch\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/kindsonthegenius.com\\\/pytorch\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/kindsonthegenius.com\\\/pytorch\\\/#\\\/schema\\\/person\\\/2b1e3e1f9e5335a8493d437c3c835c66\",\"name\":\"Kindson Munonye\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/3b0f9291f0924a109c2372c345a86a4059732be59aad1f8795a216f0b96f855b?s=96&d=mm&r=g\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/3b0f9291f0924a109c2372c345a86a4059732be59aad1f8795a216f0b96f855b?s=96&d=mm&r=g\",\"contentUrl\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/3b0f9291f0924a109c2372c345a86a4059732be59aad1f8795a216f0b96f855b?s=96&d=mm&r=g\",\"caption\":\"Kindson Munonye\"},\"sameAs\":[\"http:\\\/\\\/www.kindsonthegeniuscom\"],\"url\":\"https:\\\/\\\/kindsonthegenius.com\\\/pytorch\\\/author\\\/kindsonthegenius\\\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"PyTorch Tutorial - Build the Model - PyTorch Simplified Tutorial","description":"In this PyTorch tutorial, we would build the NeuralNetwork and try to understand the Neural Network creation process","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/kindsonthegenius.com\/pytorch\/pytorch-tutorials-build-the-model\/","og_locale":"en_US","og_type":"article","og_title":"PyTorch Tutorial - Build the Model - PyTorch Simplified Tutorial","og_description":"In this PyTorch tutorial, we would build the NeuralNetwork and try to understand the Neural Network creation process","og_url":"https:\/\/kindsonthegenius.com\/pytorch\/pytorch-tutorials-build-the-model\/","og_site_name":"PyTorch Simplified Tutorial","article_published_time":"2024-10-11T12:51:54+00:00","article_modified_time":"2024-10-18T21:39:55+00:00","author":"Kindson Munonye","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Kindson Munonye","Est. reading time":"2 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/kindsonthegenius.com\/pytorch\/pytorch-tutorials-build-the-model\/#article","isPartOf":{"@id":"https:\/\/kindsonthegenius.com\/pytorch\/pytorch-tutorials-build-the-model\/"},"author":{"name":"Kindson Munonye","@id":"https:\/\/kindsonthegenius.com\/pytorch\/#\/schema\/person\/2b1e3e1f9e5335a8493d437c3c835c66"},"headline":"PyTorch Tutorial &#8211; Build the Model","datePublished":"2024-10-11T12:51:54+00:00","dateModified":"2024-10-18T21:39:55+00:00","mainEntityOfPage":{"@id":"https:\/\/kindsonthegenius.com\/pytorch\/pytorch-tutorials-build-the-model\/"},"wordCount":260,"commentCount":0,"articleSection":["PyTorch Tutorial"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/kindsonthegenius.com\/pytorch\/pytorch-tutorials-build-the-model\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/kindsonthegenius.com\/pytorch\/pytorch-tutorials-build-the-model\/","url":"https:\/\/kindsonthegenius.com\/pytorch\/pytorch-tutorials-build-the-model\/","name":"PyTorch Tutorial - Build the Model - PyTorch Simplified Tutorial","isPartOf":{"@id":"https:\/\/kindsonthegenius.com\/pytorch\/#website"},"datePublished":"2024-10-11T12:51:54+00:00","dateModified":"2024-10-18T21:39:55+00:00","author":{"@id":"https:\/\/kindsonthegenius.com\/pytorch\/#\/schema\/person\/2b1e3e1f9e5335a8493d437c3c835c66"},"description":"In this PyTorch tutorial, we would build the NeuralNetwork and try to understand the Neural Network creation process","breadcrumb":{"@id":"https:\/\/kindsonthegenius.com\/pytorch\/pytorch-tutorials-build-the-model\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/kindsonthegenius.com\/pytorch\/pytorch-tutorials-build-the-model\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/kindsonthegenius.com\/pytorch\/pytorch-tutorials-build-the-model\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/kindsonthegenius.com\/pytorch\/"},{"@type":"ListItem","position":2,"name":"PyTorch Tutorial &#8211; Build the Model"}]},{"@type":"WebSite","@id":"https:\/\/kindsonthegenius.com\/pytorch\/#website","url":"https:\/\/kindsonthegenius.com\/pytorch\/","name":"PyTorch Simplified Tutorial","description":"Learn how to build deep learning models with Pytorch","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/kindsonthegenius.com\/pytorch\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/kindsonthegenius.com\/pytorch\/#\/schema\/person\/2b1e3e1f9e5335a8493d437c3c835c66","name":"Kindson Munonye","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/3b0f9291f0924a109c2372c345a86a4059732be59aad1f8795a216f0b96f855b?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/3b0f9291f0924a109c2372c345a86a4059732be59aad1f8795a216f0b96f855b?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/3b0f9291f0924a109c2372c345a86a4059732be59aad1f8795a216f0b96f855b?s=96&d=mm&r=g","caption":"Kindson Munonye"},"sameAs":["http:\/\/www.kindsonthegeniuscom"],"url":"https:\/\/kindsonthegenius.com\/pytorch\/author\/kindsonthegenius\/"}]}},"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/kindsonthegenius.com\/pytorch\/wp-json\/wp\/v2\/posts\/22","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/kindsonthegenius.com\/pytorch\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/kindsonthegenius.com\/pytorch\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/kindsonthegenius.com\/pytorch\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/kindsonthegenius.com\/pytorch\/wp-json\/wp\/v2\/comments?post=22"}],"version-history":[{"count":5,"href":"https:\/\/kindsonthegenius.com\/pytorch\/wp-json\/wp\/v2\/posts\/22\/revisions"}],"predecessor-version":[{"id":39,"href":"https:\/\/kindsonthegenius.com\/pytorch\/wp-json\/wp\/v2\/posts\/22\/revisions\/39"}],"wp:attachment":[{"href":"https:\/\/kindsonthegenius.com\/pytorch\/wp-json\/wp\/v2\/media?parent=22"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/kindsonthegenius.com\/pytorch\/wp-json\/wp\/v2\/categories?post=22"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/kindsonthegenius.com\/pytorch\/wp-json\/wp\/v2\/tags?post=22"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}