# 导入相关包和函数 import torch import numpy as np import pandas as pd import torch.optim as optim from matplotlib import pyplot as plt
1 2 3 4 5 6 7 8 9 10 11
# 读入数据并进行数据处理 data = pd.read_csv('bikes.csv') col_titles = ['season', 'weathersit', 'mnth', 'hr', 'weekday'] for i in col_titles: dummies = pd.get_dummies(data[i], prefix=i) data = pd.concat([data, dummies], axis=1)
# 训练模型 losses = [] for i inrange(1000): batch_loss = [] for start inrange(0, len(X), batch_size): if start+batch_size<len(X): end = start+batch_size else: end = len(X)
# 生成一个batch的训练数据 x = torch.FloatTensor(X[start:end]) y = torch.FloatTensor(Y[start:end])
pred = neu(x) loss = loss_fn(pred, y) opt.zero_grad() loss.backward() opt.step() batch_loss.append(loss.data.numpy()) if i%100==0: losses.append(np.mean(batch_loss)) print(i, np.mean(batch_loss))
# 测试,验证 X = test_data.drop(['cnt'], axis=1) Y = test_data['cnt'] Y = Y.values.reshape([len(Y), 1]) X = torch.FloatTensor(X.values) Y = torch.FloatTensor(Y) pred = neu(X)
Y = Y.data.numpy()*std_cnt+mean_cnt pred = pred.data.numpy()*std_cnt+mean_cnt