【tensorflow框架神经网络实现鸢尾花分类】

1、数据获取

  • 从sklearn中获取鸢尾花数据,并合并处理
from sklearn.datasets import load_iris
import pandas as pd

x_data = load_iris().data
y_data = load_iris().target

x_data = pd.DataFrame(x_data, columns=['花萼长度','花萼宽度','花瓣长度','花瓣宽度'])
pd.set_option('display.unicode.east_asian_width', True)

x_data['类别'] = y_data
x_data

在这里插入图片描述

2、数据集构建

  • 数据集构建包括:
    • 数据读取
    • 数据打乱
    • 数据划分
    • 小批量迭代器生成
import tensorflow as tf
import numpy as np
from sklearn.datasets import load_iris

# 1、从sklearn包中datasets读取数据集
x_data = load_iris().data
y_data = load_iris().target

# 2、数据打乱
np.random.seed(1)   # 使用相同的seed,使输入特征/标签一一对应
np.random.shuffle(x_data)
np.random.seed(1)
np.random.shuffle(y_data)
tf.random.set_seed(1)

# 3、训练集、测试集划分
x_train, x_test = x_data[:-30], x_data[-30:]
y_train, y_test = y_data[:-30], y_data[-30:]

# 4、小批量数据
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)

3、模型的训练验证

# 定义超参数,预设变量
lr = 0.1
loss_all = 0
Epoch = 500
train_loss_list = []
test_acc = []

# 定义神经网络的可训练参数
w = tf.Variable(tf.random.truncated_normal([4,3], stddev=0.1, seed=1))
b = tf.Variable(tf.random.truncated_normal([3], stddev=0.1, seed=1))

# 循环迭代,训练参数
for epoch in range(Epoch):
    for step, (x_, y_) in enumerate(train_db):
        with tf.GradientTape() as tape:
            x_ = tf.cast(x_, tf.float32)
            y_pre = tf.matmul(x_, w) + b
            y_pre = tf.nn.softmax(y_pre)

            y_lab = tf.one_hot(y_, depth=3)
            loss = tf.reduce_mean(tf.square(y_lab - y_pre))
            loss_all += loss.numpy()

        grads = tape.gradient(loss, [w,b])
        w.assign_sub(lr * grads[0])
        b.assign_sub(lr * grads[1])
    print(f'Epoch: {epoch}, loss: {loss_all/4}')
    train_loss_list.append(loss_all/4)
    loss_all = 0

    # 测试部分
    total_correct, total_number = 0, 0
    for x_,y_ in test_db:
        x_ = tf.cast(x_, tf.float32)
        y_pre = tf.matmul(x_, w) + b
        y_pre = tf.nn.softmax(y_pre)
        y_p = tf.argmax(y_pre, axis=1)
        y_p = tf.cast(y_p, dtype=y_.dtype)

        correct = tf.cast(tf.equal(y_p, y_), dtype=tf.int32)
        correct = tf.reduce_sum(correct)
        total_correct += int(correct) 
        total_number += x_.shape[0]
    acc = total_correct / total_number
    test_acc.append(acc)
    print("Test_acc:", acc)
    print("-"*30)

在这里插入图片描述

4、可视化训练过程

# 绘制测试Acc曲线和训练loss曲线
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(train_loss_list,'b-')
ax.set_xlabel('Epoch')
ax.set_ylabel('Loss')

ax1 = ax.twinx()
ax1.plot(test_acc,'r-')
ax1.set_ylabel('Acc')

ax1.spines['left'].set_color('blue')
ax1.spines['right'].set_color('red')

在这里插入图片描述

  • 9
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
好的,我可以帮你解答这个问题。首先,需要导入tensorflow和numpy库: ``` import tensorflow as tf import numpy as np ``` 然后,我们需要载入鸢尾花数据集: ``` from sklearn.datasets import load_iris iris = load_iris() X = iris.data y = iris.target ``` 接下来,我们将数据集分为训练集和测试集: ``` from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) ``` 然后,我们需要对数据进行标准化处理: ``` from sklearn.preprocessing import StandardScaler scaler = StandardScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test) ``` 现在,我们可以定义我们的神经网络模型。我们将使用两个隐藏层,每个隐藏层有10个神经元,使用ReLU激活函数。输出层有3个神经元,使用softmax激活函数: ``` model = tf.keras.models.Sequential([ tf.keras.layers.Dense(10, input_shape=(4,), activation='relu'), tf.keras.layers.Dense(10, activation='relu'), tf.keras.layers.Dense(3, activation='softmax') ]) ``` 接下来,我们需要编译我们的模型,并指定损失函数、优化器和评估指标: ``` model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy']) ``` 现在,我们可以训练我们的模型了: ``` model.fit(X_train, y_train, epochs=50, validation_data=(X_test, y_test)) ``` 最后,我们可以使用测试集来评估我们的模型: ``` test_loss, test_acc = model.evaluate(X_test, y_test) print('Test accuracy:', test_acc) ``` 这就是使用tensorflow实现多层神经网络分类鸢尾花的基本流程。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值