【10】MLP-数据划分验证数据并添加正确率

数据、代码等相关资料来源于b站日月光华老师视频,此博客作为学习记录。

在【9】中,对多层感知机的训练进行了学习,但如果还需要添加准确率的信息呢?并且,对于训练数据不错并不代表对未知数据好不好,所以还需要防止过拟合的问题。

一、划分数据集

  • 过拟合:对已知数据训练很好,但对未知数据训练很差。
  • 欠拟合:对已知数据训练不够表现不佳,对未知数据也很差。

那么需要对数据进行划分,搞一部分不参与训练,该部分数据对于模型来说可以看作未知,因此可以作为未知数据进行验证。
使用库sklearn
用以下语句可以进行调用:from sklearn.model_selection import train_test_split
返回四个值:train_x , test_x , train_y , test_y
默认把数据中的25%划分为验证数据。

值得注意的是,此时的train_x , test_x , train_y , test_y还是ndarray,需要转化成tensor再利用【9】中所学的dataset和dataloader进行数据的包装。

# 数据集的划分   sklearn
from sklearn.model_selection import train_test_split
train_x, test_x, train_y, test_y = train_test_split(X_data, Y_data)
train_x = torch.from_numpy(train_x).type(torch.float32)
train_y = torch.from_numpy(train_y).type(torch.float32)
test_x = torch.from_numpy(test_x).type(torch.float32)
test_y = torch.from_numpy(test_y).type(torch.float32)
# dataset和dataloader的包装
from torch.utils.data import TensorDataset
from torch.utils.data import DataLoader
train_ds = TensorDataset(train_x, train_y)
train_dl = DataLoader(train_ds, batch_size=batch, shuffle=True)
test_ds = TensorDataset(test_x, test_y)
test_dl = DataLoader(test_ds, batch_size=batch)    # 测试数据乱序没有意义

二、添加正确率

2.1训练代码再改进

对激活函数的部分,其实训练时没有调用可训练的参数,只是对数据进行了一个变化,那么在初始化的时候还对激活函数进行初始化是累赘且没啥用的,可以用function方法进行改进。
首先在开头导入库的部分添加:import torch.nn.functional as F,那么在后面写训练代码部分的时候在初始化的地方就不需要进行激活函数的初始化了,使用F.relu(x)就可以啦。
F相对于nn来说是一种稍低阶的方法,对激活函数这样写与原来是完全等价的。
以前的代码:

class Model(nn.Module):
    def __init__(self):
        super().__init__()   # 继承父类的所有属性
        self.linear_1 = nn.Linear(20, 64)  # 输入20列的特征(数据集决定),输出为64(假设给64个隐藏层)
        self.linear_2 = nn.Linear(64, 64)  # 接上层64输入,输出64维
        self.linear_3 = nn.Linear(64, 1)   # 因为是逻辑回归,只要一个输出
        self.relu = nn.ReLU()
        self.sigmoid = nn.Sigmoid()
    def forward(self, input):
        x = self.linear_1(input)
        x = self.relu(x)
        x = self.linear_2(x)
        x = self.relu(x)
        x = self.linear_3(x)
        x = self.sigmoid(x)
        return x

改写之后:

class Model(nn.Module):
    def __init__(self):
        super().__init__()   # 继承父类的所有属性
        self.linear_1 = nn.Linear(20, 64)  # 输入20列的特征(数据集决定),输出为64(假设给64个隐藏层)
        self.linear_2 = nn.Linear(64, 64)  # 接上层64输入,输出64维
        self.linear_3 = nn.Linear(64, 1)   # 因为是逻辑回归,只要一个输出
    def forward(self, input):
        x = F.relu(self.linear_1(input))
        x = F.relu(self.linear_2(x))
        x = F.sigmoid(self.linear_3(x))
        return x

可以看到是简洁了很多的。

2.2 添加正确率

思路:

# 正确率的计算
# type(torch.int32)将true转化为1,false转化为0,把预测的结果和0.5作比较并二分
#即把y_pred翻译成0和1
y_pred = (y_pred > 0.5).type(torch.int32)
# 那么想知道正确率的话,就是将翻译结果和label做对比
(y_pred == labels).float().mean()

代码:

def accuracy(y_pred, y_true):
    y_pred = (y_pred > 0.5).type(torch.int32)
    acc = (y_pred == y_true).float().mean()
    return acc

在打印epoch和loss的地方做更改加上对accuracy的调用:

    with torch.no_grad():
        epoch_accuracy = accuracy(model(train_x), train_y)
        epoch_loss = loss_fn(model(train_x), train_y).data
        print('epoch:', epoch,'loss:', epoch_loss.item(), 'accuracy:', epoch_accuracy.item())

