从零到一:用Keras Sequential模型实战鸢尾花分类(深度神经网络构建全解析)
1. 环境准备与数据理解在开始构建鸢尾花分类模型前我们需要准备好Python环境和相关工具库。推荐使用Anaconda创建虚拟环境避免与其他项目产生依赖冲突。安装核心库只需一行命令pip install tensorflow pandas scikit-learn鸢尾花数据集是机器学习领域的经典数据集包含150个样本每个样本有4个特征花萼长度、花萼宽度、花瓣长度和花瓣宽度。目标变量是三种鸢尾花的类别Iris-setosa山鸢尾Iris-versicolor变色鸢尾Iris-virginica维吉尼亚鸢尾用pandas加载数据时可以直观查看数据结构import pandas as pd from sklearn.datasets import load_iris iris load_iris() df pd.DataFrame(iris.data, columnsiris.feature_names) df[target] iris.target print(df.head())数据预处理的关键步骤包括特征标准化将各特征缩放到相近范围加速模型收敛标签编码把文本类别转换为数值再转为独热编码数据集划分按8:2比例拆分训练集和测试集from sklearn.preprocessing import StandardScaler from keras.utils import to_categorical from sklearn.model_selection import train_test_split # 标准化特征 scaler StandardScaler() X_scaled scaler.fit_transform(iris.data) # 标签独热编码 y_ohe to_categorical(iris.target) # 划分数据集 X_train, X_test, y_train, y_test train_test_split( X_scaled, y_ohe, test_size0.2, random_state42)2. 构建Sequential模型Keras的Sequential模型就像搭积木一样逐层堆叠网络层。我们先创建一个空模型然后像三明治一样添加各层from keras.models import Sequential from keras.layers import Dense, Dropout model Sequential([ Dense(16, activationrelu, input_shape(4,)), Dense(16, activationrelu), Dropout(0.3), # 随机丢弃30%神经元防止过拟合 Dense(3, activationsoftmax) ])这里有几个关键设计选择输入层input_shape(4,)对应4个特征隐藏层使用ReLU激活函数避免梯度消失输出层3个神经元对应3个类别softmax确保输出为概率分布Dropout训练时随机关闭部分神经元增强泛化能力可以用model.summary()查看网络结构输出如下Model: sequential _________________________________________________________________ Layer (type) Output Shape Param # dense (Dense) (None, 16) 80 _________________________________________________________________ dense_1 (Dense) (None, 16) 272 _________________________________________________________________ dropout (Dropout) (None, 16) 0 _________________________________________________________________ dense_2 (Dense) (None, 3) 51 Total params: 403 Trainable params: 403 Non-trainable params: 03. 模型编译与训练模型编译相当于给模型设置学习规则需要指定三个关键参数model.compile( optimizeradam, # 自适应学习率优化器 losscategorical_crossentropy, # 多分类对数损失 metrics[accuracy] # 监控准确率 )训练时要注意两个核心参数batch_size每次梯度更新使用的样本数影响训练速度和内存占用epochs完整遍历数据集的次数太少欠拟合太多过拟合history model.fit( X_train, y_train, batch_size8, epochs100, validation_data(X_test, y_test), verbose1 # 显示进度条 )训练过程会输出类似这样的日志Epoch 1/100 15/15 [] - 0s 5ms/step - loss: 1.0932 - accuracy: 0.3583 - val_loss: 1.0283 - val_accuracy: 0.5667 ... Epoch 100/100 15/15 [] - 0s 2ms/step - loss: 0.0523 - accuracy: 0.9833 - val_loss: 0.0741 - val_accuracy: 0.96674. 模型评估与调优训练完成后我们需要评估模型表现。除了看准确率还要关注损失曲线import matplotlib.pyplot as plt plt.plot(history.history[accuracy], labelTrain Acc) plt.plot(history.history[val_accuracy], labelVal Acc) plt.title(Model Accuracy) plt.ylabel(Accuracy) plt.xlabel(Epoch) plt.legend() plt.show()如果发现过拟合训练集准确率高但验证集低可以尝试增加Dropout比例添加L2正则化减少网络层数或神经元数量使用早停EarlyStoppingfrom keras.regularizers import l2 # 添加L2正则化的隐藏层示例 Dense(16, activationrelu, kernel_regularizerl2(0.01))5. 模型应用与扩展训练好的模型可以保存为文件方便后续调用model.save(iris_model.h5) # 保存完整模型 from keras.models import load_model loaded_model load_model(iris_model.h5) # 加载模型进行新数据预测时要注意保持相同的预处理流程import numpy as np # 新样本预测需先进行相同的标准化 new_sample np.array([[5.1, 3.5, 1.4, 0.2]]) new_sample_scaled scaler.transform(new_sample) pred model.predict(new_sample_scaled) print(f预测概率分布{pred}) print(f预测类别{iris.target_names[np.argmax(pred)]})对于更复杂的场景可以尝试使用Functional API构建分支结构添加批标准化层BatchNormalization尝试不同的优化器如Nadam实现自定义评估指标这个鸢尾花分类项目虽然简单但涵盖了深度学习开发的完整流程。在实际工作中我发现很多初学者容易忽视数据标准化和验证集评估这两个环节导致模型表现不稳定。建议大家在修改网络结构前先确保数据预处理流程正确无误。