天天看点

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

输出结果

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

核心代码

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

from sklearn.datasets import make_regression

import seaborn as sns

import pandas as pd

import matplotlib.pyplot as plt

sns.set()

x_train, y_train, W_target = make_regression(n_samples=100, n_features=1, noise=10, coef = True)

df = pd.DataFrame(data = {'X':x_train.ravel(), 'Y':y_train.ravel()})

sns.lmplot(x='X', y='Y', data=df, fit_reg=True)

plt.show()

x_torch = torch.FloatTensor(x_train)

y_torch = torch.FloatTensor(y_train)

y_torch = y_torch.view(y_torch.size()[0], 1)

class LinearRegression(torch.nn.Module):  #定义LR的类。torch.nn库构建模型

   #PyTorch 的 nn 库中有大量有用的模块,其中一个就是线性模块。如名字所示,它对输入执行线性变换,即线性回归。

   def __init__(self, input_size, output_size):

       super(LinearRegression, self).__init__()

       self.linear = torch.nn.Linear(input_size, output_size)  

   def forward(self, x):

       return self.linear(x)

model = LinearRegression(1, 1)

criterion = torch.nn.MSELoss() #训练线性回归,我们需要从 nn 库中添加合适的损失函数。对于线性回归,我们将使用 MSELoss()——均方差损失函数

optimizer = torch.optim.SGD(model.parameters(), lr=0.1)#还需要使用优化函数(SGD),并运行与之前示例类似的反向传播。本质上,我们重复上文定义的 train() 函数中的步骤。

#不能直接使用该函数的原因是我们实现它的目的是分类而不是回归,以及我们使用交叉熵损失和最大元素的索引作为模型预测。而对于线性回归,我们使用线性层的输出作为预测。

for epoch in range(50):

   data, target = Variable(x_torch), Variable(y_torch)

   output = model(data)

   optimizer.zero_grad()

   loss = criterion(output, target)

   loss.backward()

   optimizer.step()

predicted = model(Variable(x_torch)).data.numpy()

#打印出原始数据和适合 PyTorch 的线性回归

plt.plot(x_train, y_train, 'o', label='Original data')

plt.plot(x_train, predicted, label='Fitted line')

plt.legend()

plt.title(u'Py:PyTorch实现简单合成数据集上的线性回归进行数据分析')