这个时候,运行代码就可以看到每个epoch的loss和accuracy的变化啦。
在这里插入图片描述
再添加上test数据的loss和正确率,但是如上图结果所示,loss和accuracy的结果太长,故使用round方法仅取三位小数:

    with torch.no_grad():
        epoch_train_accuracy = accuracy(model(train_x), train_y)
        epoch_train_loss = loss_fn(model(train_x), train_y).data
        epoch_test_accuracy = accuracy(model(train_x), train_y)
        epoch_test_loss = loss_fn(model(train_x), train_y).data
        print('epoch:', epoch,'train_loss:', round(epoch_train_loss.item(),3),
                              'train_accuracy:', round(epoch_train_accuracy.item(), 3),
                              'test_loss', round(epoch_test_loss.item(), 3),
                              'test_accuracy', round(epoch_test_accuracy.item(), 3))

结果如下:
在这里插入图片描述

三、完整代码

import torch
import pandas as pd
from torch import nn
import torch.nn.functional as F
# 数据集预处理
data = pd.read_csv(r'E:\Code\pytorch\第5章\HR.csv')
data = data.join(pd.get_dummies(data.salary))
del data['salary']
data = data.join(pd.get_dummies(data.part))
del data['part']
Y_data = data.left.values.reshape(-1, 1) # left转为1维,其余自动计算
Y = torch.from_numpy(Y_data).type(torch.float32)  # 转换成tensor
# 取出除了left这一列的其他列作为X_data,data.values是转成ndarrary
X_data = data[[c for c in data.columns if c != 'left']].values
X = torch.from_numpy(X_data).type(torch.float32)
# 网络模型编写
class Model(nn.Module):
    def __init__(self):
        super().__init__()   # 继承父类的所有属性
        self.linear_1 = nn.Linear(20, 64)  # 输入20列的特征(数据集决定),输出为64(假设给64个隐藏层)
        self.linear_2 = nn.Linear(64, 64)  # 接上层64输入,输出64维
        self.linear_3 = nn.Linear(64, 1)   # 因为是逻辑回归,只要一个输出
    def forward(self, input):
        x = F.relu(self.linear_1(input))
        x = F.relu(self.linear_2(x))
        x = torch.sigmoid(self.linear_3(x))
        return x
# 定义get_model
lr = 0.0001
def get_model():
    model = Model()
    opt = torch.optim.Adam(model.parameters(), lr=lr)
    return model, opt
# 定义准确率
def accuracy(y_pred, y_true):
    y_pred = (y_pred > 0.5).type(torch.int32)
    acc = (y_pred == y_true).float().mean()
    return acc

# 数据集的划分   sklearn
batch = 64
from sklearn.model_selection import train_test_split
train_x, test_x, train_y, test_y = train_test_split(X_data, Y_data)
train_x = torch.from_numpy(train_x).type(torch.float32)
train_y = torch.from_numpy(train_y).type(torch.float32)
test_x = torch.from_numpy(test_x).type(torch.float32)
test_y = torch.from_numpy(test_y).type(torch.float32)
# dataset和dataloader的包装
from torch.utils.data import TensorDataset
from torch.utils.data import DataLoader
train_ds = TensorDataset(train_x, train_y)
train_dl = DataLoader(train_ds, batch_size=batch, shuffle=True)
test_ds = TensorDataset(test_x, test_y)
test_dl = DataLoader(test_ds, batch_size=batch) # 测试数据乱序没有意义

# 每个epoch中如何运行
model, optim = get_model()
loss_fn = nn.BCELoss()
epochs = 100

for epoch in range(epochs):
    for x, y in train_dl:         # 这样每次提供/返回一个batchsize的x和y
        y_pred = model(x)
        loss = loss_fn(y_pred, y)
        optim.zero_grad()
        loss.backward()
        optim.step()
    with torch.no_grad():
        epoch_train_accuracy = accuracy(model(train_x), train_y)
        epoch_train_loss = loss_fn(model(train_x), train_y).data
        epoch_test_accuracy = accuracy(model(train_x), train_y)
        epoch_test_loss = loss_fn(model(train_x), train_y).data
        print('epoch:', epoch,'train_loss:', round(epoch_train_loss.item(),3),
                              'train_accuracy:', round(epoch_train_accuracy.item(), 3),
                              'test_loss:', round(epoch_test_loss.item(), 3),
                              'test_accuracy:', round(epoch_test_accuracy.item(), 3))
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

要努力的小菜鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值