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()
相关推荐
NutShell Wang几秒前
「音画同生」时代开启:2026 年 8 月 AI 视频生成四大发布复盘
人工智能·开源·aigc·ai agent·智能体·vibe coding
正在走向自律8 分钟前
WorkBuddy AI工具使用介绍完全指南
人工智能·爬虫·ai编程·workbuddy·ai的力量
EasyGBS11 分钟前
告别“通用AI”的三大痛点:国标GB28181公网平台EasyGBS+DLTM让企业拥有专属AI安防大脑
人工智能·深度学习·机器学习
爱分享的康康11 分钟前
解锁路测数据价值|康谋自动驾驶采集‑分析全链路方案解读
人工智能·数码相机·自动驾驶
链上日记29 分钟前
WEEX TradFi交易边界正在消失
人工智能
ctlover31 分钟前
AI应用项目开发源码级教程:AI智能伴侣
人工智能
jonyleek34 分钟前
JVS-Logic 实践指南:基于私有化与柔性配置的企业级逻辑引擎落地方法
人工智能·低代码·私有化部署·企业集成·逻辑引擎·流程编排·jvs
诗句藏于尽头35 分钟前
deepseek harness对接商汤科技免费大模型使用教程
人工智能·科技·学习
兰亭妙微UI设计公司39 分钟前
兰亭妙微用户体验公司分享:《AI 体验设计》第 3 部分:指导原则
人工智能
阿萨德528号39 分钟前
DeepSeek Harness 开源了,但先别叫“正式版”:从封闭内测到 Developer Preview,只隔了两周
人工智能·deepseek·harness