Python深度学习实战-基于Sequential方法搭建BP神经网络实现分类任务(附源码和实现效果)

实现功能

  1. 第一步:导入模块:import tensorflow as tf

  2. 第二步:制定输入网络的训练集和测试集

  3. 第三步:搭建网络结构:tf.keras.models.Sequential()

  4. 第四步:配置训练方法:model.compile():

  5. 第五步:执行训练过程:model.fit():

  6. 第六步:打印网络结构:model.summary()

  7. 第七步:执行验证过程:model.evaluate()

实现代码

python 复制代码
import tensorflow as tf
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

# 加载鸢尾花数据集
iris = load_iris()
X = iris.data
y = iris.target

# 数据预处理
scaler = StandardScaler()
X = scaler.fit_transform(X)

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 创建模型
model = tf.keras.Sequential([
    tf.keras.layers.Dense(64, activation='relu', input_shape=(X.shape[1],)),
    tf.keras.layers.Dense(64, activation='relu'),
    tf.keras.layers.Dense(len(set(y)), activation='softmax')
])

# 编译模型
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

# 训练模型
model.fit(X_train, y_train, epochs=10, batch_size=32)
model.summary()
# 评估模型
test_loss, test_accuracy = model.evaluate(X_test, y_test)

实现效果

本人读研期间发表5篇SCI数据挖掘相关论文,现在某研究院从事数据挖掘相关科研工作,对数据挖掘有一定认知和理解,会结合自身科研实践经历不定期分享关于python、机器学习、深度学习基础知识与案例。

致力于 只做原创 ,以最简单的方式理解和学习,关注我一起交流成长。

邀请三个朋友关注本订阅号V:数据杂坛,即可在后台联系我 获取相关数据集和源码 ,送有关数据分析、数据挖掘、机器学习、深度学习相关的电子书籍。

相关推荐
databook5 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室5 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三6 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户25191624271110 小时前
Python之语言特点
python
刘立军10 小时前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机14 小时前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机15 小时前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i16 小时前
django中的FBV 和 CBV
python·django
c8i16 小时前
python中的闭包和装饰器
python
惯导马工16 小时前
【论文导读】ORB-SLAM3:An Accurate Open-Source Library for Visual, Visual-Inertial and
深度学习·算法