这部分是以实现线性回归为主, 当中是代码, 将会不使用框架实现
详见代码, 里面已尽量给予解释
import torch
import random
# 自创数据集
def synthetic_data(w, b, num_examples):
x = torch.normal(0, 1, (num_examples, len(w)))
y = torch.matmul(x, w) + b
y += torch.normal(0, 0.01, y.shape) # add noise
return x, y.reshape((-1, 1))
# default: w=[2, -3.4].T, b=4.2
true_w = torch.tensor([2, -3.4])
true_b = 4.2
features, labels = synthetic_data(true_w, true_b, 1000)
# 每次读取小批量
def data_iter(batch_size, features, labels):
num_examples = len(features)
indices = list(range(num_examples))
random.shuffle(indices) # 样本是random取的, 没有特定顺序
for i in range(0, num_examples, batch_size):
batch_indices = torch.tensor(indices[i:min(i+batch_size, num_examples)])
yield features[batch_indices], labels[batch_indices]
# 定义model params
# 对bias进行更新, 所以requires_grad=True
w = to