为什么我的损失趋于下降,而我的准确度却为零?

Dan*_*nyK 1 python machine-learning structured-data tensorflow

我正在尝试使用 Tensorflow/Keras 练习我的机器学习技能,但是我在拟合模型方面遇到了麻烦。让我解释一下我做了什么以及我在哪里。

我正在使用来自 Kaggle 的哥斯达黎加家庭贫困水平预测挑战的数据集

由于我只是想熟悉 Tensorflow 工作流程,因此我通过删除一些包含大量缺失数据的列来清理数据集,然后用它们的平均值填充其他列。所以我的数据集中没有缺失值。

接下来,我make_csv_dataset从 TF中使用 using 加载了新的、清理过的 csv 。

batch_size = 32

train_dataset = tf.data.experimental.make_csv_dataset(
    'clean_train.csv',
    batch_size,
    column_names=column_names,
    label_name=label_name,
    num_epochs=1)
Run Code Online (Sandbox Code Playgroud)

我设置了一个函数来返回我编译的模型,如下所示:

f1_macro = tfa.metrics.F1Score(num_classes=4, average='macro')

def get_compiled_model():
    model = tf.keras.Sequential([
      tf.keras.layers.Dense(512, activation=tf.nn.relu, input_shape=(137,)),  # input shape required
      tf.keras.layers.Dense(256, activation=tf.nn.relu),
      tf.keras.layers.Dense(4, activation=tf.nn.softmax)
    ])

    model.compile(optimizer='adam',
                loss='binary_crossentropy',
                metrics=[f1_macro, 'accuracy'])
    return model
Run Code Online (Sandbox Code Playgroud)
model = get_compiled_model()
model.fit(train_dataset, epochs=15)
Run Code Online (Sandbox Code Playgroud)

下面是结果

这是我的输出

我的笔记本的链接在这里

我应该提到,我的实现强烈基于 Tensorflow 的 iris 数据演练

谢谢!

thu*_*v89 7

一段时间后,我能够找到您的代码的问题,它们按重要性排序。(第一个是最重要的)

  1. 您正在进行多类分类(不是二元分类)。因此你的损失应该是categorical_crossentropy

  2. 你不是onehot 编码你的标签。使用binary_crossentropy和拥有标签作为数字 ID 绝对不是前进的方向。相反,您应该对标签进行 onehot 编码,并像多类分类问题一样解决这个问题。这是你如何做到的。

def pack_features_vector(features, labels):
    """Pack the features into a single array."""
    features = tf.stack(list(features.values()), axis=1)
    return features, tf.one_hot(tf.cast(labels-1, tf.int32), depth=4)
Run Code Online (Sandbox Code Playgroud)
  1. 规范化您的数据。如果你看看你的训练数据。它们没有标准化。他们的价值观无处不在。因此,您应该考虑通过执行以下操作来规范您的数据。这仅用于演示目的。你应该阅读有关倍线器在scikit学习和选择最适合你。
x = train_df[feature_names].values #returns a numpy array
min_max_scaler = preprocessing.StandardScaler()
x_scaled = min_max_scaler.fit_transform(x)
train_df = pd.DataFrame(x_scaled)
Run Code Online (Sandbox Code Playgroud)

这些问题应该让你的模型变得直截了当。