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 torch\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "import seaborn" ] }, { "cell_type": "code", "source": [ "# Creating a function f(X) with a slope of -5\n", "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 grids\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": "EFDhIKURjPbB" }, "execution_count": null, "outputs": [] }, { "cell_type": "code", "source": [ "# Adding Gaussian noise to the function f(X) and saving it in Y\n", "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 blue\n", "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 prediction\n", "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.1\n", "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 pass\n", " Y_pred = forward(X)\n", "\n", "\n", " # calculating the loss between original and predicted data points\n", " loss = criterion(Y_pred, Y)\n", "\n", "\n", " # storing the calculated loss in a list\n", " loss_list.append(loss.item())\n", "\n", "\n", " # backward pass for .