天天看点

用最简单的神经网络做数据分类,展示神经网络训练过程

from:https://www.jianshu.com/p/0d7438a5acb6

我的代码:

import paddle
import numpy as np
import matplotlib.pyplot as plt
import os
os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRUE'
print(paddle.__version__)

# --------------step1----------------

# 生成训练数据与标签
x1 = np.random.normal(6, 1, size=(100))
x2 = np.random.normal(3, 1, size=(100))
y = np.ones(100) #  label:1
class1 = np.array([x1, x2, y]).T
y = np.zeros(100) # label:0
class2 = np.array([x2, x1, y]).T
print(class1.shape, class2.shape)

#查看数据集图像
# plt.scatter(class1[:, 0], class1[:, 1], c='r')
# plt.scatter(class2[:, 0], class2[:, 1], c='b', marker='*')
# plt.show()


# --------------step2----------------

#合并数据并将数据打乱
all_data = np.concatenate((class1, class2)) # 合并数据
print(all_data.shape)
np.random.shuffle(all_data) # 打乱数据

#获取训练数据和标签
train_data_x = all_data[:,:2]
train_data_y = all_data[:, -1].reshape(-1, 1) # 转换成一列的数据 行设置成-1代表任意整数

#转换为Paddle框架所需要的数据类型
x_data = paddle.to_tensor(train_data_x.astype('float32'))
y_data = paddle.to_tensor(train_data_y.astype('float32'))


# --------------step3----------------
# 基于Paddle,构建神经网络、定义损失函数和优化器:Y = w1x1 + w2x2 + b

#构建线性网络:y = w1*x1 + w2*x2 + b
linear = paddle.nn.Linear(in_features=2, out_features=1)
#定义MSE损失函数
mse_loss = paddle.nn.MSELoss()
#定义优化器(optimizer) SGD:梯度下降算法  parameters:决定因素
optim = paddle.optimizer.SGD(learning_rate=0.001, parameters=linear.parameters())


# --------------step4----------------
# 定义训练轮次
total_epoch = 50000
#构建训练过程
for i in range(total_epoch):
    y_predict = linear(x_data) #计算预测值
    loss = mse_loss(y_predict, y_data)
    loss.backward()            #反向传播
    optim.step()               #执行优化算法
    optim.clear_grad()         #梯度清零
    w1_after_opt = linear.weight.numpy()[0].item() #获取模型中的w1
    w2_after_opt = linear.weight.numpy()[1].item() #获取模型中的w2
    b_after_opt = linear.bias.numpy().item()       #获取模型中的b

    #每1000次输出一次数据
    if i % 1000 == 0:
        print("epoch {} loss {}".format(i, loss.numpy()))
        print("w1 after optimize: {}".format(w1_after_opt))
        print("w2 after optimize: {}".format(w2_after_opt))
        print("b after optimize: {}".format(b_after_opt))
print("finished training, loss {}".format(loss.numpy()))


# --------------step45---------------

#绘制结果
plt.scatter(class1[:, 0], class1[:, 1])
plt.scatter(class2[:, 0], class2[:, 1], marker='*')
x = np.arange(10)

#画线的公式
y = -(w1_after_opt * x) / w2_after_opt + b_after_opt
plt.plot(x, y)
plt.show()
           

继续阅读