# 线性回归模型从零开始的实现# import packages and modulesimport matplotlib
# %matplotlib inlineimport torch
from IPython import display
from matplotlib import pyplot as plt
import numpy as np
import random
print(torch.__version__)# 生成数据集# 使用线性模型来生成数据集,生成一个1000个样本的数据集,下面是用来生成数据的线性关系:# price=warea⋅area+wage⋅age+b# set input feature number
num_inputs =2# set example number
num_examples =1000# set true weight and bias in order to generate corresponded label
true_w =[2,-3.4]
true_b =4.2
features = torch.randn(num_examples, num_inputs, dtype=torch.float32)print(features)print(features[:,0])
labels = true_w[0]* features[:,0]+ true_w[1]* features[:,1]+ true_b
labels += torch.tensor(np.random.normal(0,0.01, size=labels.size()), dtype=torch.float32)# 使用图像来展示生成的数据
plt.scatter(features[:,1].numpy(), labels.numpy(),1)
plt.show()# 读取数据集defdata_iter(batch_size, features, labels):
num_examples2 =len(features)
indices =list(range(num_examples2))
random.shuffle(indices)# random read 10 samplesfor i inrange(0, num_examples2, batch_size):
j = torch.LongTensor(
indices[i:min(i + batch_size, num_examples2)])# the last time may be not enough for a whole batchyield features.index_select(0, j), labels.index_select(0, j)
batch_size =10for X, y in data_iter(batch_size, features, labels):print(X,'\n', y)break# 初始化模型参数
w = torch.tensor(np.random.normal(0,0.01,(num_inputs,1)), dtype=torch.float32)
b = torch.zeros(1, dtype=torch.float32)
w.requires_grad_(requires_grad=True)
b.requires_grad_(requires_grad=True)