本文針對本人學習pytorch的分類問題,自己寫了一個簡單的code
import numpy as np
from collections import Counter
from sklearn import datasets
import torch.nn.functional as Fun
from torch.autograd import Variable
import matplotlib.pyplot as plt
import torch
#數據準備
dataset = datasets.load_iris()
dataut=dataset['data']
priciple=dataset['target']
input=torch.FloatTensor(dataset['data'])
label=torch.LongTensor(dataset['target'])
#定義BP神經網絡
class Net(torch.nn.Module):
def __init__(self, n_feature, n_hidden, n_output):
super(Net, self).__init__()
self.hidden = torch.nn.Linear(n_feature, n_hidden) # hidden layer
self.out = torch.nn.Linear(n_hidden, n_output) # output layer
def forward(self, x):
x = Fun.relu(self.hidden(x)) # activation function for hidden layer we choose sigmoid
x = self.out(x)
return x
net = Net(n_feature=4, n_hidden=20, n_output=3)
optimizer = torch.optim.SGD(net.parameters(), lr=0.02) #SGD: 隨機梯度下降
loss_func = torch.nn.CrossEntropyLoss() #針對分類問題的損失函數![在這裏插入圖片描述](https://img-blog.csdnimg.cn/20190108120127973.png)
#訓練數據
for t in range(500):
out = net(input) # input x and predict based on x
loss = loss_func(out, label) # 輸出與label對比
optimizer.zero_grad() # clear gradients for next train
loss.backward() # backpropagation, compute gradients
optimizer.step() # apply gradients
out = net(input) #out是一個計算矩陣,可以用Fun.softmax(out)轉化爲概率矩陣
prediction = torch.max(out, 1)[1] # 1返回index 0返回原值
pred_y = prediction.data.numpy()
target_y = label.data.numpy()
accuracy = float((pred_y == target_y).astype(int).sum()) / float(target_y.size)
print("鶯尾花預測準確率",accuracy)