1、手动实现训练集和测试集的切分
1. data_split()函数
接下来我们开始实践模型评估过程,首先是对训练集和测试集的划分,我们尝试创建一个切分训练集和测试集的函数。
def data_split(features, labels, rate=0.7):
"""
训练集和测试集切分函数
:param features: 输入的特征张量
:param labels:输入的标签张量
:param rate:训练集占所有数据的比例
:return Xtrain, Xtest, ytrain, ytest:返回特征张量的训练集、测试集,以及标签张量的训练集、测试集
"""
num_examples = len(features) # 总数据量
indices = list(range(num_examples)) # 数据集行索引
random.shuffle(indices) # 乱序调整
num_train = int(num_examples * rate) # 训练集数量
indices_train = torch.tensor(indices[: num_train]) # 在已经乱序的的indices中挑出前num_train数量的行索引值
indices_test = torch.tensor(indices[num_train: ])
Xtrain = features[indices_train] # 训练集特征
ytrain = labels[indices_train] # 训练集标签
Xtest = features[indices_test] # 测试集特征
ytest = labels[indices_test] # 测试集标签
return Xtrain, Xtest, ytrain, ytest
- 测试函数性能
features = torch.arange(10) # 创建特征0-9
features
labels = torch.arange(1, 11) # 创建标签1-10,保持和特征+1的关系
labels
data_split(features, labels)
- 实验结果:
#f
tensor([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
#l
tensor([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
#fs
(tensor([2, 6, 3, 0, 7, 5, 9]),
tensor([1, 8, 4]),
#ls
tensor([ 3, 7, 4, 1, 8, 6, 10]),
tensor([2, 9, 5]))
2. 实践练习
尝试带入训练集进行建模,利用测试集评估模型建模效果
# 设置随机数种子
torch.manual_seed(420)
# 生成回归类数据集
features, labels = tensorGenReg()
# 切分训练集和测试集
Xtrain, Xtest, ytrain, ytest = data_split(features, labels)
# 初始化核心参数
batch_size = 10 # 小批的数量
lr = 0.03 # 学习率
num_epochs = 5 # 训练过程遍历几次数据
w = torch.zeros(3, 1, requires_grad = True) # 随机设置初始权重
# 2、模型构建
def linreg(X,w):
return torch.mm(X, w)
# 3、损失函数 mse
def MSE_loss(yhat, y):
total = y.numel()
sse = torch.sum((yhat.reshape(-1, 1) - y.reshape(-1, 1)) ** 2)
return sse / total
# 4、优化算法
def sgd(params, lr):
params.data -= lr * params.grad # (参数-学习率lr * 梯度)
params.grad.zero_()
# 5、训练模型
# 参与训练的模型方程
net = linreg # 使用回归方程
loss = MSE_loss # 均方误差的一半作为损失函数
# 模型训练过程
for epoch in range(num_epochs):
for X, y in data_iter(batch_siz