【深度学习】鸢尾花分类

3 实验步骤

  1. 数据准备

我们首先收集了关于鸢尾花的数据集,包括花萼长度、花萼宽度、花瓣长度和花瓣宽度等特征,并针对每个样本标注了其所属的鸢尾花品种。然后,我们对数据进行了预处理,包括数据的归一化和划分为训练集和测试集。

        2.模型设计

我们选择了一个神经网络模型来解决这个分类问题。模型由输入层、多个隐藏层和输出层组成。每个隐藏层都使用了激活函数来引入非线性性质。最后的输出层使用了softmax函数,将输出转化为每个类别的概率分布。

        3.模型训练

在模型训练阶段,我们使用了交叉熵损失函数作为我们的损失函数,并选择了随机梯度下降(SGD)作为优化器。我们将训练集输入模型进行前向传播,计算损失,并通过反向传播更新模型的参数。这个过程重复进行多个epoch,直到模型收敛。

        4.模型评估

在模型训练完成后,我们使用测试集对模型进行评估。通过将测试集输入模型进行前向传播,我们获得了模型对于每个样本的预测结果。然后,我们将预测结果与真实标签进行比较,并计算分类准确率来评估模型的性能。

        5.实验代码

import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
from torch.utils.data import DataLoader, Dataset

torch.set_default_tensor_type(torch.DoubleTensor)

# 加载数据
iris = load_iris()
X = iris.data
Y = iris.target

# 划分训练集和测试集
train_X, test_X, train_y, test_y = train_test_split(X, Y, test_size=0.3, random_state=2022)

# 转换为Tensor
train_X = torch.from_numpy(train_X)
test_X = torch.from_numpy(test_X)
train_y = torch.from_numpy(train_y).long()
test_y = torch.from_numpy(test_y).long()

class IrisDataset(Dataset):
    def __init__(self):
        self.x = train_X
        self.y = train_y
        self.len = self.x.shape[0]

    def __getitem__(self, index):
        return self.x[index], self.y[index]

    def __len__(self):
        return self.len

# 创建DataLoader
data_set = IrisDataset()
trainloader = DataLoader(dataset=data_set, batch_size=64)
print(data_set.x.shape, data_set.y.shape)

class Net(nn.Module):
    def __init__(self, input_dim, hidden_dim, output_dim):
        super(Net, self).__init__()
        self.linear1 = nn.Linear(input_dim, hidden_dim)
        self.linear2 = nn.Linear(hidden_dim, 10)
        self.linear3 = nn.Linear(10, output_dim)

    def forward(self, x):
        x = torch.sigmoid(self.linear1(x))
        x = torch.sigmoid(self.linear2(x))
        x = self.linear3(x)
        return x

# 定义模型、损失函数和优化器
input_dim = 4
hidden_dim = 30
output_dim = 3

model = Net(input_dim, hidden_dim, output_dim)
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.005)

# 训练模型
n_epochs = 1001
loss_list = []

for epoch in range(n_epochs):
    loss_sum = 0.0
    for x, y in trainloader:
        optimizer.zero_grad()
        pred = model(x)
        loss = loss_fn(pred, y)
        loss.backward()
        optimizer.step()
        loss_sum += loss.item()

    loss_list.append(loss_sum / len(trainloader))
    
    if epoch % 100 == 0:
        print('Epoch {}, Loss {}'.format(epoch, loss_list[epoch]))

# 保存模型
torch.save(model.state_dict(), 'Model.path')

# 绘制损失图
import matplotlib.pyplot as plt

draw_loss = [loss_list[i] for i in range(n_epochs) if i % 100 == 0]
x = list(range(0, n_epochs, 100))

plt.plot(x, draw_loss)
plt.xlabel("Epoch")
plt.ylabel("Loss")
plt.show()

# 加载模型
model = Net(input_dim, hidden_dim, output_dim)
model.load_state_dict(torch.load('Model.path'))
model.eval()

# 预测并计算准确率
out = model(test_X)
_, prediction = torch.max(out, 1)
pred_y = prediction.data.numpy()
target_y = test_y.data.numpy()

accuracy = float((pred_y == target_y).astype(int).sum()) / float(target_y.size)
print("Iris classification accuracy:", accuracy)

5 总结

        PyTorch是一个强大的深度学习框架,提供了丰富的工具和函数,方便我们构建和训练神经网络模型。

        在解决分类问题时,合适的模型设计是关键。选择适当的网络结构和激活函数能够帮助模型更好地学习数据的特征。

        模型训练的过程中,选择合适的损失函数和优化器对模型的性能有很大影响。交叉熵损失函数和随机梯度下降优化器是常见且有效的选择。

        在模型评估时,分类准确率是常用的性能指标,但在实验评估时,除了分类准确率,还可以考虑其他指标,如精确率、召回率和F1分数等,特别是在不平衡数据集或有重要类别的情况下。

        数据预处理对模型的性能也有一定影响。在本实验中,我们对数据进行了归一化处理,以确保不同特征之间的数值范围相似,避免某些特征对模型训练的影响过大。

        本实验仅针对鸢尾花数据集进行了三分类问题的处理,但这个方法可以扩展到其他多分类问题中。通过收集更多的数据和调整模型结构,可以处理更复杂的分类任务。

        总的来说,通过本实验,学习了如何使用PyTorch构建一个神经网络模型来解决基础的三分类问题。了解了模型的设计、训练和评估过程,并了解了一些关键的深度学习概念和技术。这个实验为进一步探索和解决更复杂的分类问题奠定了基础。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值