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()
相关推荐
AI服务老曹5 分钟前
算法任务配置完整流程:明厨亮灶项目从0到1怎么做 | AI视频分析算法实践
人工智能·算法·音视频
LUSTER凌云光7 分钟前
工业AI视觉检测系统设计:传统视觉与深度学习如何融合?
人工智能·深度学习·视觉检测
AI创界者8 分钟前
【开源实战】FaceFusionFree 5.3 部署与进阶:修复内存模式条纹 Bug 与帧率对齐逻辑解析
人工智能·aigc·音视频
huashengzsj9 分钟前
绝缘陶瓷电极材料怎么选?绝缘陶瓷电极厂家推荐
人工智能
IT_陈寒16 分钟前
JavaScript的隐式转换太坑了,我的==比较怎么就炸了?
前端·人工智能·后端
流浪00117 分钟前
大模型技术全景(四):国内外大语言模型格局,技术路线与能力图谱
人工智能·llm
今天的砖头有点烫手啊19 分钟前
Meta Muse Spark 1.3 发布:编码超 GPT-5.6,但真正的信号是“Agent 成本战“
人工智能
hans汉斯20 分钟前
【计算机科学与应用】基于联合熵驱动改进麻雀搜索优化VMD的DAS信号去噪方法
深度学习·算法·yolo·软件工程·汉斯出版社
词却24 分钟前
机器学习入门:手写数字识别与算法对比
人工智能·算法·机器学习
霸道流氓气质33 分钟前
Spring AI 多租户隔离方案
java·人工智能·spring