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()

相关推荐
Q_Q19632884758 分钟前
python+uniapp基于微信小程序的高校二手商品交易系统
spring boot·python·微信小程序·django·flask·uni-app·node.js
k***a4291 小时前
Python 中设置布尔值参数为 True 来启用验证
开发语言·windows·python
云霄IT1 小时前
python之使用cv2.matchTemplate识别缺口滑块验证码---实现最佳图像匹配
python·opencv·计算机视觉
BenjaminQA2 小时前
Python OpenCV 模板匹配的一些应用场景和方法思考,浅析KAZE特征匹配对比
python·opencv·kaza·图片匹配·airtest ui自动化
逆羽飘扬4 小时前
【JupyterLab集成】GPU性能监控可视化组件
人工智能·python·jupyter·gpu监控
love530love5 小时前
【笔记】解决部署国产AI Agent 开源项目 MiniMax-M1时 Hugging Face 模型下载缓存占满 C 盘问题:更改缓存位置全流程
开发语言·人工智能·windows·笔记·python·缓存·uv
狐凄5 小时前
Python实例题:基于 Apache Kafka 的实时数据流处理平台
开发语言·python
Jooolin5 小时前
【Python】Python可以用来做游戏吗?
python·ai编程·游戏开发
MarkGosling5 小时前
【开源项目】免费且本地运行:用 DeepEval 测测你的大模型接口有没有缩水
人工智能·python·llm
noravinsc5 小时前
django调用 paramiko powershell 获取cpu 核数
python·django