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博客6 小时前
腾讯王炸:CodeMoment - 全球首个产设研一体 AI IDE
ide·人工智能
中达瑞和-高光谱·多光谱6 小时前
中达瑞和LCTF:精准调控光谱,赋能显微成像新突破
人工智能
mahtengdbb16 小时前
【目标检测实战】基于YOLOv8-DynamicHGNetV2的猪面部检测系统搭建与优化
人工智能·yolo·目标检测
Pyeako6 小时前
深度学习--BP神经网络&梯度下降&损失函数
人工智能·python·深度学习·bp神经网络·损失函数·梯度下降·正则化惩罚
清 澜7 小时前
大模型面试400问第一部分第一章
人工智能·大模型·大模型面试
哥布林学者7 小时前
吴恩达深度学习课程五:自然语言处理 第二周:词嵌入(四)分层 softmax 和负采样
深度学习·ai
不大姐姐AI智能体7 小时前
搭了个小红书笔记自动生产线,一句话生成图文,一键发布,支持手机端、电脑端发布
人工智能·经验分享·笔记·矩阵·aigc
虹科网络安全7 小时前
艾体宝方案 | 释放数据潜能 · 构建 AI 驱动的自动驾驶实时数据处理与智能筛选平台
人工智能·机器学习·自动驾驶
Deepoch8 小时前
Deepoc数学大模型:发动机行业的算法引擎
人工智能·算法·机器人·发动机·deepoc·发动机行业