目錄
1、環境條件
2、代碼實現
3、總結
1、環境條件
- pycharm編譯器
- pytorch依賴
- matplotlib依賴
- numpy依賴等等
2、代碼實現
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import numpy as np# 設置設備
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")# 定義數據變換
transform = transforms.Compose([transforms.ToTensor(),transforms.Normalize((0.5,), (0.5,))
])# 加載 MNIST 數據集
trainset = torchvision.datasets.MNIST(root='./data', train=True, download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)testset = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=False)# 定義 LeNet-5 模型
class LeNet5(nn.Module):def __init__(self):super(LeNet5, self).__init__()self.conv1 = nn.Conv2d(1, 6, kernel_size=5, stride=1, padding=2)self.pool = nn.MaxPool2d(kernel_size=2, stride=2)self.conv2 = nn.Conv2d(6, 16, kernel_size=5, stride=1)self.fc1 = nn.Linear(16 * 5 * 5, 120)self.fc2 = nn.Linear(120, 84)self.fc3 = nn.Linear(84, 10)def forward(self, x):x = self.pool(torch.relu(self.conv1(x)))x = self.pool(torch.relu(self.conv2(x)))x = x.view(-1, 16 * 5 * 5)x = torch.relu(self.fc1(x))x = torch.relu(self.fc2(x))x = self.fc3(x)return x# 初始化模型、損失函數和優化器
model = LeNet5().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)# 訓練模型
epochs = 5
for epoch in range(epochs):running_loss = 0.0for i, data in enumerate(trainloader, 0):inputs, labels = datainputs, labels = inputs.to(device), labels.to(device)optimizer.zero_grad()outputs = model(inputs)loss = criterion(outputs, labels)loss.backward()optimizer.step()running_loss += loss.item()if i % 100 == 99:print(f'[Epoch {epoch + 1}, Batch {i + 1}] loss: {running_loss / 100:.3f}')running_loss = 0.0print('Finished Training')# 保存模型
torch.save(model.state_dict(), 'lenet5.pth')
print('Model saved to lenet5.pth')# 加載模型
model = LeNet5()
model.load_state_dict(torch.load('lenet5.pth'))
model.to(device)
model.eval()# 在測試集上評估模型
correct = 0
total = 0
with torch.no_grad():for data in testloader:images, labels = dataimages, labels = images.to(device), labels.to(device)outputs = model(images)_, predicted = torch.max(outputs.data, 1)total += labels.size(0)correct += (predicted == labels).sum().item()print(f'Accuracy on the test set: {100 * correct / total:.2f}%')# 加載并預處理本地圖片進行預測
from PIL import Imagedef load_and_preprocess_image(image_path):img = Image.open(image_path).convert('L') # 轉為灰度圖img = img.resize((28, 28))img = np.array(img, dtype=np.float32)img = (img / 255.0 - 0.5) / 0.5 # 歸一化到[-1, 1]img = torch.tensor(img).unsqueeze(0).unsqueeze(0) # 添加批次和通道維度return img.to(device)# 預測本地圖片
image_path = '4.png' # 替換為你的本地圖片路徑
img = load_and_preprocess_image(image_path)# 使用加載的模型進行預測
model.eval()
with torch.no_grad():outputs = model(img)_, predicted = torch.max(outputs, 1)# 打印預測結果
predicted_label = predicted.item()
print(f'預測結果: {predicted_label}')# 顯示圖片及預測結果
img_np = img.cpu().numpy().squeeze()
plt.imshow(img_np, cmap='gray')
plt.title(f'預測結果: {predicted_label}')
plt.show()
解釋:torch.save()方法完成模型的保存,image_path為本地圖片,用于測試
3、總結
????????安裝環境是比較難的點,均使用pip install 。。指令進行依賴環境的安裝,其他的比較簡單。
學習之所以會想睡覺,是因為那是夢開始的地方。
?(?ˊ?ˋ)??(開心) ?(?ˊ?ˋ)??(開心)?(?ˊ?ˋ)??(開心)?(?ˊ?ˋ)??(開心)?(?ˊ?ˋ)??(開心)
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ------不寫代碼不會凸的小劉