0 写在前面
- 考虑到之前用于训练的数据都是小样本的,比如说
PyTorch深度学习入门 || 系列(一)
中的输入就只有五组数据,然后我们将这五个数据作为一次输入,全部喂给模型。这种方法是快速的。 - 但是本文主要围绕使用大规模数据进行线性回归实验!
- 如果您觉得本篇文章对您有帮助的话,感谢点赞+收藏+关注我噢!
1 随机生成大规模数据
- 首先使用
linspace()
函数在[-3,3)区间内划分出100000个点。作为input - 然后对于y来说,为了使得数据更加符合线性分布且更加真实,在x的基础上增加了一些误差。使用rand()函数生成一组在[0,1)区间内均匀分布的随机数(数量=x.size),然后乘以1.2。作为output
- 数据输出情况如下:
- 代码如下,代码可以直接运行:
import torch
import matplotlib.pyplot as plt
def Produce_X(x):
x0 = torch.ones(x.numpy().size)
X = torch.stack((x, x0), dim=1)
return X
x = torch.linspace(-3, 3, 100000)
X = Produce_X(x)
y = x + 1.2 * torch.rand(x.size())
w = torch.rand(2)
plt.scatter(x.numpy(), y.numpy(), s=0.001)
plt.show()
2 使用cuda加速
- 默认是支持CUDA的平台,采用GPU进行加速运算。
inputs = X.cuda()
target = y.cuda()
w = w.cuda()
w.requires_grad=True
注意:如果没有cuda的话,直接把上面代码中的.cuda()
去掉就好了!
3 定义draw()函数
- 注意:在使用了CUDA()加速之后,在draw()函数的output需要还原成CPU类型的数据才能进行绘图
- .data返回的是一个Tensor,要
output.data.numpy()
- .item返回的是一个值,适合返回 loss,accuracy
def draw(output, loss):
output = output.cpu()
plt.cla() # 清空画布
plt.scatter(x.numpy(), y.numpy())
plt.plot(x.numpy(), output.data.numpy(), 'r-', lw=5)
plt.text(0.5, 0, 'Loss=%s' % (loss.item()), fontdict={'size':20, 'color':'red'})
plt.show()
4 定义train()函数
- .sum()函数:返回Tensor所有元素之和
def train(epochs=1, learning_rate=0.01):
for epoch in range(epochs):
output = inputs.mv(w) # 矩阵和向量相乘
loss = (output - target).pow(2).sum()/100000
loss.backward() # 调用之后才会有w.grad的值
w.data -= learning_rate * w.grad
w.grad.zero_()
if epoch % 80 == 0:
draw(output, loss)
return w, loss
5 主函数模块内容
start = perf_counter()
w, loss = train(10000, learning_rate=1e-4)
finish = perf_counter()
time = finish - start
print("计算时间: %s" % time)
print("final loss: ", loss.item())
print("weights:", w.data)
6 完整代码
- 此段代码可以直接运行,考虑到效率,我传入的是
train(100, learning_rate=1e-4)
import torch
import matplotlib.pyplot as plt
from time import perf_counter
def Produce_X(x):
x0 = torch.ones(x.numpy().size)
X = torch.stack((x, x0), dim=1)
return X
x = torch.linspace(-3, 3, 100000)
X = Produce_X(x)
y = x + 1.2 * torch.rand(x.size())
w = torch.rand(2)
plt.scatter(x.numpy(), y.numpy(), s=0.001)
plt.show()
inputs = X.cuda()
target = y.cuda()
w = w.cuda()
w.requires_grad=True
def draw(output, loss):
output = output.cpu()
plt.cla()
plt.scatter(x.numpy(), y.numpy())
plt.plot(x.numpy(), output.data.numpy(), 'r-', lw=5)
plt.text(0.5, 0, 'Loss=%s' % (loss.item()), fontdict={'size':20, 'color':'red'})
plt.show()
def train(epochs=1, learning_rate=0.01):
for epoch in range(epochs):
output = inputs.mv(w) # 矩阵和向量相乘
loss = (output - target).pow(2).sum()/100000
loss.backward() # 调用之后才会有w.grad的值
w.data -= learning_rate * w.grad
w.grad.zero_()
if epoch % 80 == 0:
draw(output, loss)
return w, loss
start = perf_counter()
w, loss = train(100, learning_rate=1e-4)
finish = perf_counter()
time = finish - start
print("计算时间: %s" % time)
print("final loss: ", loss.item())
print("weights:", w.data)
- 输出