在传统机器学习中,要实现分类算法,一般可采用KNN或者KMeans等方法实现,但以上两种方法,都会有K取值不同,分类结果的问题。而在深度学习中,跟线性回归一样,也可以使用简单粗暴的方式,解决分类问题。以下介绍使用 Pytorch 通过深度学习的方法,实现分类算法。

代码示例

1、生成随机数据集

from matplotlib import pyplot as plt
from sklearn.datasets._samples_generator import make_blobs

x, y = make_blobs(200, 2, centers=[[2, 3], [6, 8]])
plt.scatter(x[:, 0], x[:, 1])
plt.show()

2、建立神经网络

import torch
import torch.nn as nn

class CModule(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear1 = nn.Linear(2, 32)
        self.relu = nn.ReLU()
        self.linear2 = nn.Linear(32, 4)

    def forward(self, x):
        x = self.linear1(x)
        x = self.relu(x)
        x = self.linear2(x)
        return x

cmodule = CModule()
print(cmodule)

output:

CModule(
  (linear1): Linear(in_features=2, out_features=32, bias=True)
  (relu): ReLU()
  (linear2): Linear(in_features=32, out_features=4, bias=True)
)

3、模型训练

x, y = make_blobs(200, 2, centers=4)
x = torch.FloatTensor(x)
y = torch.tensor(y)

# 优化器
optimizer = torch.optim.Adam(cmodule.parameters(), lr=0.02)
# 损失函数
loss_fn = torch.nn.CrossEntropyLoss()

for i in range(1000):
    p_y = cmodule(x)
    loss = loss_fn(p_y, y)

    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

4、可视化预测结果

ax = plt.axes()
plt.ion()
plt.show()

for i in range(1000):
    ......
    # 准确率
    p_y = torch.argmax(p_y, 1).data.numpy()
    accuracy = (p_y == y.data.numpy()).sum() / y.size()[0]

    plt.cla()
    plt.scatter(x[:, 0], x[:, 1], c=p_y)
    plt.text(0.75, 0.05 , 'accuracy:' + str(accuracy), transform=ax.transAxes)
    plt.pause(0.3)

本文为 陈华 原创,欢迎转载,但请注明出处:http://www.ichenhua.cn/read/243