多分類問題 手寫數字 pytorch

2021-10-18 17:28:33 字數 2732 閱讀 7301

# 手寫數字識別

import torch

# 資料集處理

from torchvision import transforms

from torchvision import datasets

from torch.utils.data import dataloader

# 函式 啟用函式等

import torch.nn.functional as f

# 優化器包

import torch.optim as optim

# 分批

batch_size = 64

# 1. 資料處理

transform = transforms.compose([

transforms.totensor(),

transforms.normalize((0.1307, ), (0.3081, ))

])train_dataset = datasets.mnist(root='../dataset/mnist/',

train=true,

download=true,

transform=transform)

test_dataset = datasets.mnist(root='../dataset/mnist/',

train=false,

download=true,

transform=transform)

train_loader = dataloader(test_dataset,

shuffle=true,

batch_size=batch_size)

test_loader = dataloader(test_dataset,

shuffle=false,

batch_size=batch_size)

# 資料為1 * 28 * 28

# 2. 建立模型

class net(torch.nn.module):

def __init__(self):

super(net, self).__init__()

self.l1 = torch.nn.linear(784, 512)

self.l2 = torch.nn.linear(512, 256)

self.l3 = torch.nn.linear(256, 128)

self.l4 = torch.nn.linear(128, 64)

self.l5 = torch.nn.linear(64, 10)

def forward(self, x):

x = x.view(-1, 784)

x = f.relu(self.l1(x))

x = f.relu(self.l2(x))

x = f.relu(self.l3(x))

x = f.relu(self.l4(x))

return self.l5(x)

model = net()

# 3.損失函式和優化器 交叉熵損失

criterion = torch.nn.crossentropyloss()

optimizer = optim.sgd(model.parameters(), lr=0.01, momentum=0.5)

# 4.迴圈訓練

def train(epoch):

running_loss = 0.0

for batch_idx, data in enumerate(train_loader):

inputs, target = data

optimizer.zero_grad()

outputs = model(inputs)

loss = criterion(outputs, target)

loss.backward()

optimizer.step()

running_loss += loss.item()

print(batch_idx% 300)

if batch_idx % 300 == 0:

print('[%d,%d] loss: %.10f' % (epoch+1, batch_idx+1, running_loss / 300))

running_loss = 0.0

# 測試驗證

def test():

correct = 0

total = 0

with torch.no_grad(): # 不會再進行梯度

for data in test_loader:

images, labels = data

outputs = model(images)

_, predicted = torch.max(outputs.data, dim=1)

total+=labels.size(0)

correct+=(predicted==labels).sum().item()

print("accuracy on test set: %d %%" % (100 * correct / total))

# 程式入口處

if __name__ == '__main__':

for epoch in range(200):

train(epoch)

test()

print("訓練結束...")

存在的問題, 因為全連線, 可能會存在過擬合;

Tensorflow 多分類問題

import requests import numpy as np 複製 r requests.get 複製 with open iris.data w as f f.write r.text 複製 import pandas as pd 複製 data pd.read csv iris.data...

XGBoost解決多分類問題

xgboost官方給的二分類問題的例子是區別蘑菇有無毒,資料集和 都可以在xgboost中的demo資料夾對應找到,我是用的anaconda安裝的xgboost,實現起來比較容易。唯一的梗就是在終端中執行所給命令 xgboost mushroom.conf 時會報錯,是路徑設定的問題,所以我乾脆把x...

手寫數字問題

import osos.environ tf cpp min log level 2 使tensorflow少列印一些不必要的資訊 import tensorflow.compat.v1 as tf from tensorflow import keras from tensorflow.keras...