Linear regression:

Linear regression is a method of analyzing the relationship between one variable and one (more) other variables dependent variable: y Independent variable: x Relationship: linear y = wx +b Analysis: solve w, b

Solution steps:

1. Determine the model

Model: y = wx + b

2. Select the loss function

MSE:



3. Solve the gradient and update W, b

w = w – LR * w.grad

b = b – LR * b.grad

Import torch import matplotlib.pyplot as PLT torch. Manual_seed (10) 1) * 10 y = 2*x + (5 + torch. Randn (20, 1)) requires_grad=True) for iteration in range(1000): Wx = torch. Mul (w, x) y_pred = torch. Add (wx, x) B) # calculate MSE loss Loss = (0.5 * (y-y_pred) ** 2).mean() # spread loss. Backward () # update parameter b.data.sub_(lr * b.grad) W.data.sub_ (LR * w.grad) # Draw if Iteration % 20 == 0: plt.scatter(x.data.numpy(), y.data.numpy()) plt.plot(x.data.numpy(), y_pred.data.numpy(), 'r-', lw=5) plt.text(2, 20, 'Loss=%.4f' % loss.data.numpy(), fontdict={'size': 20, 'color': 'red'}) PLT. Xlim (1.5, 10) PLT. Ylim (8, 28) PLT. Title (' Iteration: {} \ nw: {} b: {}'.format(iteration, w.data.numpy(), b.data.numpy()))) plt.pause(0.5) if loss.data.numpy() < 1: breakCopy the code