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()
相关推荐
Joy T2 小时前
Spring Security 从 Acegi 到 AI Agent——JWT、角色鉴权与异步任务安全实战
人工智能·安全·spring·spring security·json web token·securitycontext·多次鉴权
AIHR数智引擎3 小时前
拆掉“关键人依赖”:黄仁勋复职全员会上的四道组织切口
人工智能·经验分享·职场和发展·ai-native·英伟达·aihr
Flynn Liang3 小时前
全栈实战:从零搭建一套可落地的生产级 AI 智能体系统(Redis 版)
人工智能·redis·ai agent
小九九的爸爸3 小时前
为了收第一笔钱,我终于打通OPC支付链路
人工智能·程序员·全栈
kyriewen3 小时前
我写的 12 个 AI Skill,三个月后 8 个在吃空饷
javascript·人工智能·程序员
陆枫Larry3 小时前
MCP 实践(二):让自己开发的 MCP Server 调用真实 HTTP 接口
人工智能
阿里云大数据AI技术3 小时前
从空间圈选到区域决策:EMR Serverless StarRocks(Stella)的 GIS 架构与空间索引实践
人工智能
掘金酱4 小时前
X-Lab 年度大会线上同步活动 | 带上你的 AI 作品,来 X-Lab 年度大会聊聊 AI 新生意!
人工智能
阿里云大数据AI技术4 小时前
Hologres 长记忆服务发布知识库:好记性,也要懂业务
人工智能
AllData公司负责人4 小时前
实战二:AllData大模型与AI数据底座-数据传输平台-DBSyncer,搭建 Http 接口同步至 Doris,API 业务数据自动拉取入数仓
大数据·数据库·数据仓库·人工智能·算法·http·doris