DAY 38 MLP神经网络的训练

python 复制代码
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
import torch
import torch.nn as nn
import torch.optim as optim

iris = load_iris()
X = iris.data
y = iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

scaler = MinMaxScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

X_train = torch.FloatTensor(X_train)
X_test = torch.FloatTensor(X_test)
y_train = torch.LongTensor(y_train)
y_test = torch.LongTensor(y_test)

class MLP(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(4, 10)
        self.relu = nn.ReLU()
        self.fc2 = nn.Linear(10, 3)

    def forward(self, x):
        out = self.fc1(x)
        out = self.relu(out)
        out = self.fc2(out)
        return out
    
model = MLP()

criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)

epoches = 20000
losses = []

for epoch in range(epoches):
    outputs = model.forward(X_train)
    loss = criterion(outputs, y_train)
    losses.append(loss.item())
    
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

    if (epoch + 1) % 100 == 0:
        print(f"Epoch [{epoch + 1}/{epoches}], Loss: {loss.item():.6f}")
python 复制代码
import matplotlib.pyplot as plt

plt.figure()
plt.plot(losses)
plt.xlabel("Epoch")
plt.ylabel("Loss")
plt.title("Training Loss Curve")
plt.show()

@浙大疏锦行

相关推荐
接着奏乐接着舞。20 分钟前
机器学习经验总结整理
人工智能·机器学习
Dfreedom.1 小时前
【实战篇】图像分割-计算图中不同颜色区域的面积比
图像处理·人工智能·深度学习·计算机视觉·图像分割·otsu
handsomestWei2 小时前
scikit-learn数据预处理模块
python·机器学习·scikit-learn
计算机毕业设计指导2 小时前
基于机器学习和深度学习的恶意WebURL检测系统实战详解
人工智能·深度学习·机器学习·网络安全
w_t_y_y2 小时前
机器学习常用的python包(二)工具箱scikit-learn
python·机器学习·scikit-learn
罗西的思考2 小时前
【OpenClaw】通过 Nanobot 源码学习架构---(6)Skills
人工智能·深度学习·算法
志栋智能2 小时前
超自动化巡检:实现运维“事前预防”的关键拼图
大数据·运维·网络·人工智能·机器学习·自动化
枫叶林FYL2 小时前
【自然语言处理 NLP】7.2 红队测试与对抗鲁棒性(Red Teaming & Adversarial Robustness)
人工智能·算法·机器学习
乐园游梦记2 小时前
机器学习:监督学习与无监督学习由浅入深全解析
人工智能·深度学习·学习·机器学习
LDG_AGI2 小时前
【搜索引擎】Elasticsearch(二):基于function_score的搜索排序
数据库·人工智能·深度学习·elasticsearch·机器学习·搜索引擎·推荐算法