SlideShare a Scribd company logo
Describe the complete pipeline in ML using programming through PyTorch. For this, you need
to write code that performs linear regression using PyTorch on simulated data. Make sure you
include training, testing and evaluation in your code.
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "V0RhNGmBjFWt"
},
"outputs": [],
"source": [
"import torchn",
"import numpy as npn",
"import matplotlib.pyplot as pltn",
"import seaborn"
]
},
{
"cell_type": "code",
"source": [
"# Creating a function f(X) with a slope of -5n",
"X = torch.arange(-5, 5, 0.2).view(-1, 1)n",
"func = -5 * X"
],
"metadata": {
"id": "Vq4OWcCNjJFj"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Plot the line in red with gridsn",
"plt.plot(X.numpy(), func.numpy(), 'r', label='func')n",
"plt.xlabel('x')n",
"plt.ylabel('y')n",
"plt.legend()n",
"plt.grid('True', color='y')n",
"plt.show()"
],
"metadata": {
"id": "EFDhIKURjPbB"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Adding Gaussian noise to the function f(X) and saving it in Yn",
"Y = func + 1.7 * torch.randn(X.size())"
],
"metadata": {
"id": "c2KRcFl5jRuy"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Plot and visualizing the data points in bluen",
"plt.plot(X.numpy(), Y.numpy(), 'b+', label='Y')n",
"plt.plot(X.numpy(), func.numpy(), 'r', label='func')n",
"plt.xlabel('x')n",
"plt.ylabel('y')n",
"plt.legend()n",
"plt.grid('True', color='y')n",
"plt.show()"
],
"metadata": {
"id": "ahd47p24jgrB"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# defining the function for forward pass for predictionn",
"def forward(x):n",
" return w * x"
],
"metadata": {
"id": "T-vtFS9Gjig2"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# evaluating data points with Mean Square Error.n",
"def criterion(y_pred, y):n",
" return torch.mean( (y_pred - y) ** 2 )"
],
"metadata": {
"id": "DpPaj2Vvjv5A"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"w = torch.tensor(-10.0, requires_grad=True)"
],
"metadata": {
"id": "UMXfOHC0jx9G"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"step_size = 0.1n",
"loss_list = []n",
"iter = 20"
],
"metadata": {
"id": "Ml6UCAqujzvm"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"for i in range (iter):n",
" # making predictions with forward passn",
" Y_pred = forward(X)n",
"n",
"n",
" # calculating the loss between original and predicted data pointsn",
" loss = criterion(Y_pred, Y)n",
"n",
"n",
" # storing the calculated loss in a listn",
" loss_list.append(loss.item())n",
"n",
"n",
" # backward pass for computing the gradients of the loss w.r.t to learnable parametersn",
" loss.backward()n",
"n",
"n",
" # updateing the parameters after each iterationn",
" w.data = w.data - step_size * w.grad.datan",
"n",
"n",
" # zeroing gradients after each iterationn",
" w.grad.data.zero_()n",
"n",
"n",
" # priting the values for understandingn",
" print('{},t{},t{}'.format(i, loss.item(), w.item())) n",
" n",
" n",
" # .item() gets the numeric value from the tensor structure"
],
"metadata": {
"id": "3C11BynFj1yw"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"# Plotting the loss after each iterationn",
"plt.plot(loss_list, 'r')n",
"plt.tight_layout()n",
"plt.grid('True', color='y')n",
"plt.xlabel("Epochs/Iterations")n",
"plt.ylabel("Loss")n",
"plt.show()"
],
"metadata": {
"id": "dt9RKOLSj-EZ"
},
"execution_count": null,
"outputs": []
},
{
"cell_type": "code",
"source": [
"w.item()"
],
"metadata": {
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "sSswUL6-kQ5O",
"outputId": "9412eaed-eaab-4d8c-81fd-822516587349"
},
"execution_count": null,
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"-4.990855693817139"
]
},
"metadata": {},
"execution_count": 35
}
]
},
{
"cell_type": "code",
"source": [],
"metadata": {
"id": "RA8s3FjZkbuU"
},
"execution_count": null,
"outputs": []
}
]
}

More Related Content

PDF
pytorch-cheatsheet.pdf for ML study with pythroch
PDF
Machine learning with py torch
PDF
01_pytorch_workflow jutedssd huge hhgggdf
PDF
Reproducible AI using MLflow and PyTorch
PDF
Dive Into PyTorch
PPTX
Deep learning study 3
pytorch-cheatsheet.pdf for ML study with pythroch
Machine learning with py torch
01_pytorch_workflow jutedssd huge hhgggdf
Reproducible AI using MLflow and PyTorch
Dive Into PyTorch
Deep learning study 3

Similar to Describe the complete pipeline in ML using programming through PyTorch.pdf (20)

