In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
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!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.