DAY33 简单的神经网络

@浙大疏锦行

手敲复现了一下文档的代码

python 复制代码
import torch
torch.cuda

if torch.cuda.is_available():
    print("CUDA可用!")
    device_count=torch.cuda.device_count()
    print(f"可用的CUDA设备数量:{device_count}")

    current_device=torch.cuda.current_device()
    print(f"当前使用的CUDA设备索引:{current_device}")

    device_name=torch.cuda.get_device_name(current_device)
    print(f"当前CUDA设备的名称:{device_name}")

    cuda_version=torch.cuda.get_device_name(current_device)
    print(f"当前CUDA设备的名称:{device_name}")

    cuda_version=torch.version.cuda
    print(f"CUDA版本:{cuda_version}")

else:
    print("CUDA不可用。")
python 复制代码
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
import numpy as np

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)

print(X_train.shape)
print(y_train.shape)
print(X_test.shape)
print(y_test.shape)
python 复制代码
from sklearn.preprocessing import MinMaxScaler
scaler=MinMaxScaler()
X_train=scaler.fit_transform(X_train)
X_test=scaler.transform(X_test)

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


import torch
import torch.nn as nn
import torch.optim

class MLP(nn.Module):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        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 = torch.optim.SGD(model.parameters(), lr=0.01)
python 复制代码
num_epochs=20000
losses=[]
for epoch in range(num_epochs):
    outputs=model.forward(X_train)
    loss=criterion(outputs,y_train)# 预测损失

    # 反向传播和优化
    optimizer.zero_grad()
    loss.backward() # 反向传播计算梯度 
    optimizer.step() 

    losses.append(loss.item())

    if(epoch+1)%100==0:
        print(f'Epoch[{epoch+1}/{num_epochs}],Loss:{loss.item():.4f}')
python 复制代码
import matplotlib.pyplot as plt
plt.plot(range(num_epochs),losses)
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.title('Training Loss over Epochs')
plt.show()
相关推荐
system_error_x7 分钟前
MCP协议开发实战:从零搭建AI Agent工具链
人工智能
Sayai14 分钟前
ComfyUI+混元视频实战:12G 显存跑 13G 模型,5 分钟出片(国产开源,附模型与工作流)
人工智能·aigc·音视频·comfyui·hunyuanvideo·混元视频
燧机科技SuiJi21 分钟前
山体坍塌落石滑坡泥石流监测系统 落石泥石流监控摄像机
大数据·人工智能·深度学习·yolo
国科安芯42 分钟前
立方星与微纳卫星综合电子微型化趋势下的抗辐射MCU选型综述
人工智能·单片机·嵌入式硬件·mcu·risc-v·抗辐射
诸神缄默不语1 小时前
小春学习日刊 2026年第4期:2026.10.16
人工智能
draracle1 小时前
为什么 AI 无法胜任系统架构
人工智能·系统架构
未来和明天2 小时前
iLeadE-3403边缘计算网关10.4 TOPS数据采集、视频接入与外设扩展等多元化应用需求
人工智能·边缘计算
youngfengying2 小时前
集成学习及置信度
人工智能·机器学习
火山引擎开发者社区2 小时前
1000次专业数据集调用,这次我们免费送!
人工智能