PPTX
Lecture 02_ Linear Model - machine learning
PPTX
Pytorch and Machine Learning for the Math Impaired
PPTX
[DevDay2019] Python Machine Learning with Jupyter Notebook - By Nguyen Huu Th...
PPTX
PyTorch Tutorial for NTU Machine Learing Course 2017
PPTX
[Update] PyTorch Tutorial for NTU Machine Learing Course 2017
PDF
Reproducible AI Using PyTorch and MLflow
PDF
Assignment 5.2.pdf
PDF
Introduction to Machine Learning
PPTX
Machine Learning Essentials Demystified part2 | Big Data Demystified
PDF
Gradient Descent Code Implementation.pdf
PPTX
Introduction to PyTorch
PDF
Pythonbrasil - 2018 - Acelerando Soluções com GPU
PDF
Pytorch for tf_developers
PDF
Reproducible AI Using PyTorch and MLflow
PPTX
TensorFlow for IITians
PDF
Hello below is my code for MPL image classification- When I try to run.pdf
PDF
"PyTorch Deep Learning Framework: Status and Directions," a Presentation from...
PPTX
pytorch_tutorial_follow_this_to_start.pptx
PPTX
Introduction to TensorFlow
PDF
MLCC Schedule #1
Lecture 02_ Linear Model - machine learning
Pytorch and Machine Learning for the Math Impaired
[DevDay2019] Python Machine Learning with Jupyter Notebook - By Nguyen Huu Th...
PyTorch Tutorial for NTU Machine Learing Course 2017
[Update] PyTorch Tutorial for NTU Machine Learing Course 2017
Reproducible AI Using PyTorch and MLflow
Assignment 5.2.pdf
Introduction to Machine Learning
Machine Learning Essentials Demystified part2 | Big Data Demystified
Gradient Descent Code Implementation.pdf
Introduction to PyTorch
Pythonbrasil - 2018 - Acelerando Soluções com GPU
Pytorch for tf_developers
Reproducible AI Using PyTorch and MLflow
TensorFlow for IITians
Hello below is my code for MPL image classification- When I try to run.pdf
"PyTorch Deep Learning Framework: Status and Directions," a Presentation from...
pytorch_tutorial_follow_this_to_start.pptx
Introduction to TensorFlow
MLCC Schedule #1

More from BorisdFHFraserk (20)

