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

相关推荐
竹子_233 分钟前
《零基础入门AI:深度学习之NLP基础学习》
人工智能·python·深度学习·自然语言处理
旦莫37 分钟前
MTSC2025参会感悟:AI 驱动的测试用例生成
人工智能·python·测试开发·测试用例·ai测试·mtsc2025
im_AMBER1 小时前
学习日志39 python
开发语言·python·学习
农场主John1 小时前
(栈)Leetcode155最小栈+739每日温度
windows·python·算法·leetcode·
Goona_2 小时前
PyQt多窗口应用开发:构建完整的可二次开发用户登录注册模板
python·小程序·excel·pyqt
山烛2 小时前
OpenCV图像形态学操作
图像处理·人工智能·python·opencv·计算机视觉·图像形态学
Q_Q5110082852 小时前
python的校园研招网系统
开发语言·spring boot·python·django·flask·node.js·php
AI_RSER3 小时前
遥感&机器学习入门实战教程|Sklearn 案例④ :多分类器对比(SVM / RF / kNN / Logistic...)
python·算法·机器学习·支持向量机·分类·sklearn
于越海3 小时前
Python工程师向项目管理转型的深度分析与学习道路规划
笔记·python·学习