Python学习Day34

学习来源:@浙大疏锦行

优化耗时:

import torch

import torch.nn as nn

import torch.optim as optim

from sklearn.datasets import load_iris

from sklearn.model_selection import train_test_split

from sklearn.preprocessing import MinMaxScaler

import time

import matplotlib.pyplot as plt

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

print(f"使用设备: {device}")

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)

scaler = MinMaxScaler()

X_train = scaler.fit_transform(X_train)

X_test = scaler.transform(X_test)

X_train = torch.FloatTensor(X_train).to(device)

y_train = torch.LongTensor(y_train).to(device)

X_test = torch.FloatTensor(X_test).to(device)

y_test = torch.LongTensor(y_test).to(device)

class MLP(nn.Module):

def init(self):

super(MLP, self).init()

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().to(device)

criterion = nn.CrossEntropyLoss()

optimizer = optim.SGD(model.parameters(), lr=0.01)

num_epochs = 20000

losses = []

start_time = time.time()

for epoch in range(num_epochs):

outputs = model(X_train)

loss = criterion(outputs, y_train)

optimizer.zero_grad()

loss.backward()

optimizer.step()

if (epoch + 1) % 200 == 0:

losses.append(loss.item())

print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}')

if (epoch + 1) % 100 == 0:

print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}')

time_all = time.time() - start_time

print(f'Training time: {time_all:.2f} seconds')

plt.plot(range(len(losses)), losses)

plt.xlabel('Epoch')

plt.ylabel('Loss')

plt.title('Training Loss over Epochs')​​​​​​​​​​​@​

plt.show()

相关推荐
乔巴先生242 小时前
LLMCompiler:基于LangGraph的并行化Agent架构高效实现
人工智能·python·langchain·人机交互
张子夜 iiii3 小时前
实战项目-----Python+OpenCV 实现对视频的椒盐噪声注入与实时平滑还原”
开发语言·python·opencv·计算机视觉
困鲲鲲5 小时前
Flask 核心基础:从 路由装饰器 到 __name__ 变量 的底层逻辑解析
python·flask
njxiejing5 小时前
Python NumPy安装、导入与入门
开发语言·python·numpy
Rhys..5 小时前
Python&Flask 使用 DBUtils 创建通用连接池
开发语言·python·mysql
Just_Paranoid5 小时前
【Python Tkinter】图形用户界面(GUI)开发及打包EXE指南
python·gui·tkinter·pyinstaller
小宁爱Python6 小时前
Django 基础入门:命令、结构与核心配置全解析
后端·python·django
闲人编程7 小时前
Flask 前后端分离架构实现支付宝电脑网站支付功能
python·架构·flask·支付宝·前后端·网站支付·apl
996终结者7 小时前
同类软件对比(四):Jupyter vs PyCharm vs VS Code:Python开发工具终极选择指南
vscode·python·jupyter·pycharm·visual studio code
果壳~7 小时前
【Python】爬虫html提取内容基础,bs4
爬虫·python·html