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

相关推荐
nbsaas-boot2 小时前
Java 正则表达式白皮书:语法详解、工程实践与常用表达式库
开发语言·python·mysql
仗剑_走天涯2 小时前
基于pytorch.nn模块实现线性模型
人工智能·pytorch·python·深度学习
chao_7892 小时前
二分查找篇——搜索旋转排序数组【LeetCode】两次二分查找
开发语言·数据结构·python·算法·leetcode
chao_7896 小时前
二分查找篇——搜索旋转排序数组【LeetCode】一次二分查找
数据结构·python·算法·leetcode·二分查找
烛阴7 小时前
Python装饰器解除:如何让被装饰的函数重获自由?
前端·python
noravinsc7 小时前
django 一个表中包括id和parentid,如何通过parentid找到全部父爷id
python·django·sqlite
ajassi20007 小时前
开源 python 应用 开发(三)python语法介绍
linux·python·开源·自动化
沉默媛8 小时前
如何安装python以及jupyter notebook
开发语言·python·jupyter
Deng9452013149 小时前
基于Python的旅游数据可视化应用
python·numpy·pandas·旅游·数据可视化技术
2401_878624799 小时前
pytorch 自动微分
人工智能·pytorch·python·机器学习