{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "Ivo Bernardo",
  "title_listed": "PyTorch Introduction - Training a Computer Vision Algorithm",
  "keywords": "",
  "domain": "图像处理",
  "content_type": "深度技术解析",
  "is_paid_flag": "否",
  "url": "https://towardsdatascience.com/pytorch-introduction-training-a-computer-vision-algorithm-c17ed96e64d5/",
  "publish_date": "2024-05-31",
  "corpus_stage": "",
  "notes": "",
  "id": "03f263e77ad7",
  "collected_at": "2026-10-02T05:44:43",
  "title": "PyTorch Introduction - Training a Computer Vision Algorithm | Towards Data Science",
  "body_markdown": "![Revisit consent button](../images/body-df29beacd7496220cc94.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](../images/body-2159bb67f3de8ad870eb.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\n# PyTorch Introduction - Training a Computer Vision Algorithm\nIn this post of the PyTorch Introduction, we'll learn how to train a computer vision model using a Convolutional Neural Network with...\n[Ivo Bernardo](https://towardsdatascience.com/author/ivopbernardo/)\nMay 30, 202410 min read\n### In this post, we'll learn how to train a computer vision model using a convolutional Neural Network in PyTorch\n![Self-Driving Cars are mostly Powered by Computer Vision Algorithms - Image generated by AI in Microsoft Designer](../images/000.png)\nSelf-Driving Cars are mostly Powered by Computer Vision Algorithms - Image generated by AI in Microsoft Designer\n _PyTorch_ is currently one of the hottest libraries in the Deep Learning field. Used by thousand of developers around the world, the library gained prominence since the release of _ChatGPT_ and the introduction of deep learning into mainstream news headlines.\nWith its capabilities of efficiently training deep learning models (with GPU-ready features), it has become a machine learning engineer and data scientist's best friend when it comes to train complex neural network algorithms.\nSo far, in this _PyTorch_ series, we've covered several fundamentals that gave us the foundations to work with this library from scratch. For example:\nLearn this step by step with the interactive [AI Engineer](https://roadmap.sh/ai-engineer), [AI and Data Scientist](https://roadmap.sh/ai-data-scientist) and [Machine Learning](https://roadmap.sh/machine-learning) roadmaps.\n  * [We've learned the basics about tensors](https://towardsdatascience.com/pytorch-introduction-tensors-and-tensor-calculations-412ff818bd5b?sk=2cf4d44549664fc647baa3455e9d78e8);\n  * We understood how to create our first linear model (regression) using _PyTorch_.\n  * [We've learned how to work with non-linear activation functions and how to solve non-linear problems.](https://towardsdatascience.com/pytorch-introduction-enter-nonlinear-functions-4dd893845592)\n  * [We've seen how to use custom data in the context of the library.](https://medium.com/@ivopbernardo/pytorch-introduction-using-custom-data-4c70940d5358?sk=be995a685a4f573aea64c4491283ab32)\n\n\nIn this blog post, we are finally going to bring out the big guns and train our first computer vision algorithm. Alongside, we'll also get to know convolutional neural networks (CNNs), a famous set of architectures tailored for training computer vision models. Although we'll use a simple dataset here (making it accessible for anyone to run this code on their computer), the principles we'll see can be applied to other image classification algorithms.\nLet's start!\n* * *\n## Loading and Preparing the Data\nAs a way for everyone to be able to run this pipeline without the need for a GPU, we'll keep it simple and use the ever-present _MNIST_ dataset.\nThis dataset consists of handwritten digits and is available in _torchvision_ by running the following code:\npython\n\n```\nimport torchvision\nfrom torchvision.transforms import transforms\n\ntransform = transforms.Compose([\n    transforms.ToTensor(),\n    transforms.Normalize((0.5,), (0.5,))\n])\n\n# Load training and test datasets\ntrain_dataset = torchvision.datasets.MNIST(root='./data', train=True, download=True, transform=transform)\ntest_dataset = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=transform)\n```\n\n_Note: I'll add the imports we need during the code for visualization purposes, but the recommendation is that you always put them on top of your code_\n_torchvision.datasets_ also has another cool feature: we can immediately add a _transform_ that will be applied directly to images. In our case, our _transform_ pipeline will:\n  * Transform our data to tensor;\n  * Normalize the data;\n\n\nAlthough not very important for this grayscale dataset (as it only contains one channel of color) normalization will definitely help the gradient descent process and prevent exploding or vanishing gradients during the training of our models.\nWith our datasets in memory, it's time to see what our tensors contain! Let's take a look at the first one:\n![First Tensor of MNIST dataset - Image by Author](../images/001.png)\nFirst Tensor of MNIST dataset - Image by Author\nErrr.. ok, hard to visualize! let's see the shape of the tensor:\n![](../images/body-91168fbe57cb83c89b10.png)\nWe have a _28 x 28_ tensor of 1 channel. Maybe it's better to visualize our tensor in image format! Let's do that:\njavascript\n\n```\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nimage, label = train_dataset[0]\nimage = np.transpose(image, (1, 2, 0))\nplt.figure(figsize=(4, 4))\nplt.imshow(image)\nplt.title(label);\n```\n\n![Number 5, MNIST Dataset - Image by Author](../images/002.png)\nNumber 5, MNIST Dataset - Image by Author\nWe have the number 5 in the first row! Let's see another tensor in the dataset:\nmakefile\n\n```\nimage, label = train_dataset[120]\nimage = np.transpose(image, (1, 2, 0))\nplt.figure(figsize=(4, 4))\nplt.imshow(image)\nplt.title(label);\n```\n\n![Number 2 on MNIST Dataset - Image by Author](../images/003.png)\nNumber 2 on MNIST Dataset - Image by Author\nNumber 2!\nNow, our goal is to classify these numbers with the correct digit. Basically, our algorithm will have to check, based on these tensors, how to classify the number on the image.\nAs usual, in _pytorch_ , we need to use batches to feed the data to our neural network - if we need it, `torch` has it!\nkotlin\n\n```\nimport torch\n\ntrain_loader = torch.utils.data.DataLoader(train_dataset, batch_size=30, shuffle=True)\ntest_loader = torch.utils.data.DataLoader(test_dataset, batch_size=30)\n```\n\nWe're using 30 examples on each _batch_. This will help us train our neural network, next.\nWith our data in-place, let's create our model!\n* * *\n## Creating a Standard Neural Network Model\nBefore training our model, let's see the classes that our model will need to classify:\nmakefile\n\n```\nclass_names = train_dataset.classes\nclass_names\n```\n\n![Classes on the MNIST Dataset](../images/004.png)\nClasses on the MNIST Dataset\nSo our first algorithm will be super simple - a single hidden layer with ReLU activation. If this sentence sounds odd to you, consider visiting the other blog posts of this series, which are linked in the introduction!\npython\n\n```\nclass MNIST_NN(nn.Module):\n    def __init__(self, input_shape: int, \n                 hidden_units: int, \n                 output_shape: int):\n        super().__init__()\n\n        # Create a hidden layer with non-linearities\n        self.layer_stack = nn.Sequential(\n            nn.Flatten(),\n            nn.Linear(in_features=input_shape, out_features=hidden_units),\n            nn.ReLU(),\n            nn.Linear(in_features=hidden_units, out_features=output_shape),\n            nn.ReLU()\n        )\n\n    def forward(self, x: torch.Tensor):\n        return self.layer_stack(x)\n```\n\nWe'll use 150 units in our hidden layer:\nini\n\n```\nmodel_non_linear = MNIST_NN(input_shape=28*28,\n hidden_units=150,\n output_shape=len(class_names))\n```\n\nAs a loss function, we'll use CrossEntropy (suitable for classification problems) and we will use stochastic gradient descent optimizer (with 0.01 learning rate):\nini\n\n```\nloss_function = nn.CrossEntropyLoss()\noptimizer = torch.optim.SGD(params=model_1.parameters(),\n lr=0.01)\n```\n\nTime to define our `train` and `test` steps next:\nscss\n\n```\ndef train_step(model: torch.nn.Module,\n               data_loader: torch.utils.data.DataLoader,\n               loss_fn: torch.nn.Module,\n               optimizer: torch.optim.Optimizer,\n               accuracy_fn):\n\n    # Zero loss and acc\n    train_loss, train_acc = 0, 0\n\n    model.train()\n\n    for batch, (X, y) in enumerate(data_loader):\n\n        y_pred = model(X)\n        loss = loss_fn(y_pred, y)\n        train_loss += loss.item()\n        train_acc += accuracy_fn(y_true=y,\n                                 y_pred=y_pred.argmax(dim=1))\n\n        optimizer.zero_grad()\n        loss.backward()\n        optimizer.step()\n\n    train_loss /= len(data_loader)\n    train_acc /= len(data_loader)\n    print(f\"Train loss: {train_loss:.2f} | Train accuracy: {train_acc:.2f}%\")\n\n    return train_loss\n\ndef test_step(data_loader: torch.utils.data.DataLoader,\n              model: torch.nn.Module,\n              loss_fn: torch.nn.Module,\n              accuracy_fn):\n    test_loss, test_acc = 0, 0\n    model.eval() \n\n    with torch.no_grad(): \n        for X, y in data_loader:\n            test_pred = model(X)\n            test_loss += loss_fn(test_pred, y).item() \n            test_acc += accuracy_fn(y_true=y,\n                                    y_pred=test_pred.argmax(dim=1))\n\n        test_loss /= len(data_loader)\n        test_acc /= len(data_loader)\n        print(f\"Test loss: {test_loss:.5f} | Test accuracy: {test_acc:.2f}%n\")\n\n        return test_loss\n```\n\nThese steps have been approached in our [Training a Linear Model](https://towardsdatascience.com/pytorch-introduction-building-your-first-linear-model-d868a8681a41) blog post. Feel free to revisit it if you are finding this difficult to grasp!\nIn a nutshell, we are creating the training and step processes that will help our neural network perform back-propagation.\nAlright, everything is in its place. Time to train our feed-forward NN model:\npython\n\n```\nloss_hist = {}\n\nloss_hist['train'] = {}\nloss_hist['test'] = {}\n\nepochs = 10\nfor epoch in tqdm(range(epochs)):\n    print(f\"Epoch: {epoch}n---------\")\n    train_loss = train_step(data_loader=train_loader,\n        model=model_non_linear,\n        loss_fn=loss_function,\n        optimizer=optimizer,\n        accuracy_fn=accuracy_fn\n    )\n\n    loss_hist['train'][epoch] = train_loss\n\n    test_loss = test_step(data_loader=test_loader,\n        model=model_non_linear,\n        loss_fn=loss_function,\n        accuracy_fn=accuracy_fn\n    )\n\n    loss_hist['test'][epoch] = test_loss\n```\n\nWe'll train it for 10 epochs. Remember that a training epoch is a complete pass on the data, so our neural network will see each example 10 times. After a while (depending on your system's resources), the neural network should finish the training process:\n![Train and Test Loss Evolution - Image by Author\\)](../images/005.png)\nTrain and Test Loss Evolution - Image by Author)\nWe could probably continue to train our neural network for a while as it seems that the loss still had some points room for further improvement past 10 epochs.\nIn terms of accuracy, let's see the status of the accuracy and loss in the last epoch:\n![Train and Test Accuracy on last epoch - Image by Author](../images/006.png)\nTrain and Test Accuracy on last epoch - Image by Author\nCool, around 87% accuracy and our model isn't showing signs of overfit!\nFinally, let's pass some handwritten images through the algorithm and see how it's performing in the classification of digits. For that, we'll use a custom `show_predict_digit` function:\npython\n\n```\ndef show_predict_digit(model, dataset, index):\n    image_tensor = dataset.data[index].unsqueeze(0).unsqueeze(0).to(torch.float32)\n    plt.figure(figsize=(4, 4))\n    plt.imshow(image_tensor.squeeze(0).squeeze(0))\n\n    with torch.no_grad():\n        output = model(image_tensor)\n\n    return torch.argmax(output)\n```\n\nStarting with the digit on index 0 in our test set:\npython\n\n```\nshow_predict_digit(model_non_linear,\n test_dataset,\n 0)\n```\n\n![Prediction of Digit &quot;7&quot; using our model - image by author](../images/007.png)\nPrediction of Digit \"7\" using our model - image by author\nRight above the image, do you see \"tensor(7)\"? This is the output from our neural network. In a perfect world, this would match the digit we are seeing on the screen, everytime.\nIn this case, we got this digit correctly! Our neural network is predicting the digit 7. Let's see another example:\n![Prediction of Digit &quot;0&quot; using our model - image by author](../images/008.png)\nPrediction of Digit \"0\" using our model - image by author\nToo bad! :-( As our image highlights the circle on the digit \"9\", our neural network is incorrectly classifying the digit as \"0\". There's certainly still some room for improvement in the algorithm!\nIt's expected that feed-forward neural networks exhibit this behavior, particularly in problems that suffer from large dimensionality (such as image classification that rely on pixel-by-pixel features).\nIn the next part of this blog post, we'll try to solve this issue by fitting our first convolutional neural network, **a specific type of neural network that is tailored to deal with computer vision problems.**\n* * *\n## Training a Convolutional Neural Network\nLet's now build a new neural network model using `pytorch`— in this case, we're going to use a convolutional neural network (CNN).\nThese types of neural network architectures are tailored for vision algorithms and to work with high dimensionality data. When it comes to image data, they focus on specific features within the image with its architecture being loosely inspired by the human eye.\nSome of the most famous operations of a CNN are pooling, sampling and flatten operations - they help our algorithm converge faster and with less error. Explaining convolutional neural networks is outside of the scope of this post, but you can check this awesome [blog post on TDS](https://towardsdatascience.com/convolutional-neural-networks-explained-9cc5188c4939) and this great [visualizer](https://poloclub.github.io/cnn-explainer/) on how data passes through the layers of a CNN.\npython\n\n```\nclass SimpleCNN(nn.Module):\n    def __init__(self):\n        super(SimpleCNN, self).__init__()\n        self.conv1 = nn.Conv2d(in_channels=1, out_channels=32, \n                               kernel_size=3, padding=1)\n        self.conv2 = nn.Conv2d(32, 64, kernel_size=3, padding=1)\n        self.pool = nn.MaxPool2d(kernel_size=2, stride=2)\n        self.fc1 = nn.Linear(64 * 7 * 7, 128)\n        self.fc2 = nn.Linear(128, 10)\n        self.dropout = nn.Dropout(0.5) \n        self.batch_norm1 = nn.BatchNorm2d(32)\n        self.batch_norm2 = nn.BatchNorm2d(64)\n\n    def forward(self, x):\n        x = self.pool(F.relu(self.batch_norm1(self.conv1(x))))\n        x = self.pool(F.relu(self.batch_norm2(self.conv2(x))))\n        x = torch.flatten(x, 1)\n        x = F.relu(self.fc1(x))\n        x = self.dropout(x)\n        x = self.fc2(x)\n        return x\n```\n\nIn our convolutional neural network, we have the following architecture:\n  * A normalized convolutional layer with a 3 by 3 kernel and 32 output channels.\n  * A pooling operation with RELU activation, processed in `self.pool(F.relu(self.batch_norm1(self.conv1(x))))`\n  * A second normalized convolutional layer with a 3 by 3 kernel.\n  * A pooling operation with RELU activation, processed in `self.pool(F.relu(self.batch_norm2(self.conv2(x))))`\n  * A flattening layer - `torch.flatten(x,1)`\n  * Finally, two fully connected layers with a dropout in-between to prevent overfit.\n\n\nTraining a CNN in `pytorch` is similar to training a typical feed-forward neural network:\nini\n\n```\nnet = SimpleCNN()\n\noptimizer = torch.optim.SGD(params=net.parameters(),\n                            lr=0.05)\n```\n\nIn this example, we'll be using stochastic gradient descent with `0.05`learning rate. We can rely on code we previously defined to train the network:\npython\n\n```\nloss_hist_cnn = {}\n\nloss_hist_cnn['train'] = {}\nloss_hist_cnn['test'] = {}\n\nepochs = 10\nfor epoch in tqdm(range(epochs)):\n    print(f\"Epoch: {epoch}n---------\")\n    loss_cnn = train_step(data_loader=train_loader,\n        model=net,\n        loss_fn=loss_function,\n        optimizer=optimizer,\n        accuracy_fn=accuracy_fn\n    )\n\n    loss_hist_cnn['train'][epoch] = loss_cnn\n\n    loss_cnn_test = test_step(data_loader=test_loader,\n        model=net,\n        loss_fn=loss_function,\n        accuracy_fn=accuracy_fn\n    )\n\n    loss_hist_cnn['test'][epoch] = loss_cnn_test\n```\n\nAfter our 10th epoch, these are the results of our accuracy and loss:\n![Train and Test Accuracy on last epoch of CNN— Image by Author](../images/009.png)\nTrain and Test Accuracy on last epoch of CNN— Image by Author\nCool! It seemed we improved our model's accuracy by a lot, by more than 10 percentage points. This is clearly outperforming the simple non-linear architecture.\nLet's confirm that by plotting the train and test loss curves:\n![Train and Test Loss Evolution - Image by Author](../images/010.png)\nTrain and Test Loss Evolution - Image by Author\nWe have the confirmation that loss is lower than the first experiment. But, we'll not celebrate yet! It's time for the litmus test: let's see how our model is classifying the _\"9\"_ digit that our first classifier was predicting incorrectly:\n![Prediction of Digit &quot;9&quot; using our CNN model - image by author](../images/011.png)\nPrediction of Digit \"9\" using our CNN model - image by author\nSo cool! We're now able to predict this digit correctly using a CNN. To wrap things up and out of curiosity, let's see another random example:\nscss\n\n```\nshow_predict_digit_cnn(net,\n                  test_dataset,\n                  15)\n```\n\n![Prediction of Digit &quot;5&quot; using our CNN model - image by author](../images/body-ca7b5d5302d2ffd1aa2c.png)\nPrediction of Digit \"5\" using our CNN model - image by author\nAnother example correct! Can you check more digits and see if you can find the rare cases where our CNN is falling?\n* * *\nAnd that's a wrap for this post! Thank you for reading until the end and I hope that these examples helped you understand how to train a convolutional neural network using `pytorch` . It was also our first time dealing with these types of layers within the framework and it's really cool to see how `torch` is built similar to lego bricks! As soon as you understand how the layers work, mixing and matching them will give you extraordinary abilities when it comes to building deep learning models.\nIn summary, here's what we've done in this blog post:\n  * Trained our first computer vision model\n  * Fitted a typical feed-forward neural network on the MNIST dataset\n  * Fitted a CNN on the MNIST dataset\n  * Touched lightly upon the concept of CNNs and got to know conv, flatten, and pool layers.\n\n\nHope you've enjoyed this and see you on the next PyTorch post!\nYou can check the first PyTorch blog posts from this series [[[here](https://github.com/DareData/lp-pytorch-fundamentals)](https://towardsdatascience.com/pytorch-introduction-building-your-first-linear-model-d868a8681a41)](https://towardsdatascience.com/pytorch-introduction-tensors-and-tensor-calculations-412ff818bd5b?sk=2cf4d44549664fc647baa3455e9d78e8) and here. I also recommend that you visit [PyTorch Zero to Mastery Course](https://www.learnpytorch.io/01_pytorch_workflow/), an amazing free resource that inspired the methodology behind this post or go through our DareData's pytorch learning pod, available here.\nFeel free to drop by on my newly created youTube channel - the [Data Journey](https://www.youtube.com/@TheDataJourney42) where I'll be adding content on data Science and machine learning in the next couple of months and looking forward to seeing you there!\n[The dataset used in this post is under the MIT license.](https://huggingface.co/datasets/mnist)\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](../images/body-6f351be10c9e83aa9f9d.jpeg)\nWritten By\n## [Ivo Bernardo](https://towardsdatascience.com/author/ivopbernardo/)\n[See all from Ivo Bernardo](https://towardsdatascience.com/author/ivopbernardo/)\n[Artificial Intelligence](https://towardsdatascience.com/tag/artificial-intelligence/)[Computer Vision](https://towardsdatascience.com/tag/computer-vision/)[Data Science](https://towardsdatascience.com/tag/data-science/)[Deep Learning](https://towardsdatascience.com/tag/deep-learning/)[Machine Learning](https://towardsdatascience.com/tag/machine-learning/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fpytorch-introduction-training-a-computer-vision-algorithm-c17ed96e64d5%2F&title=PyTorch%20Introduction%20-%20Training%20a%20Computer%20Vision%20Algorithm)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fpytorch-introduction-training-a-computer-vision-algorithm-c17ed96e64d5%2F&title=PyTorch%20Introduction%20-%20Training%20a%20Computer%20Vision%20Algorithm)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fpytorch-introduction-training-a-computer-vision-algorithm-c17ed96e64d5%2F&text=PyTorch%20Introduction%20-%20Training%20a%20Computer%20Vision%20Algorithm)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](../images/012.jpeg)](https://towardsdatascience.com/3-bitter-lessons-i-wish-i-knew-earlier-as-a-big-data-engineer-e2956bcc7b29/)\n## [3 Bitter Lessons I Wish I Knew Earlier As a Big Data Engineer](https://towardsdatascience.com/3-bitter-lessons-i-wish-i-knew-earlier-as-a-big-data-engineer-e2956bcc7b29/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nThe Dos and Don'ts of data engineering\n[Nam Nguyen](https://towardsdatascience.com/author/namnguyenwrite/)\nAugust 6, 20216 min read\n  * [![](../images/013.jpeg)](https://towardsdatascience.com/multithreading-multiprocessing-python-180d0975ab29/)\n## [Multi-threading and Multi-processing in Python](https://towardsdatascience.com/multithreading-multiprocessing-python-180d0975ab29/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nA deep dive into multi-threading and multi-processing with Python and how they are related to concurrency and parallelism\n[Giorgos Myrianthous](https://towardsdatascience.com/author/gmyrianthous/)\nJanuary 21, 202210 min read\n  * [![](../images/014.jpg)](https://towardsdatascience.com/backpropagation-explained-for-beginners-part-1-building-the-intuition/)\n## [Backpropagation Explained for Beginners (Part 1): Building the Intuition](https://towardsdatascience.com/backpropagation-explained-for-beginners-part-1-building-the-intuition/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nLet's discover how neural networks learn, step by step\n[Nikhil Dasari](https://towardsdatascience.com/author/nikhil.dasari/)\nJuly 19, 20269 min read\n  * [![](../images/015.jpg)](https://towardsdatascience.com/from-monolith-to-contract-driven-data-mesh/)\n## [From Monolith to Contract-Driven Data Mesh](https://towardsdatascience.com/from-monolith-to-contract-driven-data-mesh/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nA pragmatic journey using website analytics as a real-world example\n[Corné Potgieter](https://towardsdatascience.com/author/corne-potgieter/)\nFebruary 20, 202611 min read\n  * [![](../images/016.png)](https://towardsdatascience.com/reinforcement-learning-part-3-monte-carlo-methods-7ce2828a1fdb/)\n## [Reinforcement Learning, Part 3: Monte Carlo Methods](https://towardsdatascience.com/reinforcement-learning-part-3-monte-carlo-methods-7ce2828a1fdb/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nFrom casinos to AI: unveiling the power of Monte Carlo methods in complex environments\n[Slava Efimov](https://towardsdatascience.com/author/slavahead/)\nMay 23, 202413 min read\n  * [![](../images/017.jpeg)](https://towardsdatascience.com/teaching-data-science-at-general-assembly-week-5-84b19e6f5697/)\n## [Teaching Data Science at General Assembly: Week 5](https://towardsdatascience.com/teaching-data-science-at-general-assembly-week-5-84b19e6f5697/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nThis week students are starting to think about what awesome data product they want to build for their capstone project. Also GA hosted a...\n[Alexander Barriga](https://towardsdatascience.com/author/databeast/)\nMarch 8, 20174 min read\n  * [![](../images/018.png)](https://towardsdatascience.com/4-more-little-known-nlp-libraries-that-are-hidden-gems-e77a71d1bc57/)\n## [4 More Little-Known NLP Libraries That Are Hidden Gems](https://towardsdatascience.com/4-more-little-known-nlp-libraries-that-are-hidden-gems-e77a71d1bc57/)\n[NLP](https://towardsdatascience.com/category/artificial-intelligence/nlp/)\nWith code examples and explanations.\n[Michael Markin](https://towardsdatascience.com/author/michaelmarkin/)\nSeptember 15, 20226 min read\n  * [![](../images/019.png)](https://towardsdatascience.com/identifying-protein-ligand-interactions-with-colab-2cfd26ed469a/)\n## [Identifying Protein-Ligand Interactions with Colab](https://towardsdatascience.com/identifying-protein-ligand-interactions-with-colab-2cfd26ed469a/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nSetting up Autodock Vina\n[Jose Manuel Napoles-Duarte](https://towardsdatascience.com/author/jnapoles/)\nMay 3, 20208 min read\n  * [![](../images/020.jpeg)](https://towardsdatascience.com/countif-in-5-languages-vba-sql-python-m-query-dax-powerbi-639d3d7c6c7f/)\n## [COUNTIF in 5 languages (VBA/SQL/PYTHON/M query/DAX powerBI)](https://towardsdatascience.com/countif-in-5-languages-vba-sql-python-m-query-dax-powerbi-639d3d7c6c7f/)\n[Programming](https://towardsdatascience.com/category/programming/)\nHow to make your favorite Excel feature in another analytic language (VBA/SQL/PYTHON/M query/DAX powerBI)\n[Aymen](https://towardsdatascience.com/author/aymenbaraket/)\nJanuary 10, 20216 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500) How Relevance Models Foreshadowed Transformers for NLP ](https://towardsdatascience.com/how-relevance-models-foreshadowed-transformers-for-nlp/ \"How Relevance Models Foreshadowed Transformers for NLP\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ \"Does Your Company Have a Data Strategy?\")\n\n\n",
  "metadata": {
    "title": "PyTorch Introduction - Training a Computer Vision Algorithm | Towards Data Science",
    "description": "In this post of the PyTorch Introduction, we'll learn how to train a computer vision model using a Convolutional Neural Network with...",
    "keywords": null,
    "author": "Ivo Bernardo",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "PyTorch Introduction - Training a Computer Vision Algorithm",
    "og:description": "In this post of the PyTorch Introduction, we'll learn how to train a computer vision model using a Convolutional Neural Network with...",
    "og:url": "https://towardsdatascience.com/pytorch-introduction-training-a-computer-vision-algorithm-c17ed96e64d5/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/1eH7HX8J0tDLE8m3gaA-Mug.png",
    "og:image:width": "1024",
    "og:image:height": "1024",
    "og:image:type": "image/png",
    "twitter:card": "summary_large_image",
    "twitter:site": "@TDataScience",
    "twitter:creator": "@TDataScience",
    "twitter:label1": "Written by",
    "twitter:data1": "Ivo Bernardo",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "10 min read",
    "article:published_time": "2024-05-30T20:24:12.000Z",
    "article:modified_time": "2024-05-30T20:24:12.000Z",
    "article:author": "https://towardsdatascience.com/author/ivopbernardo/"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 200,
    "error": ""
  },
  "code_blocks": [
    {
      "language": "txt",
      "file": "attachments/03f263e77ad7/code/block_000.txt",
      "chars": 417
    },
    {
      "language": "txt",
      "file": "attachments/03f263e77ad7/code/block_001.txt",
      "chars": 186
    },
    {
      "language": "txt",
      "file": "attachments/03f263e77ad7/code/block_002.txt",
      "chars": 136
    },
    {
      "language": "txt",
      "file": "attachments/03f263e77ad7/code/block_003.txt",
      "chars": 172
    },
    {
      "language": "txt",
      "file": "attachments/03f263e77ad7/code/block_004.txt",
      "chars": 48
    },
    {
      "language": "txt",
      "file": "attachments/03f263e77ad7/code/block_005.txt",
      "chars": 574
    },
    {
      "language": "txt",
      "file": "attachments/03f263e77ad7/code/block_006.txt",
      "chars": 98
    },
    {
      "language": "txt",
      "file": "attachments/03f263e77ad7/code/block_007.txt",
      "chars": 105
    },
    {
      "language": "txt",
      "file": "attachments/03f263e77ad7/code/block_008.txt",
      "chars": 1449
    },
    {
      "language": "txt",
      "file": "attachments/03f263e77ad7/code/block_009.txt",
      "chars": 572
    },
    {
      "language": "txt",
      "file": "attachments/03f263e77ad7/code/block_010.txt",
      "chars": 309
    },
    {
      "language": "txt",
      "file": "attachments/03f263e77ad7/code/block_011.txt",
      "chars": 56
    },
    {
      "language": "txt",
      "file": "attachments/03f263e77ad7/code/block_012.txt",
      "chars": 840
    },
    {
      "language": "txt",
      "file": "attachments/03f263e77ad7/code/block_013.txt",
      "chars": 109
    },
    {
      "language": "txt",
      "file": "attachments/03f263e77ad7/code/block_014.txt",
      "chars": 570
    },
    {
      "language": "txt",
      "file": "attachments/03f263e77ad7/code/block_015.txt",
      "chars": 82
    }
  ],
  "images": [
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:40:54Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:40:54Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:40:54Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:40:54Z"
    }
  ],
  "audio": [],
  "videos": [
    {
      "url": "https://www.youtube.com/@TheDataJourney42",
      "kind": "channel_reference",
      "status": "reference_only"
    },
    {
      "url": "https://www.youtube.com/c/TowardsDataScience",
      "kind": "channel_reference",
      "status": "reference_only"
    }
  ],
  "links": [
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/latest/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/editors-pick/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/the-variable/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/shipai/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/submissions/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/ivopbernardo/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/pytorch-introduction-tensors-and-tensor-calculations-412ff818bd5b?sk=2cf4d44549664fc647baa3455e9d78e8"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/pytorch-introduction-enter-nonlinear-functions-4dd893845592"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/pytorch-introduction-building-your-first-linear-model-d868a8681a41"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/convolutional-neural-networks-explained-9cc5188c4939"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/artificial-intelligence/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/computer-vision/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/data-science/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/deep-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/machine-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/3-bitter-lessons-i-wish-i-knew-earlier-as-a-big-data-engineer-e2956bcc7b29/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/data-science/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/namnguyenwrite/"
    },
    {
      "type": "external",
      "href": "https://write.insightmediagroup.io"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/company/towards-data-science/"
    },
    {
      "type": "external",
      "href": "https://x.com/TDataScience"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/ai-engineer"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/ai-data-scientist"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/machine-learning"
    },
    {
      "type": "external",
      "href": "https://medium.com/@ivopbernardo/pytorch-introduction-using-custom-data-4c70940d5358?sk=be995a685a4f573aea64c4491283ab32"
    },
    {
      "type": "external",
      "href": "https://poloclub.github.io/cnn-explainer/"
    },
    {
      "type": "external",
      "href": "https://www.learnpytorch.io/01_pytorch_workflow/"
    },
    {
      "type": "external",
      "href": "https://www.youtube.com/@TheDataJourney42"
    },
    {
      "type": "external",
      "href": "https://huggingface.co/datasets/mnist"
    },
    {
      "type": "external",
      "href": "https://www.facebook.com/sharer/sharer.php?title=PyTorch+Introduction+-+Training+a+Computer+Vision+Algorithm&u=https%3A%2F%2Ftowardsdatascience.com%2Fpytorch-introduction-training-a-computer-vision-algorithm-c17ed96e64d5%2F"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/shareArticle?mini=true&title=PyTorch+Introduction+-+Training+a+Computer+Vision+Algorithm&url=https%3A%2F%2Ftowardsdatascience.com%2Fpytorch-introduction-training-a-computer-vision-algorithm-c17ed96e64d5%2F"
    },
    {
      "type": "external",
      "href": "https://x.com/share?text=PyTorch+Introduction+-+Training+a+Computer+Vision+Algorithm&url=https%3A%2F%2Ftowardsdatascience.com%2Fpytorch-introduction-training-a-computer-vision-algorithm-c17ed96e64d5%2F"
    },
    {
      "type": "external",
      "href": "https://www.youtube.com/c/TowardsDataScience"
    },
    {
      "type": "external",
      "href": "https://www.threads.net/@towardsdatascience"
    },
    {
      "type": "external",
      "href": "https://bsky.app/profile/towardsdatascience.com"
    },
    {
      "type": "external",
      "href": "https://thenewstack.io"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh"
    },
    {
      "type": "external",
      "href": "https://insightmediagroup.io/creator-network"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-20T17:24:47Z",
  "source_url": "https://towardsdatascience.com/pytorch-introduction-training-a-computer-vision-algorithm-c17ed96e64d5/",
  "delivery_status": "unverified",
  "discovery_status": "http_403",
  "missing_reason": "源页面未重新核验:http_403；已按保留正文补采图片",
  "repair_error": "",
  "actual_video_files": [],
  "expected_saved_body_images": 4,
  "image_discovery": "saved_markdown",
  "source_body_markdown": "![Revisit consent button](https://cdn-cookieyes.com/assets/images/revisit.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](https://cdn-cookieyes.com/assets/images/close.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\n# PyTorch Introduction - Training a Computer Vision Algorithm\nIn this post of the PyTorch Introduction, we'll learn how to train a computer vision model using a Convolutional Neural Network with...\n[Ivo Bernardo](https://towardsdatascience.com/author/ivopbernardo/)\nMay 30, 202410 min read\n### In this post, we'll learn how to train a computer vision model using a convolutional Neural Network in PyTorch\n![Self-Driving Cars are mostly Powered by Computer Vision Algorithms - Image generated by AI in Microsoft Designer](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/1eH7HX8J0tDLE8m3gaA-Mug.png)\nSelf-Driving Cars are mostly Powered by Computer Vision Algorithms - Image generated by AI in Microsoft Designer\n _PyTorch_ is currently one of the hottest libraries in the Deep Learning field. Used by thousand of developers around the world, the library gained prominence since the release of _ChatGPT_ and the introduction of deep learning into mainstream news headlines.\nWith its capabilities of efficiently training deep learning models (with GPU-ready features), it has become a machine learning engineer and data scientist's best friend when it comes to train complex neural network algorithms.\nSo far, in this _PyTorch_ series, we've covered several fundamentals that gave us the foundations to work with this library from scratch. For example:\nLearn this step by step with the interactive [AI Engineer](https://roadmap.sh/ai-engineer), [AI and Data Scientist](https://roadmap.sh/ai-data-scientist) and [Machine Learning](https://roadmap.sh/machine-learning) roadmaps.\n  * [We've learned the basics about tensors](https://towardsdatascience.com/pytorch-introduction-tensors-and-tensor-calculations-412ff818bd5b?sk=2cf4d44549664fc647baa3455e9d78e8);\n  * We understood how to create our first linear model (regression) using _PyTorch_.\n  * [We've learned how to work with non-linear activation functions and how to solve non-linear problems.](https://towardsdatascience.com/pytorch-introduction-enter-nonlinear-functions-4dd893845592)\n  * [We've seen how to use custom data in the context of the library.](https://medium.com/@ivopbernardo/pytorch-introduction-using-custom-data-4c70940d5358?sk=be995a685a4f573aea64c4491283ab32)\n\n\nIn this blog post, we are finally going to bring out the big guns and train our first computer vision algorithm. Alongside, we'll also get to know convolutional neural networks (CNNs), a famous set of architectures tailored for training computer vision models. Although we'll use a simple dataset here (making it accessible for anyone to run this code on their computer), the principles we'll see can be applied to other image classification algorithms.\nLet's start!\n* * *\n## Loading and Preparing the Data\nAs a way for everyone to be able to run this pipeline without the need for a GPU, we'll keep it simple and use the ever-present _MNIST_ dataset.\nThis dataset consists of handwritten digits and is available in _torchvision_ by running the following code:\npython\n\n```\nimport torchvision\nfrom torchvision.transforms import transforms\n\ntransform = transforms.Compose([\n    transforms.ToTensor(),\n    transforms.Normalize((0.5,), (0.5,))\n])\n\n# Load training and test datasets\ntrain_dataset = torchvision.datasets.MNIST(root='./data', train=True, download=True, transform=transform)\ntest_dataset = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=transform)\n```\n\n_Note: I'll add the imports we need during the code for visualization purposes, but the recommendation is that you always put them on top of your code_\n_torchvision.datasets_ also has another cool feature: we can immediately add a _transform_ that will be applied directly to images. In our case, our _transform_ pipeline will:\n  * Transform our data to tensor;\n  * Normalize the data;\n\n\nAlthough not very important for this grayscale dataset (as it only contains one channel of color) normalization will definitely help the gradient descent process and prevent exploding or vanishing gradients during the training of our models.\nWith our datasets in memory, it's time to see what our tensors contain! Let's take a look at the first one:\n![First Tensor of MNIST dataset - Image by Author](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/1KdLwt5Fec6tVPBlDENhDaQ.png)\nFirst Tensor of MNIST dataset - Image by Author\nErrr.. ok, hard to visualize! let's see the shape of the tensor:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/1oSNjW7_DYqMTWzByHSv4qw.png)\nWe have a _28 x 28_ tensor of 1 channel. Maybe it's better to visualize our tensor in image format! Let's do that:\njavascript\n\n```\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nimage, label = train_dataset[0]\nimage = np.transpose(image, (1, 2, 0))\nplt.figure(figsize=(4, 4))\nplt.imshow(image)\nplt.title(label);\n```\n\n![Number 5, MNIST Dataset - Image by Author](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/1DDXEDcTL_tCmOzUs-u7K4w.png)\nNumber 5, MNIST Dataset - Image by Author\nWe have the number 5 in the first row! Let's see another tensor in the dataset:\nmakefile\n\n```\nimage, label = train_dataset[120]\nimage = np.transpose(image, (1, 2, 0))\nplt.figure(figsize=(4, 4))\nplt.imshow(image)\nplt.title(label);\n```\n\n![Number 2 on MNIST Dataset - Image by Author](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/1KlyMcTHrrrYAbR1sV6A04A.png)\nNumber 2 on MNIST Dataset - Image by Author\nNumber 2!\nNow, our goal is to classify these numbers with the correct digit. Basically, our algorithm will have to check, based on these tensors, how to classify the number on the image.\nAs usual, in _pytorch_ , we need to use batches to feed the data to our neural network - if we need it, `torch` has it!\nkotlin\n\n```\nimport torch\n\ntrain_loader = torch.utils.data.DataLoader(train_dataset, batch_size=30, shuffle=True)\ntest_loader = torch.utils.data.DataLoader(test_dataset, batch_size=30)\n```\n\nWe're using 30 examples on each _batch_. This will help us train our neural network, next.\nWith our data in-place, let's create our model!\n* * *\n## Creating a Standard Neural Network Model\nBefore training our model, let's see the classes that our model will need to classify:\nmakefile\n\n```\nclass_names = train_dataset.classes\nclass_names\n```\n\n![Classes on the MNIST Dataset](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/1PBRU-ulKeFbLrJjwjqzIZA.png)\nClasses on the MNIST Dataset\nSo our first algorithm will be super simple - a single hidden layer with ReLU activation. If this sentence sounds odd to you, consider visiting the other blog posts of this series, which are linked in the introduction!\npython\n\n```\nclass MNIST_NN(nn.Module):\n    def __init__(self, input_shape: int, \n                 hidden_units: int, \n                 output_shape: int):\n        super().__init__()\n\n        # Create a hidden layer with non-linearities\n        self.layer_stack = nn.Sequential(\n            nn.Flatten(),\n            nn.Linear(in_features=input_shape, out_features=hidden_units),\n            nn.ReLU(),\n            nn.Linear(in_features=hidden_units, out_features=output_shape),\n            nn.ReLU()\n        )\n\n    def forward(self, x: torch.Tensor):\n        return self.layer_stack(x)\n```\n\nWe'll use 150 units in our hidden layer:\nini\n\n```\nmodel_non_linear = MNIST_NN(input_shape=28*28,\n hidden_units=150,\n output_shape=len(class_names))\n```\n\nAs a loss function, we'll use CrossEntropy (suitable for classification problems) and we will use stochastic gradient descent optimizer (with 0.01 learning rate):\nini\n\n```\nloss_function = nn.CrossEntropyLoss()\noptimizer = torch.optim.SGD(params=model_1.parameters(),\n lr=0.01)\n```\n\nTime to define our `train` and `test` steps next:\nscss\n\n```\ndef train_step(model: torch.nn.Module,\n               data_loader: torch.utils.data.DataLoader,\n               loss_fn: torch.nn.Module,\n               optimizer: torch.optim.Optimizer,\n               accuracy_fn):\n\n    # Zero loss and acc\n    train_loss, train_acc = 0, 0\n\n    model.train()\n\n    for batch, (X, y) in enumerate(data_loader):\n\n        y_pred = model(X)\n        loss = loss_fn(y_pred, y)\n        train_loss += loss.item()\n        train_acc += accuracy_fn(y_true=y,\n                                 y_pred=y_pred.argmax(dim=1))\n\n        optimizer.zero_grad()\n        loss.backward()\n        optimizer.step()\n\n    train_loss /= len(data_loader)\n    train_acc /= len(data_loader)\n    print(f\"Train loss: {train_loss:.2f} | Train accuracy: {train_acc:.2f}%\")\n\n    return train_loss\n\ndef test_step(data_loader: torch.utils.data.DataLoader,\n              model: torch.nn.Module,\n              loss_fn: torch.nn.Module,\n              accuracy_fn):\n    test_loss, test_acc = 0, 0\n    model.eval() \n\n    with torch.no_grad(): \n        for X, y in data_loader:\n            test_pred = model(X)\n            test_loss += loss_fn(test_pred, y).item() \n            test_acc += accuracy_fn(y_true=y,\n                                    y_pred=test_pred.argmax(dim=1))\n\n        test_loss /= len(data_loader)\n        test_acc /= len(data_loader)\n        print(f\"Test loss: {test_loss:.5f} | Test accuracy: {test_acc:.2f}%n\")\n\n        return test_loss\n```\n\nThese steps have been approached in our [Training a Linear Model](https://towardsdatascience.com/pytorch-introduction-building-your-first-linear-model-d868a8681a41) blog post. Feel free to revisit it if you are finding this difficult to grasp!\nIn a nutshell, we are creating the training and step processes that will help our neural network perform back-propagation.\nAlright, everything is in its place. Time to train our feed-forward NN model:\npython\n\n```\nloss_hist = {}\n\nloss_hist['train'] = {}\nloss_hist['test'] = {}\n\nepochs = 10\nfor epoch in tqdm(range(epochs)):\n    print(f\"Epoch: {epoch}n---------\")\n    train_loss = train_step(data_loader=train_loader,\n        model=model_non_linear,\n        loss_fn=loss_function,\n        optimizer=optimizer,\n        accuracy_fn=accuracy_fn\n    )\n\n    loss_hist['train'][epoch] = train_loss\n\n    test_loss = test_step(data_loader=test_loader,\n        model=model_non_linear,\n        loss_fn=loss_function,\n        accuracy_fn=accuracy_fn\n    )\n\n    loss_hist['test'][epoch] = test_loss\n```\n\nWe'll train it for 10 epochs. Remember that a training epoch is a complete pass on the data, so our neural network will see each example 10 times. After a while (depending on your system's resources), the neural network should finish the training process:\n![Train and Test Loss Evolution - Image by Author\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/1MN-Ifr1dKUCPBFvC3YbfGw.png)\nTrain and Test Loss Evolution - Image by Author)\nWe could probably continue to train our neural network for a while as it seems that the loss still had some points room for further improvement past 10 epochs.\nIn terms of accuracy, let's see the status of the accuracy and loss in the last epoch:\n![Train and Test Accuracy on last epoch - Image by Author](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/1C6_YI4NcgL-m3FXGh1yE7w.png)\nTrain and Test Accuracy on last epoch - Image by Author\nCool, around 87% accuracy and our model isn't showing signs of overfit!\nFinally, let's pass some handwritten images through the algorithm and see how it's performing in the classification of digits. For that, we'll use a custom `show_predict_digit` function:\npython\n\n```\ndef show_predict_digit(model, dataset, index):\n    image_tensor = dataset.data[index].unsqueeze(0).unsqueeze(0).to(torch.float32)\n    plt.figure(figsize=(4, 4))\n    plt.imshow(image_tensor.squeeze(0).squeeze(0))\n\n    with torch.no_grad():\n        output = model(image_tensor)\n\n    return torch.argmax(output)\n```\n\nStarting with the digit on index 0 in our test set:\npython\n\n```\nshow_predict_digit(model_non_linear,\n test_dataset,\n 0)\n```\n\n![Prediction of Digit &quot;7&quot; using our model - image by author](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/1Fp90nV2lMAfJYiUYVSz6pg.png)\nPrediction of Digit \"7\" using our model - image by author\nRight above the image, do you see \"tensor(7)\"? This is the output from our neural network. In a perfect world, this would match the digit we are seeing on the screen, everytime.\nIn this case, we got this digit correctly! Our neural network is predicting the digit 7. Let's see another example:\n![Prediction of Digit &quot;0&quot; using our model - image by author](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/1xuMURhPrIQuaFJncPqVdxQ.png)\nPrediction of Digit \"0\" using our model - image by author\nToo bad! :-( As our image highlights the circle on the digit \"9\", our neural network is incorrectly classifying the digit as \"0\". There's certainly still some room for improvement in the algorithm!\nIt's expected that feed-forward neural networks exhibit this behavior, particularly in problems that suffer from large dimensionality (such as image classification that rely on pixel-by-pixel features).\nIn the next part of this blog post, we'll try to solve this issue by fitting our first convolutional neural network, **a specific type of neural network that is tailored to deal with computer vision problems.**\n* * *\n## Training a Convolutional Neural Network\nLet's now build a new neural network model using `pytorch`— in this case, we're going to use a convolutional neural network (CNN).\nThese types of neural network architectures are tailored for vision algorithms and to work with high dimensionality data. When it comes to image data, they focus on specific features within the image with its architecture being loosely inspired by the human eye.\nSome of the most famous operations of a CNN are pooling, sampling and flatten operations - they help our algorithm converge faster and with less error. Explaining convolutional neural networks is outside of the scope of this post, but you can check this awesome [blog post on TDS](https://towardsdatascience.com/convolutional-neural-networks-explained-9cc5188c4939) and this great [visualizer](https://poloclub.github.io/cnn-explainer/) on how data passes through the layers of a CNN.\npython\n\n```\nclass SimpleCNN(nn.Module):\n    def __init__(self):\n        super(SimpleCNN, self).__init__()\n        self.conv1 = nn.Conv2d(in_channels=1, out_channels=32, \n                               kernel_size=3, padding=1)\n        self.conv2 = nn.Conv2d(32, 64, kernel_size=3, padding=1)\n        self.pool = nn.MaxPool2d(kernel_size=2, stride=2)\n        self.fc1 = nn.Linear(64 * 7 * 7, 128)\n        self.fc2 = nn.Linear(128, 10)\n        self.dropout = nn.Dropout(0.5) \n        self.batch_norm1 = nn.BatchNorm2d(32)\n        self.batch_norm2 = nn.BatchNorm2d(64)\n\n    def forward(self, x):\n        x = self.pool(F.relu(self.batch_norm1(self.conv1(x))))\n        x = self.pool(F.relu(self.batch_norm2(self.conv2(x))))\n        x = torch.flatten(x, 1)\n        x = F.relu(self.fc1(x))\n        x = self.dropout(x)\n        x = self.fc2(x)\n        return x\n```\n\nIn our convolutional neural network, we have the following architecture:\n  * A normalized convolutional layer with a 3 by 3 kernel and 32 output channels.\n  * A pooling operation with RELU activation, processed in `self.pool(F.relu(self.batch_norm1(self.conv1(x))))`\n  * A second normalized convolutional layer with a 3 by 3 kernel.\n  * A pooling operation with RELU activation, processed in `self.pool(F.relu(self.batch_norm2(self.conv2(x))))`\n  * A flattening layer - `torch.flatten(x,1)`\n  * Finally, two fully connected layers with a dropout in-between to prevent overfit.\n\n\nTraining a CNN in `pytorch` is similar to training a typical feed-forward neural network:\nini\n\n```\nnet = SimpleCNN()\n\noptimizer = torch.optim.SGD(params=net.parameters(),\n                            lr=0.05)\n```\n\nIn this example, we'll be using stochastic gradient descent with `0.05`learning rate. We can rely on code we previously defined to train the network:\npython\n\n```\nloss_hist_cnn = {}\n\nloss_hist_cnn['train'] = {}\nloss_hist_cnn['test'] = {}\n\nepochs = 10\nfor epoch in tqdm(range(epochs)):\n    print(f\"Epoch: {epoch}n---------\")\n    loss_cnn = train_step(data_loader=train_loader,\n        model=net,\n        loss_fn=loss_function,\n        optimizer=optimizer,\n        accuracy_fn=accuracy_fn\n    )\n\n    loss_hist_cnn['train'][epoch] = loss_cnn\n\n    loss_cnn_test = test_step(data_loader=test_loader,\n        model=net,\n        loss_fn=loss_function,\n        accuracy_fn=accuracy_fn\n    )\n\n    loss_hist_cnn['test'][epoch] = loss_cnn_test\n```\n\nAfter our 10th epoch, these are the results of our accuracy and loss:\n![Train and Test Accuracy on last epoch of CNN— Image by Author](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/1CRdv-8YEsfD7eZDnklDuMw.png)\nTrain and Test Accuracy on last epoch of CNN— Image by Author\nCool! It seemed we improved our model's accuracy by a lot, by more than 10 percentage points. This is clearly outperforming the simple non-linear architecture.\nLet's confirm that by plotting the train and test loss curves:\n![Train and Test Loss Evolution - Image by Author](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/1HpLz6wXSjxIOgdyp66kPKQ.png)\nTrain and Test Loss Evolution - Image by Author\nWe have the confirmation that loss is lower than the first experiment. But, we'll not celebrate yet! It's time for the litmus test: let's see how our model is classifying the _\"9\"_ digit that our first classifier was predicting incorrectly:\n![Prediction of Digit &quot;9&quot; using our CNN model - image by author](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/1YMwsa6iT8Q5sdFk5c9WTfg.png)\nPrediction of Digit \"9\" using our CNN model - image by author\nSo cool! We're now able to predict this digit correctly using a CNN. To wrap things up and out of curiosity, let's see another random example:\nscss\n\n```\nshow_predict_digit_cnn(net,\n                  test_dataset,\n                  15)\n```\n\n![Prediction of Digit &quot;5&quot; using our CNN model - image by author](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/1N6WzcFgV8XWRcDa1J4Cz3w.png)\nPrediction of Digit \"5\" using our CNN model - image by author\nAnother example correct! Can you check more digits and see if you can find the rare cases where our CNN is falling?\n* * *\nAnd that's a wrap for this post! Thank you for reading until the end and I hope that these examples helped you understand how to train a convolutional neural network using `pytorch` . It was also our first time dealing with these types of layers within the framework and it's really cool to see how `torch` is built similar to lego bricks! As soon as you understand how the layers work, mixing and matching them will give you extraordinary abilities when it comes to building deep learning models.\nIn summary, here's what we've done in this blog post:\n  * Trained our first computer vision model\n  * Fitted a typical feed-forward neural network on the MNIST dataset\n  * Fitted a CNN on the MNIST dataset\n  * Touched lightly upon the concept of CNNs and got to know conv, flatten, and pool layers.\n\n\nHope you've enjoyed this and see you on the next PyTorch post!\nYou can check the first PyTorch blog posts from this series [[[here](https://github.com/DareData/lp-pytorch-fundamentals)](https://towardsdatascience.com/pytorch-introduction-building-your-first-linear-model-d868a8681a41)](https://towardsdatascience.com/pytorch-introduction-tensors-and-tensor-calculations-412ff818bd5b?sk=2cf4d44549664fc647baa3455e9d78e8) and here. I also recommend that you visit [PyTorch Zero to Mastery Course](https://www.learnpytorch.io/01_pytorch_workflow/), an amazing free resource that inspired the methodology behind this post or go through our DareData's pytorch learning pod, available here.\nFeel free to drop by on my newly created youTube channel - the [Data Journey](https://www.youtube.com/@TheDataJourney42) where I'll be adding content on data Science and machine learning in the next couple of months and looking forward to seeing you there!\n[The dataset used in this post is under the MIT license.](https://huggingface.co/datasets/mnist)\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](https://assets.insightmediagroup.io/media/1787657081760_wqdt7l.jpeg)\nWritten By\n## [Ivo Bernardo](https://towardsdatascience.com/author/ivopbernardo/)\n[See all from Ivo Bernardo](https://towardsdatascience.com/author/ivopbernardo/)\n[Artificial Intelligence](https://towardsdatascience.com/tag/artificial-intelligence/)[Computer Vision](https://towardsdatascience.com/tag/computer-vision/)[Data Science](https://towardsdatascience.com/tag/data-science/)[Deep Learning](https://towardsdatascience.com/tag/deep-learning/)[Machine Learning](https://towardsdatascience.com/tag/machine-learning/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fpytorch-introduction-training-a-computer-vision-algorithm-c17ed96e64d5%2F&title=PyTorch%20Introduction%20-%20Training%20a%20Computer%20Vision%20Algorithm)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fpytorch-introduction-training-a-computer-vision-algorithm-c17ed96e64d5%2F&title=PyTorch%20Introduction%20-%20Training%20a%20Computer%20Vision%20Algorithm)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fpytorch-introduction-training-a-computer-vision-algorithm-c17ed96e64d5%2F&text=PyTorch%20Introduction%20-%20Training%20a%20Computer%20Vision%20Algorithm)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/08/1a2OQuKItPC4dUs-Y5Cw7_A.jpeg)](https://towardsdatascience.com/3-bitter-lessons-i-wish-i-knew-earlier-as-a-big-data-engineer-e2956bcc7b29/)\n## [3 Bitter Lessons I Wish I Knew Earlier As a Big Data Engineer](https://towardsdatascience.com/3-bitter-lessons-i-wish-i-knew-earlier-as-a-big-data-engineer-e2956bcc7b29/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nThe Dos and Don'ts of data engineering\n[Nam Nguyen](https://towardsdatascience.com/author/namnguyenwrite/)\nAugust 6, 20216 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/01/1ajSwGDgJm1hjaJSQKREOVw-scaled.jpeg)](https://towardsdatascience.com/multithreading-multiprocessing-python-180d0975ab29/)\n## [Multi-threading and Multi-processing in Python](https://towardsdatascience.com/multithreading-multiprocessing-python-180d0975ab29/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nA deep dive into multi-threading and multi-processing with Python and how they are related to concurrency and parallelism\n[Giorgos Myrianthous](https://towardsdatascience.com/author/gmyrianthous/)\nJanuary 21, 202210 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/07/pexels-vargaphotography-10796342-scaled-1.jpg)](https://towardsdatascience.com/backpropagation-explained-for-beginners-part-1-building-the-intuition/)\n## [Backpropagation Explained for Beginners (Part 1): Building the Intuition](https://towardsdatascience.com/backpropagation-explained-for-beginners-part-1-building-the-intuition/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nLet's discover how neural networks learn, step by step\n[Nikhil Dasari](https://towardsdatascience.com/author/nikhil.dasari/)\nJuly 19, 20269 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/02/ChatGPT-Image-Feb-18-2026-10_20_50-AM.jpg)](https://towardsdatascience.com/from-monolith-to-contract-driven-data-mesh/)\n## [From Monolith to Contract-Driven Data Mesh](https://towardsdatascience.com/from-monolith-to-contract-driven-data-mesh/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nA pragmatic journey using website analytics as a real-world example\n[Corné Potgieter](https://towardsdatascience.com/author/corne-potgieter/)\nFebruary 20, 202611 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/05/1CzGxKbXzbDYpLqzSz2LLcw.png)](https://towardsdatascience.com/reinforcement-learning-part-3-monte-carlo-methods-7ce2828a1fdb/)\n## [Reinforcement Learning, Part 3: Monte Carlo Methods](https://towardsdatascience.com/reinforcement-learning-part-3-monte-carlo-methods-7ce2828a1fdb/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nFrom casinos to AI: unveiling the power of Monte Carlo methods in complex environments\n[Slava Efimov](https://towardsdatascience.com/author/slavahead/)\nMay 23, 202413 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2017/03/1rHfv-Bc2FaUXP4I3fLq2ow.jpeg)](https://towardsdatascience.com/teaching-data-science-at-general-assembly-week-5-84b19e6f5697/)\n## [Teaching Data Science at General Assembly: Week 5](https://towardsdatascience.com/teaching-data-science-at-general-assembly-week-5-84b19e6f5697/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nThis week students are starting to think about what awesome data product they want to build for their capstone project. Also GA hosted a...\n[Alexander Barriga](https://towardsdatascience.com/author/databeast/)\nMarch 8, 20174 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/09/1e3HhH7UciwbC0HAIERhzSg.png)](https://towardsdatascience.com/4-more-little-known-nlp-libraries-that-are-hidden-gems-e77a71d1bc57/)\n## [4 More Little-Known NLP Libraries That Are Hidden Gems](https://towardsdatascience.com/4-more-little-known-nlp-libraries-that-are-hidden-gems-e77a71d1bc57/)\n[NLP](https://towardsdatascience.com/category/artificial-intelligence/nlp/)\nWith code examples and explanations.\n[Michael Markin](https://towardsdatascience.com/author/michaelmarkin/)\nSeptember 15, 20226 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/05/1jgTnCAlfJLnSEy5RLyOdow.png)](https://towardsdatascience.com/identifying-protein-ligand-interactions-with-colab-2cfd26ed469a/)\n## [Identifying Protein-Ligand Interactions with Colab](https://towardsdatascience.com/identifying-protein-ligand-interactions-with-colab-2cfd26ed469a/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nSetting up Autodock Vina\n[Jose Manuel Napoles-Duarte](https://towardsdatascience.com/author/jnapoles/)\nMay 3, 20208 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/01/1vx398m830YzTiZLT0GF5XQ-scaled.jpeg)](https://towardsdatascience.com/countif-in-5-languages-vba-sql-python-m-query-dax-powerbi-639d3d7c6c7f/)\n## [COUNTIF in 5 languages (VBA/SQL/PYTHON/M query/DAX powerBI)](https://towardsdatascience.com/countif-in-5-languages-vba-sql-python-m-query-dax-powerbi-639d3d7c6c7f/)\n[Programming](https://towardsdatascience.com/category/programming/)\nHow to make your favorite Excel feature in another analytic language (VBA/SQL/PYTHON/M query/DAX powerBI)\n[Aymen](https://towardsdatascience.com/author/aymenbaraket/)\nJanuary 10, 20216 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607686/image?etag=1782161464448&width=500&height=500) How Relevance Models Foreshadowed Transformers for NLP ](https://towardsdatascience.com/how-relevance-models-foreshadowed-transformers-for-nlp/ \"How Relevance Models Foreshadowed Transformers for NLP\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ \"Does Your Company Have a Data Strategy?\")\n\n\n",
  "body_base_path": "attachments/03f263e77ad7/pages/",
  "body_markdown_path": "attachments/03f263e77ad7/pages/archived-body.md",
  "local_html": "attachments/03f263e77ad7/pages/archived-body.html",
  "body_source": "prior_capture"
}