ANN入学预测模型训练精度低、损失高的优化咨询
入学预测ANN模型优化方案
核心问题诊断
从你的代码和训练日志来看,模型存在多处基础错误,直接导致了高损失和低精度:
- 输出层与目标变量维度完全不匹配
- 特征利用率极低,浪费了大量有效信息
- 类别特征编码方式错误,误导模型学习
- 隐藏层激活函数选择不当,引发梯度消失问题
- 损失函数与标签格式不兼容
具体优化步骤
1. 修正目标变量与模型输出结构
你的任务是同时预测college_name(326类)和branch(95类),属于多输出多分类任务,但当前模型最后仅输出2个神经元,完全无法匹配任务需求。
调整模型结构:
import tensorflow as tf from tensorflow.keras.layers import Input, Dense, Dropout from tensorflow.keras.models import Model # 输入层:特征数根据后续调整后的特征集修改 input_layer = Input(shape=(7,), name='features') # 共享隐藏层:使用ReLU激活函数替代Softmax x = Dense(128, activation='relu')(input_layer) x = Dropout(0.3)(x) x = Dense(64, activation='relu')(x) x = Dropout(0.2)(x) # 两个独立输出分支,对应各自的类别数量 college_output = Dense(326, activation='softmax', name='college_name')(x) branch_output = Dense(95, activation='softmax', name='branch')(x) # 构建多输出模型 model = Model(inputs=input_layer, outputs=[college_output, branch_output])
2. 优化特征使用与编码
(1)使用全部有效特征
当前仅用了percentile_scaled和City,应加入seat_type、gender、family_income_less_than_8_lakh等特征,提升模型信息输入量:
# 选择全部可用特征 X = data[['percentile_scaled', 'City', 'seat_type', 'gender', 'family_income_less_than_8_lakh']].values # 拆分目标变量为两个独立数组 y_college = data['college_name'].values y_branch = data['branch'].values # 划分训练测试集 X_train, X_test, y_college_train, y_college_test, y_branch_train, y_branch_test = train_test_split( X, y_college, y_branch, test_size=0.2, random_state=42 )
(2)修正类别特征编码方式
LabelEncoder会给类别赋予有序整数,会让模型错误认为类别存在大小关系(比如City的编码1比0“更大”):
- 对于低基数类别(如gender、family_income_less_than_8_lakh):使用OneHot编码消除顺序影响
- 对于高基数类别(如City、seat_type):后续可考虑用Embedding层处理,当前先保留LabelEncoder编码用于模型输入
示例:OneHot处理低基数特征
from sklearn.preprocessing import OneHotEncoder import pandas as pd # 对低基数类别特征做OneHot编码 onehot_cols = ['gender', 'family_income_less_than_8_lakh'] encoder = OneHotEncoder(sparse_output=False, drop='first') onehot_features = encoder.fit_transform(data[onehot_cols]) onehot_df = pd.DataFrame(onehot_features, columns=encoder.get_feature_names_out(onehot_cols)) # 合并所有处理后的特征 processed_data = pd.concat([ data[['percentile_scaled', 'City', 'seat_type']], onehot_df ], axis=1) # 更新特征集 X = processed_data.values
3. 匹配损失函数与标签格式
- 目标变量是整数标签(LabelEncoder编码后),无需做OneHot编码,直接使用
sparse_categorical_crossentropy损失函数 - 多输出任务需为每个输出分支指定损失和评估指标
from tensorflow.keras.optimizers import Adam optimizer = Adam(learning_rate=0.001) model.compile( optimizer=optimizer, loss={ 'college_name': 'sparse_categorical_crossentropy', 'branch': 'sparse_categorical_crossentropy' }, metrics={ 'college_name': 'accuracy', 'branch': 'accuracy' } )
4. 调整训练参数
- 降低Dropout比例:当前0.5的Dropout对于小模型来说抑制过度,调整为0.2~0.3
- 加入早停机制:防止模型过拟合,自动保留最优权重
- 调整批次大小:可尝试64或128,提升训练稳定性
from tensorflow.keras.callbacks import EarlyStopping early_stop = EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True) # 训练时传入两个目标变量 history = model.fit( X_train, {'college_name': y_college_train, 'branch': y_branch_train}, epochs=200, batch_size=64, validation_data=(X_test, {'college_name': y_college_test, 'branch': y_branch_test}), callbacks=[early_stop] )
额外建议
- 数据平衡检查:查看
college_name和branch的类别分布,若存在严重不平衡,可采用过采样、欠采样或设置类别权重 - 特征工程:对
percentile尝试分箱处理,或生成交叉特征(如percentile+City)增强特征表达 - 基准对比:先用树模型(如XGBoost、LightGBM)跑基准效果,再针对性优化ANN模型
内容的提问来源于stack exchange,提问作者Harshil Modh
相关产品推荐
相关产品推荐

