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()
相关推荐
柳安忆2 小时前
[GLM-4.6V 多模态能力测评】对论文pipeline图的理解能力 #视觉理解MCP、#GLM我的编码搭子
人工智能·深度学习
趁你还年轻_2 小时前
Workflow vs Agents:核心区别详解
人工智能
andwhataboutit?2 小时前
神经网络某些概念(持续更新
人工智能·深度学习·神经网络
大熊猫侯佩2 小时前
拯救发际线行动:用 Swift 和 Image Playground 驾驭 AI 绘图
人工智能·ai·文生图·swift·图生图·imageplayground·apple 智能
周杰伦_Jay2 小时前
【AutoGLM部署】本地私有化部署AI手机Agent
人工智能·智能手机
勇气要爆发2 小时前
【第一阶段—数学基础】第六章:AI数学入门:线性代数基础—变形金刚的骨架
人工智能·线性代数·机器学习
资讯雷达2 小时前
企业级DevSecOps解决方案评估:捷蛙JFrog的核心能力解析
人工智能
nwsuaf_huasir3 小时前
深度学习1.2-软件篇-Anaconda软件常见命令与使用
人工智能·深度学习
爱吃烤鸡翅的酸菜鱼3 小时前
AscendNPU IR 语法指南:核心概念速查
人工智能·ai·cann