使用sklearn.dataset 的make_regression创建用于线性回归的数据集
def create_dataset():
x, y, coef = make_regression(n_samples=100, noise=10, coef=True, bias=14.5, n_features=1, random_state=0)
return torch.tensor(x), torch.tensor(y), coef
加载数据集,并拆分batchs训练集
def load_dataset(x, y, batch_size):
data_len = len(y)
batch_num = data_len // batch_size
for idx in range(batch_num):
start = idx * batch_num
end = idx * batch_num + batch_num
train_x = x[start : end]
train_y = y[start : end]
yield train_x, train_y
定义初始权重和定义计算函数
w = torch.tensor(0.1, requires_grad=True, dtype=torch.float64)
b = torch.tensor(0, requires_grad=True, dtype=torch.float64)
def linear_regression(x):
return x * w + b
损