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()

@浙大疏锦行

相关推荐
2zcode2 小时前
项目文档:基于MATLAB神经网络的心力衰竭预测与临床辅助决策系统研究
开发语言·神经网络·matlab·心力衰竭预测\
LaughingZhu3 小时前
Product Hunt 每日热榜 | 2026-07-27
人工智能·深度学习·神经网络·搜索引擎·产品运营
万里鹏程转瞬至4 小时前
论文简读:Boogu-Image 图像生成与编辑模型
论文阅读·深度学习·aigc
JackHCC5 小时前
Meta-SlimPer:固定知识库重构个性化排序
人工智能·机器学习·重构
虹科网络安全5 小时前
“顶会”看安全(十六):深入分析函数内联及其对基于机器学习的二进制分析的安全影响
人工智能·安全·机器学习
SimpleLearingAI6 小时前
DiT:Diffusion Transformer原理简介
人工智能·深度学习·transformer
满怀冰雪6 小时前
08-Paddle 神经网络层入门:Linear、激活函数与 Sequential
神经网络·机器学习·paddle
phltxy6 小时前
LangChain_Agent中间件实战
人工智能·python·深度学习·语言模型·中间件·langchain
谁看我谁 狼家二丫7 小时前
机器学习漫游(1) 基本设定
人工智能·机器学习
workflower7 小时前
从幻觉,到现实
人工智能·深度学习·机器学习·设计模式·机器人