Tensorflow 二元交叉熵总是预测相同的值

问题描述 投票:0回答:1

我是一般堆栈溢出社区的新手,尤其是 Tensorflow 库的新手(截至目前 1 周)。所以我确信我在这里遗漏了一些东西,只是我自己不太明白。

我利用 Tensorflow 的示例数据集和一些杂项教程进行了一些实践。我发现自己尝试将教程的代码之一应用到我自己的数据集,该数据集是 csv,模型应该返回“最后结果”列的预测。事实证明这有点多了,因为我很快就遇到了一个问题,“预测”函数总是为每个数据条目预测相同的值。

[[0.6335701] [0.6335701] ... [0.6335701] [0.6335701]]

import pandas as pd
from sklearn.model_selection import train_test_split
from keras.models import Sequential, load_model
from keras.layers import Dense
from sklearn.metrics import accuracy_score

df = pd.read_csv('*.csv')
x = pd.get_dummies(df.drop(['Last Result'], axis=1))
y = df['Last Result'].apply(lambda X: 1 if X == 'Registered' else 0)
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=.2)
x_train.head()
print("x train: \n", x_train)
y_train.head()
print("y train: \n", y_train)

# Below is code to create a new TensorFlow Model. If you need to call a saved model, see 'load model' below.

model = Sequential()
model.add(Dense(units=32, activation='relu', input_dim=len(x_train.columns)))
model.add(Dense(units=32, activation='relu'))
model.add(Dense(units=1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='sgd', metrics=['accuracy'])

model.fit(x_train, y_train, epochs=100, batch_size=128)

# model.save('*.keras')

# This is code to recall a previously saved TensorFlow Model

# model = load_model('*.keras')

y_hat = model.predict(x_test)
# y_hat = [0 if val < 0.5 else 1 for val in y_hat]
print(y_hat)

# print(accuracy_score(y_test, y_hat))

我尝试过类似帖子中的其他建议,但无济于事。我对这个问题的最佳理解是,该模型没有学习任何东西,而是只是猜测所有一个值,因为其中一个预期值在大约 60% 的时间内为真,因此预测值约为 0.60。

对此事的任何帮助都对帮助我了解图书馆有很大帮助。预先感谢您的宝贵时间。

python tensorflow machine-learning neural-network tensorflow2.0
1个回答
0
投票

您需要删除

pd.get_dummies
函数调用。直接赋值即可

x = df.drop(['Last Result'], axis=1)

调用 pd.get_dummies 将样本转换为 0/1 数据:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.get_dummies.html.

您能否提供有关数据集性质的更多信息?这将有助于理解您正在尝试做什么。

© www.soinside.com 2019 - 2024. All rights reserved.