pytorch FC_classification

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值