TensorFlow中使用class_weight时出现ValueError的问题咨询
解决Class Weight导致的ValueError: No axis named -1 for object type DataFrame
问题原因
你的y_train是Pandas DataFrame格式,TensorFlow处理class_weight参数时,期望标签是一维结构(如numpy数组或Pandas Series)。DataFrame仅包含轴0(行)和轴1(列),不存在轴-1,因此触发该错误。去掉class_weight时模型能正常运行,是因为此时Keras会自动兼容DataFrame格式的标签,但class_weight的逻辑对输入格式有更严格的一维要求。
解决方案
将y_train转换为一维结构,以下几种方法均可:
- 转为numpy一维数组:
y_train = y_train.values.ravel() - 提取DataFrame单列转为Series:
y_train = y_train.iloc[:, 0] # 假设标签在第一列 - 压缩维度:
y_train = y_train.squeeze()
修改后的完整代码示例
class_weight = {0: 1.0, 1: 10.0} model = tf.keras.Sequential([ tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(256, activation='relu'), tf.keras.layers.Dense(256, activation='relu'), tf.keras.layers.Dense(1, activation='sigmoid') ]) model.compile( loss=tf.keras.losses.binary_crossentropy, optimizer=tf.keras.optimizers.Adam(), metrics=[ tf.keras.metrics.BinaryAccuracy(name='accuracy'), tf.keras.metrics.Precision(name='precision'), tf.keras.metrics.Recall(name='recall') ] ) # 转换y_train为一维结构 y_train = y_train.values.ravel() history = model.fit(x_train, y_train, epochs=100, class_weight=class_weight)
内容的提问来源于stack exchange,提问作者Icy
相关产品推荐
相关产品推荐

