import torch
import torch.nn.functional as F
import matplotlib.pyplot as plt
torch.manual_seed(1000)
## 创建数据集
n_data = torch.ones(100, 2)
x0 = torch.normal(2*n_data, 1) # (2,2)处生成类别1数据,class0 x data (tensor), shape=(100, 2)
y0 = torch.zeros(100) # 声明类别1,class0 y data (tensor), shape=(100, 1)
x1 = torch.normal(-2*n_data, 1) # (-2,-2)处生成类别2数据,class1 x data (tensor), shape=(100, 2)
y1 = torch.ones(100) # 声明类别2,class1 y data (tensor), shape=(100, 1)
x = torch.cat((x0, x1), 0).type(torch.FloatTensor) # 合并,shape (200, 2) FloatTensor = 32-bit floating
y = torch.cat((y0, y1), ).type(torch.LongTensor) # 合并,shape (200,) LongTensor = 64-bit integer
# plt.scatter(x.numpy()[:, 0], x.numpy()[:, 1], c=y.numpy(), s=100, lw=0, cmap='RdYlGn')
# plt.show()
## 创建模型
class Net(torch.nn.Module):
def __init__(self):
super(Net, self).__init__()
self.hidden = torch.nn.Linear(2, 10)
self.out = torch.nn.Linear(10, 2)
def forward(self, x):
x = F.relu(self.hidden(x))
x = self.out(x)
return x
## 初始化网络
net = Net()
optimizer = torch.optim.SGD(net.parameters(), lr=0.02)
ce = torch.nn.CrossEntropyLoss() # 多分类使用CrossEntropyLoss()
## 进行训练
for t in range(100):
out = net(x)
loss = ce(out, y) # the target label is NOT one-hotted
optimizer.zero_grad()
loss.backward()
optimizer.step()
if t % 2 == 0:
prediction = torch.max(out, 1)[1]
pred_y = prediction.detach().numpy()
target_y = y.detach().numpy()
plt.scatter(x.detach().numpy()[:, 0], x.detach().numpy()[:, 1], c=pred_y, s=100, lw=0, cmap='RdYlGn')
accuracy = float((pred_y == target_y).astype(int).sum()) / float(target_y.size)
plt.text(1.5, -4, 'Accuracy=%.2f' % accuracy, fontdict={'size': 20, 'color': 'red'})
plt.pause(0.1)
plt.clf()
plt.show()
https://github.com/MorvanZhou/PyTorch-Tutorial/blob/master/tutorial-contents/302_classification.py