PDF
Create a network diagram using a forward pass and reverse pass from th.pdf
PDF
Cov(X+Y-XY)-D(X)D(Y.pdf
PDF
courage in leadership 1- What am I actually learning here- Any insight.pdf
PDF
Cov(XiX-X)-0.pdf
PDF
Coronado Hotel Foxtrot initiated operations on July 1- 2020- To manage.pdf
PDF
Coronado Company reported total manufacturing costs of $65100- manufac.pdf
PDF
Create a Cladogram and Venn diagram based on the morphological-anatomi.pdf
PDF
Do you think this sense of structured mobility is fair to everyone- Is.pdf
PDF
Dish Corporation acquired 100 percent of the common stock of Toll S na.pdf
PDF
DNA polymerase is found in- cells and all viruses all viruses some vir.pdf
PDF
Disk drives have been getting larger- Their capacity is now often give.pdf
PDF
DistributionAbsorption of a drug is a requirement for establishing ade.pdf
PDF
discuss the every point related to secure cloud storage policy - intro.pdf
PDF
Discrete structures Using the patterns to find these primes- is there.pdf
PDF
Directions- You have been asked to write a newspaper editorial- In the.pdf
PDF
Difficulties and strengths of use cases After reading the textbook mat.pdf
PDF
Different sensory systems have different benefits and biological relev.pdf
PDF
Create a small java or python program to implement the following class.pdf
PDF
Diabetics are prone to diabetic nephropathy because a- diabetics are.pdf
PDF
Develop an EER model for the following situation- After completing a c.pdf
Create a network diagram using a forward pass and reverse pass from th.pdf
Cov(X+Y-XY)-D(X)D(Y.pdf
courage in leadership 1- What am I actually learning here- Any insight.pdf
Cov(XiX-X)-0.pdf
Coronado Hotel Foxtrot initiated operations on July 1- 2020- To manage.pdf
Coronado Company reported total manufacturing costs of $65100- manufac.pdf
Create a Cladogram and Venn diagram based on the morphological-anatomi.pdf
Do you think this sense of structured mobility is fair to everyone- Is.pdf
Dish Corporation acquired 100 percent of the common stock of Toll S na.pdf
DNA polymerase is found in- cells and all viruses all viruses some vir.pdf
Disk drives have been getting larger- Their capacity is now often give.pdf
DistributionAbsorption of a drug is a requirement for establishing ade.pdf
discuss the every point related to secure cloud storage policy - intro.pdf
Discrete structures Using the patterns to find these primes- is there.pdf
Directions- You have been asked to write a newspaper editorial- In the.pdf
Difficulties and strengths of use cases After reading the textbook mat.pdf
Different sensory systems have different benefits and biological relev.pdf
Create a small java or python program to implement the following class.pdf
Diabetics are prone to diabetic nephropathy because a- diabetics are.pdf
Develop an EER model for the following situation- After completing a c.pdf

Recently uploaded (20)

PPTX
master seminar digital applications in india
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Classroom Observation Tools for Teachers
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PPTX
GDM (1) (1).pptx small presentation for students
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
master seminar digital applications in india
O5-L3 Freight Transport Ops (International) V1.pdf
Module 4: Burden of Disease Tutorial Slides S2 2025
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Microbial diseases, their pathogenesis and prophylaxis
Classroom Observation Tools for Teachers
2.FourierTransform-ShortQuestionswithAnswers.pdf
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
GDM (1) (1).pptx small presentation for students
Supply Chain Operations Speaking Notes -ICLT Program
FourierSeries-QuestionsWithAnswers(Part-A).pdf
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
human mycosis Human fungal infections are called human mycosis..pptx
102 student loan defaulters named and shamed – Is someone you know on the list?
STATICS OF THE RIGID BODIES Hibbelers.pdf
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx

Describe the complete pipeline in ML using programming through PyTorch.pdf

  • 1. Describe the complete pipeline in ML using programming through PyTorch. For this, you need to write code that performs linear regression using PyTorch on simulated data. Make sure you include training, testing and evaluation in your code. { "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "provenance": [] }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "language_info": { "name": "python" } }, "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "id": "V0RhNGmBjFWt" }, "outputs": [], "source": [ "import torchn", "import numpy as npn", "import matplotlib.pyplot as pltn", "import seaborn" ] }, { "cell_type": "code", "source": [ "# Creating a function f(X) with a slope of -5n", "X = torch.arange(-5, 5, 0.2).view(-1, 1)n", "func = -5 * X" ], "metadata": { "id": "Vq4OWcCNjJFj" }, "execution_count": null, "outputs": []
  • 2. }, { "cell_type": "code", "source": [ "# Plot the line in red with gridsn", "plt.plot(X.numpy(), func.numpy(), 'r', label='func')n", "plt.xlabel('x')n", "plt.ylabel('y')n", "plt.legend()n", "plt.grid('True', color='y')n", "plt.show()" ], "metadata": { "id": "EFDhIKURjPbB" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "# Adding Gaussian noise to the function f(X) and saving it in Yn", "Y = func + 1.7 * torch.randn(X.size())" ], "metadata": { "id": "c2KRcFl5jRuy" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "# Plot and visualizing the data points in bluen", "plt.plot(X.numpy(), Y.numpy(), 'b+', label='Y')n", "plt.plot(X.numpy(), func.numpy(), 'r', label='func')n", "plt.xlabel('x')n", "plt.ylabel('y')n", "plt.legend()n", "plt.grid('True', color='y')n", "plt.show()" ], "metadata": { "id": "ahd47p24jgrB" }, "execution_count": null,
  • 3. "outputs": [] }, { "cell_type": "code", "source": [ "# defining the function for forward pass for predictionn", "def forward(x):n", " return w * x" ], "metadata": { "id": "T-vtFS9Gjig2" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "# evaluating data points with Mean Square Error.n", "def criterion(y_pred, y):n", " return torch.mean( (y_pred - y) ** 2 )" ], "metadata": { "id": "DpPaj2Vvjv5A" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "w = torch.tensor(-10.0, requires_grad=True)" ], "metadata": { "id": "UMXfOHC0jx9G" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "step_size = 0.1n", "loss_list = []n", "iter = 20" ],
  • 4. "metadata": { "id": "Ml6UCAqujzvm" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "for i in range (iter):n", " # making predictions with forward passn", " Y_pred = forward(X)n", "n", "n", " # calculating the loss between original and predicted data pointsn", " loss = criterion(Y_pred, Y)n", "n", "n", " # storing the calculated loss in a listn", " loss_list.append(loss.item())n", "n", "n", " # backward pass for computing the gradients of the loss w.r.t to learnable parametersn", " loss.backward()n", "n", "n", " # updateing the parameters after each iterationn", " w.data = w.data - step_size * w.grad.datan", "n", "n", " # zeroing gradients after each iterationn", " w.grad.data.zero_()n", "n", "n", " # priting the values for understandingn", " print('{},t{},t{}'.format(i, loss.item(), w.item())) n", " n", " n", " # .item() gets the numeric value from the tensor structure" ], "metadata": { "id": "3C11BynFj1yw" }, "execution_count": null, "outputs": [] },
  • 5. { "cell_type": "code", "source": [ "# Plotting the loss after each iterationn", "plt.plot(loss_list, 'r')n", "plt.tight_layout()n", "plt.grid('True', color='y')n", "plt.xlabel("Epochs/Iterations")n", "plt.ylabel("Loss")n", "plt.show()" ], "metadata": { "id": "dt9RKOLSj-EZ" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "w.item()" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "sSswUL6-kQ5O", "outputId": "9412eaed-eaab-4d8c-81fd-822516587349" }, "execution_count": null, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "-4.990855693817139" ] }, "metadata": {}, "execution_count": 35 } ] }, { "cell_type": "code", "source": [],