y 本是一维向量(n),但需要将其转换为二维矩阵(nx1)。因为模型的预测输出是二维张量,标签必须与之形状一致才能匹配,否则计算损失时会报错。二维矩阵表示每个样本对应一个标签,决定了它是否可以广播(broadcast)、是否能被线性层接受、是否可以与其他张量拼接或乘法。 y.reshape((-1, 1))中-1 是自动推断维度的意思,自计算样本数。
1 2 3 4 5
defsynthetic_data(w, b, num_examples): X = torch.normal(0, 1, (num_examples, len(w))) #num_examples为样本数,len(w)为特征数 y = torch.matmul(X, w) + b # 偏置加权求和,计算每个样本的预测值(标签) y += torch.normal(0, 0.01, y.shape) # 添加随机扰动(噪声) return X, y.reshape((-1, 1)) #保持模型输出和标签结构完全一致
读取数据集
1 2 3 4 5 6 7 8 9
defdata_iter(batch_size, features, labels): num_examples = len(features) indices = list(range(num_examples)) # 这些样本是随机读取的,没有特定的顺序 random.shuffle(indices) for i inrange(0, num_examples, batch_size): batch_indices = torch.tensor( indices[i: min(i + batch_size, num_examples)]) yield features[batch_indices], labels[batch_indices]