You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

1D卷积神经网络特征分类错误:自定义时序数据集训练model.fit报错求助

1D CNN适配自有数据集报错修复方案

核心错误点

  • 输出维度配置错误:当前n_outputs设为1,实际为4分类任务,该参数需修改为4,对应4个类别的输出概率
  • 测试集未适配输入要求:训练时对trainX做了(样本数, 6, 1)的3D reshape适配Conv1D输入规范,但评估阶段testX仍为原始2D格式,同时测试集标签也未做one-hot编码处理
  • 标签与损失函数不匹配:使用categorical_crossentropy损失时,训练、评估两个阶段的标签都需要转为one-hot格式,也可直接替换为sparse_categorical_crossentropy省略转码步骤,简化代码

可选适配说明

如果你的单条样本实际是1个时间步下的6个传感器特征,而非6个时间步的1个特征,可调整reshape逻辑为reshape(len(trainX), 1, 6),同时将n_timesteps, n_features修改为1, 6即可。

修复后代码

import numpy as np
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv1D, Dropout, MaxPooling1D, Flatten, Dense
from tensorflow.keras.utils import to_categorical

# 原数据预处理代码
X = D.replace(['Resting', 'Swimming', 'Feeding', 'Non directed motion'], [0, 1, 2, 3])
X_Label = X['Label'].to_numpy()
X_Data = X[['X_static','Y_static','Z_static','X_dynamic','Y_dynamic','Z_dynamic']].to_numpy()

X_names = ['X_static','Y_static','Z_static','X_dynamic','Y_dynamic','Z_dynamic']
X_Label_Names = np.array(['Resting', 'Swimming', 'Feeding', 'Non directed motion'])

X = X_Data
y = X_Label
random_state = 42 # 补充缺失的随机种子定义

def load_dataset_f(X,y):
    X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.5, stratify=y, random_state=random_state
    )
    trainX = X_train
    trainy = y_train
    testX = X_test
    testy = y_test
    return trainX, trainy, testX, testy

def summarize_results(scores):
    # 补充缺失的结果汇总函数
    print(f"平均准确率: {np.mean(scores):.3f}%,标准差: {np.std(scores):.3f}%")

# 模型训练评估函数
def evaluate_model_f(trainX, trainy, testX, testy):
    verbose, epochs, batch_size = 2, 10, 20
    # 修改输出维度为4
    n_timesteps, n_features, n_outputs = 6, 1, 4
    model = Sequential()
    model.add(Conv1D(filters=64, kernel_size=3, activation='relu', input_shape=(n_timesteps,n_features)))
    model.add(Conv1D(filters=64, kernel_size=3, activation='relu'))
    model.add(Dropout(0.5))
    model.add(MaxPooling1D(pool_size=2))
    model.add(Flatten())
    model.add(Dense(100, activation='relu'))
    model.add(Dense(n_outputs, activation='softmax'))
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    # 统一处理训练、测试集的输入和标签格式
    trainX_reshaped = trainX.reshape(len(trainX), n_timesteps, n_features)
    testX_reshaped = testX.reshape(len(testX), n_timesteps, n_features)
    trainy_onehot = to_categorical(trainy)
    testy_onehot = to_categorical(testy)
    # 训练模型
    model.fit(trainX_reshaped, trainy_onehot, epochs=epochs, batch_size=batch_size, verbose=verbose)
    # 评估模型
    _, accuracy = model.evaluate(testX_reshaped, testy_onehot, batch_size=batch_size, verbose=0)
    return accuracy

def run_experiment_f(repeats=1):
    # 加载数据
    trainX, trainy, testX, testy = load_dataset_f(X,y)
    scores = list()
    for r in range(repeats):
        score = evaluate_model_f(trainX, trainy, testX, testy)
        score = score * 100.0
        print(f'>#{r+1}: {score:.3f}')
        scores.append(score)
    # 汇总结果
    summarize_results(scores)
    
run_experiment_f()

内容的提问来源于stack exchange,提问作者Brandon M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 12:45:05