TensorFlow2 Python深度学习 - TensorFlow2框架入门 - 使用Keras实现分类问题
锋哥原创的TensorFlow2 Python深度学习视频教程:
https://www.bilibili.com/video/BV1X5xVz6E4w/
课程介绍
本课程主要讲解基于TensorFlow2的Python深度学习知识,包括深度学习概述,TensorFlow2框架入门知识,以及卷积神经网络(CNN),循环神经网络(RNN),生成对抗网络(GAN),模型保存与加载等。
TensorFlow2 Python深度学习 - TensorFlow2框架入门 - 使用Keras实现分类问题
我们使用TensorFlow2 Keras实现分类问题,数据集使用之前机器学习用到的鸢尾花数据集。四个特征,三个目标类别。
输出层激活函数是softmax。将网络的原始输出值转换成概率分布,方便理解和比较不同类别的预测。
示例代码:
import tensorflow as tf
from keras import Input, layers
from sklearn.datasets import load_iris
# 1,加载鸢尾花数据集
iris = load_iris()
X = iris.data # 特征:花萼长度、花萼宽度、花瓣长度、花瓣宽度
y = iris.target # 标签:0-Setosa, 1-Versicolour, 2-Virginica
# 2,构建分类模型
model = tf.keras.models.Sequential([Input(shape=(X.shape[1],)), # 输入层layers.Dense(16, activation='relu'), # 隐藏层layers.Dense(3, activation='softmax') # 输出层 3个神经元,对应3个类别
])
# 3,模型编译
model.compile(optimizer='adam',loss='sparse_categorical_crossentropy', # 多分类交叉熵损失函数metrics=['accuracy'] # 评估指标:准确率
)
# 4,模型训练
history = model.fit(X, y, epochs=200, batch_size=32, verbose=1)
print(f"最终损失: {history.history['loss'][-1]:.4f}, 最终准确率: {history.history['accuracy'][-1]:.4f}")
运行输出: