How to realize Linear regression by pytorch
This article is about how pytorch implements linear regression. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
The details are as follows
# randomly initialize a 2D dataset Use a friend torch to train a regression model import numpy as npimport randomimport matplotlib.pyplot as pltx = np.arange (20) y = np.array ([5* x [I] + random.randint (1m 20) for i in range (len (x))]) # random.randint (parameter 1 Parameter 2) the function returns any integer print ('-'* 50) # print data set print (x) print (y) import torchx_train = torch.from_numpy (x). Float () y_train = torch.from_numpy (y). Float () # modelclass LinearRegression (torch.nn.Module): def _ init__ (self): super (LinearRegression) Self). _ _ init__ () # A new model whose inputs and outputs are both one-dimensional self.linear = torch.nn.Linear (1pm 1) def forward (self,x): return self.linear (x) # Error function Optimizer model = LinearRegression () criterion = torch.nn.MSELoss () optimizer = torch.optim.SGD (model.parameters (), 0.001) # start training num_epoch = 20for i in range (num_epoch): input_data = x_train.unsqueeze (1) target = y_train.unsqueeze (1) # unsqueeze (1) add a dimension out = model (input_data) loss = criterion (out) in the second dimension Target) optimizer.zero_grad () loss.backward () optimizer.step () print ("Eopch: [{} / {}, loss: [{: .4f}]" .format (if ()) if () 2 = = 0): predict = model (input_data) plt.plot (x_train.data.numpy (), predict.squeeze (1). Data.numpy () "r") loss = criterion (predict,target) plt.title ("Loss: {: .4f}" .format (loss.item ()) plt.xlabel ("X") plt.ylabel ("Y") plt.scatter
Experimental results:
Thank you for reading! This is the end of the article on "how to achieve linear regression in pytorch". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!