3200×36数值数据集使用CNN分类无准确率输出的问题求助
代码问题排查及修复
核心问题清单
- 输入数据形状不匹配CNN要求:你的数据集是
(样本数, 36)的二维结构,而Conv2D要求输入为四维格式(样本数, 高度, 宽度, 通道数),需要先将36维的特征reshape为适合卷积的二维结构,比如(6,6,1)(6*6=36)或者其他符合你数据特征的长宽组合。 - 模型结构缺少维度转换层:卷积和池化层输出是四维张量,不能直接接入全连接
Dense层,必须在池化层后加Flatten()层将多维特征压平为一维向量。 - 输入形状未显式定义:Sequential模型的第一层必须指定
input_shape参数,否则模型无法正常初始化权重。 - batch_size设置不合理:训练集总样本只有3200*0.75=2400条,batch_size设置为8149远大于训练集总量,会导致每个epoch只迭代1次,模型收敛效率极低甚至无法收敛,建议设置为16/32/64这类常规值。
- 池化核尺寸不合理:原代码设置
pool_size=4,对于66的输入特征来说池化后会直接压缩为11,丢失大部分特征信息,建议调整为2。
修复后可运行代码
from sklearn.model_selection import train_test_split from tensorflow.keras.utils import to_categorical from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, Flatten x_train, x_test, y_train, y_test = train_test_split(feature, target, train_size=0.75, random_state=42) # 将2维特征转换为Conv2D要求的4维输入格式,这里采用6*6的结构适配36维特征,单通道 x_train = x_train.reshape(-1, 6, 6, 1) x_test = x_test.reshape(-1, 6, 6, 1) y_train = to_categorical(y_train) y_test = to_categorical(y_test) model = Sequential() # 第一层显式指定输入形状 model.add(Conv2D(filters=64, kernel_size=3, activation='relu', input_shape=(6,6,1))) model.add(MaxPooling2D(pool_size=2)) # 新增压平层适配全连接层输入要求 model.add(Flatten()) model.add(Dense(3, activation='softmax')) model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) # 调整batch_size为常规值32 model.fit(x_train, y_train, epochs=100, batch_size=32, verbose=1) test_loss, test_acc = model.evaluate(x_test, y_test, verbose=1) print(f"测试集损失:{test_loss:.4f},测试集准确率:{test_acc:.4f}")
补充注意事项
如果你的36维特征有特定的空间结构含义,可以根据实际场景调整reshape的长宽参数,比如(3,12,1)等,只要长宽乘积等于36即可。
内容的提问来源于stack exchange,提问作者Sjn
相关产品推荐
相关产品推荐

