我正在尝试使用Tensorflow / Keras练习机器学习技能,但是在拟合模型时遇到了麻烦。让我解释一下我做了什么以及我现在在哪里。
我正在使用Kaggle的Costa Rican Household Poverty Level Prediction Challenge
中的数据集由于我只是想熟悉Tensorflow工作流程,因此我通过删除一些缺少大量数据的列来清理数据集,然后用均值填充其他列。因此,我的数据集中没有缺失值。
接下来,我使用TF中的make_csv_dataset
加载了新的,经过清理的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)
我设置了一个函数来返回我的编译模型,如下所示:
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
model = get_compiled_model()
model.fit(train_dataset, epochs=15)
以下是结果
我的笔记本的链接为Here
我应该提到,我的实现完全基于Tensorflow的虹膜数据walkthrough
谢谢!
答案 0 :(得分:7)
过了一会儿,我发现了与您的代码有关的问题,它们的重要性排在了先后。 (首先是最重要的)
您正在执行多类分类(不是二进制分类)。因此,您的损失应为categorical_crossentropy
。
您还没有对标签进行热编码。使用binary_crossentropy
并将标签作为数字ID绝对不是前进的道路。相反,您应该对标签进行热编码并像多类分类问题一样解决它。这是您的操作方式。
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)
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)
这些问题应该使您的模型更简单。