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

相关推荐
l1t7 分钟前
JIT执行python脚本的工具codon安装和测试
开发语言·python
2501_9010064733 分钟前
Golang怎么用gRPC Gateway_Golang gRPC Gateway教程【经典】
jvm·数据库·python
2501_9012005334 分钟前
golang如何实现错误预算Error Budget计算_golang错误预算Error Budget计算实现实战
jvm·数据库·python
2401_867623981 小时前
如何解决OUI图形界面无法调用_xhost与DISPLAY变量设置
jvm·数据库·python
Dxy12393102161 小时前
Python 去除 HTML 标签获取纯文本
开发语言·python·html
2401_824697661 小时前
CSS如何实现元素反转特效_使用transform-scaleX(-1)操作
jvm·数据库·python
CLX05051 小时前
如何在 WordPress AMP 网站中为特定模板禁用 AMP 渲染
jvm·数据库·python
砚底藏山河1 小时前
python、JavaScript 、JAVA,定制化数据服务,助力业务高效落地
java·javascript·python
神明9311 小时前
如何实现SQL动态字段选择查询_利用反射或动态拼接字符串
jvm·数据库·python
洛的地理研学1 小时前
Python下载并处理MOD13A3植被指数数据
开发语言·python