pytorch做一个分类任务

来两个圈吧

import matplotlib.pyplot as plt
from sklearn.datasets import make_circles

n_samples = 800
X, y = make_circles(n_samples=n_samples, noise=0.1, random_state=1, factor=0.6)
plt.scatter(X[:, 0], X[:, 1], c=y)

pytorch做一个分类任务_第1张图片

建立神经网络

import torch
import torch.nn.functional as F

class Net(torch.nn.Module):
    def __init__(self, n_feature, n_hidden, n_hidden2, n_output):
        super().__init__()
        self.hidden = torch.nn.Linear(n_feature, n_hidden)
        self.hidden2 = torch.nn.Linear(n_hidden, n_hidden2)
        self.out = torch.nn.Linear(n_hidden2, n_output)

    def forward(self, x):
        x = F.relu(self.hidden(x))
        x = torch.sigmoid(self.hidden2(x))
        x = self.out(x)
        x = F.softmax(x, dim=1)
        return x

net = Net(n_feature=2, n_hidden=20, n_hidden2=20, n_output=2)
print(net)

# net = torch.nn.Sequential(
#     torch.nn.Linear(2, 10),
#     torch.nn.ReLU(),
#     torch.nn.Linear(10,10),
#     torch.nn.Sigmoid(),
#     torch.nn.Linear(10,2),
#     torch.nn.Softmax(1)
# )

Net(
(hidden): Linear(in_features=2, out_features=10, bias=True)
(out): Linear(in_features=10, out_features=2, bias=True)
)

训练

optimizer = torch.optim.Adam(net.parameters(), lr=0.01)
loss_func = torch.nn.CrossEntropyLoss()
x = torch.FloatTensor(X)
y = torch.LongTensor(y)
plt.ion()

for t in range(1000):
    out = net(x)
    loss = loss_func(out, y)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    
    if t % 25 == 0:
        plt.cla()
        prediction = torch.max(out, 1)[1]
        pred_y = prediction.data.numpy()
        target_y = y.data.numpy()
        plt.scatter(x.data.numpy()[:, 0], x.data.numpy()[:, 1], c=pred_y, s=20)
        accuracy = sum(pred_y == target_y)/800.
        plt.text(-0.3, 0.1, 'Accuracy=%.2f' % accuracy, fontdict={'size': 20, 'color':  'red'})
        plt.text(-0.3, 0.3, 'Loss=%.2f' % loss, fontdict={'size': 20, 'color':  'red'})
        plt.pause(0.1)

plt.text(-0.3,-0.1,'job ended', fontdict={'size': 20, 'color':  'blue'})
plt.pause(3)
plt.ioff()

pytorch做一个分类任务_第2张图片

你可能感兴趣的:(深度学习)