PyTorch-MLP垃圾邮件分类

import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler,MinMaxScaler
from sklearn.model_selection import train_test_split#划分训练集和测试集
from sklearn.metrics import accuracy_score,confusion_matrix,classification_report #模型评估
from sklearn.manifold import TSNE#数据降维 可视化
import torch
import torch.nn as nn
from torch.optim import SGD,Adam
import torch.utils.data as Data
import matplotlib.pyplot as plt
import seaborn as sns
import hiddenlayer as hl
#垃圾邮件分类
spam=pd.read_csv("Data/spambase.csv")
# print(spam.head()) 57个特征向量 1个标签 最后一列
# print(spam.describe())
print(pd.value_counts(spam.label))
'''
0    2788
1    1813
Name: label, dtype: int64
'''
#划分测试集和训练集
X=spam.iloc[:,0:57].values
y=spam.label.values
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.25,random_state=123)
#标准化处理
scales=MinMaxScaler(feature_range=(0,1))
X_train_s=scales.fit_transform(X_train)
X_test_s=scales.fit_transform(X_test)
# #箱线图表示
# colname=spam.columns.values[:-1]
# plt.figure(figsize=(20,14))
# for ii in range(len(colname)):
#     plt.subplot(7,9,ii+1)
#     sns.boxplot(x=y_train,y=X_train_s[:,ii])
#     plt.title(colname[ii])
# plt.subplots_adjust(hspace=0.5)
# plt.show()
#全连接神经网络
class MLPclassifica(nn.Module):
    def __init__(self):
        super(MLPclassifica,self).__init__()
        #定义第一个隐藏层
        self.hidden1=nn.Sequential(
            nn.Linear(
                in_features=57,#第一个隐藏层的输入,数据的特征数
                out_features=30,#第一个隐藏层的输出,神经元的数量
                bias=True,#默认设置偏置项
            ),
            nn.ReLU()
        )
        #定义第二个隐藏层
        self.hidden2=nn.Sequential(
            nn.Linear(30,10),#10个神经元
            nn.ReLU()
        )
        #分类层 二分类
        self.classifica=nn.Sequential(
            nn.Linear(10,2),#两个神经元
            nn.Sigmoid()
        )
    def forward(self,x):
        fc1=self.hidden1(x)
        fc2=self.hidden2(fc1)
        output=self.classifica(fc2)
        return fc1,fc2,output
#网络模型可视化
MyConvnet=MLPclassifica()
print(MyConvnet)
#hiddenlayer可视化
import  hiddenlayer as hl
from graphviz import Digraph
hl_graph=hl.build_graph(MyConvnet,torch.zeros([1,57]))
hl_graph.theme=hl.graph.THEMES["blue"].copy()
#将可视化的网络保存为图片
hl_graph.save("Data/MLPclassifica_hl.png",format="png")
#模型训练
X_train_t=torch.from_numpy(X_train_s.astype(np.float32))
y_train_t=torch.from_numpy(y_train.astype(np.int64))
X_test_t=torch.from_numpy(X_test_s.astype(np.float32))
y_test_t=torch.from_numpy(y_test.astype(np.int64))
#将训练集转化为张量后,使用TensorDataset将x y整合
train_data=Data.TensorDataset(X_train_t,y_train_t)
train_loader=Data.DataLoader(
    dataset=train_data,
    batch_size=64,
    shuffle=True,
    num_workers=0,
)
#定义优化器
optimizer=torch.optim.Adam(MyConvnet.parameters(),lr=0.01)
loss_func=nn.CrossEntropyLoss()#交叉熵损失函数
history1=hl.History()#保存训练过程的指标
canvas1=hl.Canvas()#可视化训练过程
print_step=25
for epoch in range(25):
    for step,(b_x,b_y) in enumerate(train_loader):
        _,_,output=MyConvnet(b_x)
        train_loss=loss_func(output,b_y)
        optimizer.zero_grad()
        train_loss.backward()
        optimizer.step()
        niter=epoch*len(train_loader)+step+1
        if niter%print_step==0:
            _, _, output = MyConvnet(X_test_t)
            _,pre_lab=torch.max(output,1)
            test_accuracy=accuracy_score(y_test_t,pre_lab)
            history1.log(niter,train_loss=train_loss,test_accuracy=test_accuracy)
            with canvas1:
                canvas1.draw_plot(history1["train_loss"])
                canvas1.draw_plot(history1["test_accuracy"])
_,_,output=MyConvnet(X_test_t)
_, pre_lab = torch.max(output, 1)
test_accuracy = accuracy_score(y_test_t, pre_lab)
print("test_accuracy:",test_accuracy)

在这里插入图片描述
在这里插入图片描述

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 15
    评论
PyTorch-MNIST-MLP是一个使用PyTorch库和多层感知器(MLP)来训练和测试MNIST手写数字数据集的项目。 MNIST是一个经典的手写数字识别数据集,包含了大量的手写数字图片和对应的标签。通过训练一个模型,我们可以实现自动识别手写数字的功能。 MLP是一种基本的人工神经网络模型,包含了多个全连接的神经网络层,并且每个神经元都与相邻层的所有神经元连接。通过多层的非线性变换和权重调整,MLP可以处理复杂的分类和回归任务。 PyTorch是一个开源的机器学习框架,提供了丰富的工具和函数来简化神经网络模型的构建和训练过程。通过PyTorch,我们可以轻松地搭建和训练MLP模型,并在MNIST数据集上进行实验。 在PyTorch-MNIST-MLP项目中,我们首先加载MNIST数据集,并将其转换成适合MLP模型的格式。然后,我们定义MLP模型的结构,包括输入层、隐藏层和输出层,并使用PyTorch提供的函数来定义损失函数和优化器。 接下来,我们使用训练数据集对MLP模型进行训练,通过反向传播算法和优化器来逐步调整模型的权重和偏置。在训练过程中,我们可以监控模型的精确度和损失值,以评估模型的性能。 最后,我们使用测试数据集对训练好的模型进行测试,并计算模型在测试集上的准确率。通过比较预测结果和真实标签,我们可以评估模型在手写数字识别任务上的表现。 总之,PyTorch-MNIST-MLP是一个基于PyTorch库和MLP模型的项目,用于训练和测试MNIST手写数字数据集。通过该项目,我们可以学习和掌握使用PyTorch构建神经网络模型的基本方法,并实现手写数字识别的功能。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值