import numpy as np
from sklearn.model_selection import train_test_split
from sklearn import datasets
import torch
import torch.nn.functional as Fun
import torch.nn as nn
dataset = datasets.load_iris()
X = dataset['data']
Y = dataset['target']
# (训练数据,测试数据,训练标签,测试标签)
input,x_test,label,y_test = train_test_split(X,Y,test_size=0.2,random_state=10)
input = torch.FloatTensor(input)
label = torch.LongTensor(label)
x_test = torch.FloatTensor(x_test)
y_test = torch.LongTensor(y_test)
class Net(nn.Module):
def __init__(self,n_feature,n_hidden,n_output):
super(Net,self).__init__()
self.hidden = nn.Linear(n_feature,n_hidden)
self.out = nn.Linear(n_hidden,n_output)
def forward(self,x):
x = Fun.relu(self.hidden(x))
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.01)
loss_fc = torch.nn.CrossEntropyLoss()
epocnum = 2000
for epoch in range(epocnum):
y_pred = net(input)
loss = loss_fc(y_pred,label)
optimizer.zero_grad()
loss.backward()
optimizer.step()
#测试训练集准确率
out = net(input)
out_pred = torch.max(out,1)[1]
y_pred = out_pred.numpy()
y_label = label.numpy()
accuracy = float((y_pred == y_label).astype(int).sum()/float(y_label.size))
print('训练准确率:{}%'.format(accuracy*100))
#测试测试集准确率
out_test = net(x_test)
out_test_pred = torch.max(out_test,1)[1]
y_test_pred = out_test_pred.numpy()
y_test_label = y_test.numpy()
accuracy_test = float((y_test_pred == y_test_label).astype(int).sum()/float(y_test_label.size))
print("测试准确率:{}%".format(accuracy_test*100))
[鸢尾花数据集BP分类]
最新推荐文章于 2024-05-03 11:07:56 发布