政策资讯

Policy Information


PyTorch:采用sklearn 工具生成这样的合成数据集+利用PyTorch实现简单合成数据集上的线性回归进行数据分析

来源: 重庆市软件正版化服务中心    |    时间: 2022-09-20    |    浏览量: 52382    |   

PyTorch:采用sklearn 工具生成这样的合成数据集+利用PyTorch实现简单合成数据集上的线性回归进行数据分析

目录

输出结果

核心代码


输出结果

核心代码

  1. PyTorch:采用sklearn 工具生成这样的合成数据集+利用PyTorch实现简单合成数据集上的线性回归进行数据分析
  2. from sklearn.datasets import make_regression
  3. import seaborn as sns
  4. import pandas as pd
  5. import matplotlib.pyplot as plt
  6. sns.set()
  7. x_train, y_train, W_target = make_regression(n_samples=100, n_features=1, noise=10, coef = True)
  8. df = pd.DataFrame(data = {'X':x_train.ravel(), 'Y':y_train.ravel()})
  9. sns.lmplot(x='X', y='Y', data=df, fit_reg=True)
  10. plt.show()
  11. x_torch = torch.FloatTensor(x_train)
  12. y_torch = torch.FloatTensor(y_train)
  13. y_torch = y_torch.view(y_torch.size()[0], 1)
  14. class LinearRegression(torch.nn.Module): 定义LR的类。torch.nn库构建模型
  15. PyTorch 的 nn 库中有大量有用的模块,其中一个就是线性模块。如名字所示,它对输入执行线性变换,即线性回归。
  16. def __init__(self, input_size, output_size):
  17. super(LinearRegression, self).__init__()
  18. self.linear = torch.nn.Linear(input_size, output_size)
  19. def forward(self, x):
  20. return self.linear(x)
  21. model = LinearRegression(1, 1)
  22. criterion = torch.nn.MSELoss() 训练线性回归,我们需要从 nn 库中添加合适的损失函数。对于线性回归,我们将使用 MSELoss()——均方差损失函数
  23. optimizer = torch.optim.SGD(model.parameters(), lr=0.1)还需要使用优化函数(SGD),并运行与之前示例类似的反向传播。本质上,我们重复上文定义的 train() 函数中的步骤。
  24. 不能直接使用该函数的原因是我们实现它的目的是分类而不是回归,以及我们使用交叉熵损失和最大元素的索引作为模型预测。而对于线性回归,我们使用线性层的输出作为预测。
  25. for epoch in range(50):
  26. data, target = Variable(x_torch), Variable(y_torch)
  27. output = model(data)
  28. optimizer.zero_grad()
  29. loss = criterion(output, target)
  30. loss.backward()
  31. optimizer.step()
  32. predicted = model(Variable(x_torch)).data.numpy()
  33. 打印出原始数据和适合 PyTorch 的线性回归
  34. plt.plot(x_train, y_train, 'o', label='Original data')
  35. plt.plot(x_train, predicted, label='Fitted line')
  36. plt.legend()
  37. plt.title(u'Py:PyTorch实现简单合成数据集上的线性回归进行数据分析')
  38. plt.show()

评论

产品推荐

更多 >

QQ咨询 扫一扫加入群聊,了解更多平台咨询
微信咨询 扫一扫加入群聊,了解更多平台咨询
意见反馈
立即提交
QQ咨询
微信咨询
意见反馈