算法
线性回归是利用数理统计中的回归分析,来确定两种或两种以上变量间相互依赖的定量关系的一种统计分析方法,运用十分广泛。分析按照自变量和因变量之间的关系类型,可分为线性回归分析和非线性回归分析。
回归分析中,只包括一个自变量和一个因变量,且二者的关系可用一条直线近似表示,这种回归分析称为一元线性回归分析。如果回归分析中包含两个或两个以上的自变量,且因变量和自变量之间是线性关系的,则称为多元线性回归分析。
线性模型基本形式
线性回归属于回归算法,表达监督学习的过程。通过属性的线性组合来预测函数:
f ( x ) = w 1 x 1 + w 2 x 2 + . . . + w d x d + b \ f(x) = w_1x_1 + w_2x_2 + ... + w_dx_d + b f(x)=w1x1+w2x2+...+wdxd+b
一般向量形式写成:
f ( s ) = w T x + b \ f(s) = \boldsymbol w^Tx + b f(s)=wTx+b
其中的 w = ( w 1 ; w 2 ; . . . ; w d ) \boldsymbol w = (w_1; \ w_2;\ ...;\ w_d) w=(w1; w2; ...; wd)。
x 1 , x 2 , . . . , x k x_1,\ x_2,\ ...,\ x_k x1, x2, ..., xk是一组独立的预测变量。
w 1 , w 2 , . . . , w k w_1,\ w_2,\ ...,\ w_k w1, w2, ..., wk为模型从训练数据中学习到的参数,或赋予每个变量的“权值”。
b b b也是一个学习到的参数,这个线性函数中的常量也称为模型的偏置(Bias)。
线性回归的目标是找到一个与训练数据最为吻合的线性函数,用来预测或者分类,主要解决线性问题。
代码实现
import torch as tr
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
from torch.autograd import Variable
input_size = 1
output_size = 1
learning_rate = 0.001
xtrain = np.array([[2.3], [4.4], [3.7], [6.1], [7.3], [2.1], [5.6], [7.7], [8.7], [4.1], [6.7], [6.1], [7.5], [2.1], [7.2], [5.6], [5.7], [7.7], [3.1]], dtype=np.float32)
ytrain = np.array([[3.7], [4.76], [4.], [7.1], [8.6], [3.5], [5.4], [7.6], [7.9], [5.3], [7.3], [7.5], [8.5], [3.2], [8.7], [6.4], [6.6], [7.9], [5.3]], dtype=np.float32)
plt.figure()
plt.scatter(xtrain, ytrain)
plt.xlabel('xtrain')
plt.ylabel('ytrain')
plt.show()
class LinearRegression(nn.Module):
def __init__(self, input_size, output_size):
super(LinearRegression, self).__init__()
self.linear = nn.Linear(input_size, output_size)
def forward(self, x):
out = self.linear(x)
return out
model = LinearRegression(input_size, output_size)
criterion = nn.MSELoss()
optimizer = tr.optim.SGD(model.parameters(), lr=learning_rate)
num_epochs = 1000
for epoch in range(num_epochs):
inputs = Variable(tr.from_numpy(xtrain))
targets = Variable(tr.from_numpy(ytrain))
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
if(epoch+1) % 50 == 0:
print('Epoch [%d/%d], Loss: %.4f' % (epoch + 1, num_epochs, loss.item()))
model.eval()
predicted = model(Variable(tr.from_numpy(xtrain))).data.numpy()
plt.plot(xtrain, ytrain, 'ro')
plt.plot(xtrain, predicted, label='predict')
plt.legend()
plt.show()