TensorFlow手动搭建神经网络实现鸢尾花分类

步骤

  • 准备数据

  • 搭建网络

    • 定义神经网络中所有可训练参数
  • 参数优化

    • 嵌套循环迭代,with结构更新参数,显示当前loss
  • 测试效果

    • 计算当前参数前向传播后的准确率,显示当前acc
  • acc/loss可视化

这里使用一个最简单的网络实现鸢尾花分类

TensorFlow手动搭建神经网络实现鸢尾花分类_第1张图片

完整代码

import tensorflow as tf
from sklearn.datasets import load_iris
import numpy as np
from matplotlib import pyplot as plt

# import data
src = load_iris()
x_data = src.data
y_data = src.target

# shuffle data
np.random.seed(0)
np.random.shuffle(x_data)
np.random.seed(0)
np.random.shuffle(y_data)
tf.random.set_seed(0)

# split train and test data
x_train = x_data[:-30]
y_train = y_data[:-30]
x_test = x_data[-30:]
y_test = y_data[-30:]

# 数据类型转换
x_train = tf.cast(x_train, tf.float32)
x_test = tf.cast(x_test, tf.float32)

# 构建数据集
train_db = tf.data.Dataset.from_tensor_slices((x_train, y_train)).batch(32)
test_db = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(32)

# 定义神经网络的可训练参数

w1 = tf.Variable(tf.random.truncated_normal([4, 3], stddev=0.1, seed=1))
b1 = tf.Variable(tf.random.truncated_normal([3], stddev=0.1, seed=1))

# 定义超参数

lr = 0.1
train_loss_result = []
test_acc = []
epoch = 500
loss_all = 0

# 循环嵌套迭代

for epoch in range(epoch):
    for step, (x_train, y_train) in enumerate(train_db):  # batch级别迭代
        with tf.GradientTape() as tape:
            y = tf.matmul(x_train, w1) + b1
            y = tf.nn.softmax(y)
            y_ = tf.one_hot(y_train, depth=3)
            loss = tf.reduce_mean(tf.square(y_ - y))
            loss_all += loss.numpy()
        #     计算loss对各个参数的梯度
        grads = tape.gradient(loss, [w1, b1])

        # 实现梯度更新
        w1.assign_sub(lr * grads[0])
        b1.assign_sub(lr * grads[1])
    # 每个epoch,打印loss信息
    print("Epoch {},loss:{}".format(epoch, loss_all / 4))
    train_loss_result.append(loss_all / 4)
    loss_all = 0

    # 测试部分
    total_correct, total_number = 0, 0
    for x_test, y_test in test_db:
        y = tf.matmul(x_test, w1) + b1
        y=tf.nn.softmax(y)
        pred=tf.argmax(y,axis=1)
        pred=tf.cast(pred,dtype=y_test.dtype)

        correct=tf.cast(tf.equal(pred,y_test),dtype=tf.int32)
        correct=tf.reduce_sum(correct)
        total_correct+=int(correct)
        total_number+=x_test.shape[0]
    acc=total_correct/total_number
    test_acc.append(acc)
    print("Test_acc:",acc)
    print("-------------")

plt.title('Loss Function Curve')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.plot(train_loss_result,label='$Loss$')
plt.legend()
plt.show()

plt.title('Acc Curve')
plt.xlabel('Epoch')
plt.ylabel('Acc')
plt.plot(test_acc,label='$Accuracy$')
plt.legend()
plt.show()

你可能感兴趣的:(AI,DeepLearning,神经网络,tensorflow,分类)