如何解释和转换 Keras 分类器预测的值?

kit*_*Kat 3 python machine-learning neural-network keras tensorflow

我正在训练我的 Keras 模型,以使用提供的数据参数预测它是否会出手,并且它将以 0 表示否,1 表示是的方式表示。但是,当我尝试预测它时,我得到的值是浮动的。

我尝试使用与火车数据完全相同的数据来获得 1,但它不起作用。

我使用下面的数据尝试了one-hot编码。

https://github.com/eijaz1/Deep-Learning-in-Keras-Tutorial/blob/master/keras_tutorial.ipynb

import pandas as pd
from keras.utils import to_categorical
from keras.models import load_model
from keras.models import Sequential
from keras.layers import Dense
from keras.callbacks import EarlyStopping
#read in training data
train_df_2 = pd.read_csv('diabetes_data.csv')

#view data structure
train_df_2.head()

#create a dataframe with all training data except the target column
train_X_2 = train_df_2.drop(columns=['diabetes'])

#check that the target variable has been removed
train_X_2.head()

#one-hot encode target column
train_y_2 = to_categorical(train_df_2.diabetes)

#vcheck that target column has been converted
train_y_2[0:5]

#create model
model_2 = Sequential()

#get number of columns in training data
n_cols_2 = train_X_2.shape[1]

#add layers to model
model_2.add(Dense(250, activation='relu', input_shape=(n_cols_2,)))
model_2.add(Dense(250, activation='relu'))
model_2.add(Dense(250, activation='relu'))
model_2.add(Dense(2, activation='softmax'))

#compile model using accuracy to measure model performance
model_2.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
early_stopping_monitor = EarlyStopping(patience=3)
model_2.fit(train_X_2, train_y_2, epochs=30, validation_split=0.2, callbacks=[early_stopping_monitor])


train_dft = pd.read_csv('diabetes_data - Copy.csv')
train_dft.head()

test_y_predictions = model_2.predict(train_dft)
print(test_y_predictions)
Run Code Online (Sandbox Code Playgroud)

我想得到

[[0,1]
[1,0]]
Run Code Online (Sandbox Code Playgroud)

但是,我得到

[[0.8544417  0.14555828]
 [0.9312985  0.06870154]]
Run Code Online (Sandbox Code Playgroud)

此外,谁能向我解释这个值 0.8544417 是什么意思?

tod*_*day 10

实际上,您可以将顶部带有 softmax 分类器的模型的输出解释为类的置信度分数或概率(因为 softmax 函数对值进行了归一化,使得它们为正且总和为 1)。因此,当您为模型提供[1, 0]this的真实标签时,意味着该样本属于第 1 类,概率为 1,属于第 2 类,概率为零。因此,在训练过程中,优化过程试图尽可能接近该标签,但它永远不会完全达到 [1,0](实际上由于 softmax,它可能会接近 [0.999999, 0.000001],但永远不会 [1] , 0])。

但这不是问题,因为我们有兴趣获得足够接近并知道概率最高的类别,并将其视为模型的预测。您可以通过以最大概率找到类的索引来轻松做到这一点:

import numpy as np

preds = model.predict(some_data)
class_preds = np.argmax(preds, axis=-1) # e.g. for [max,min] it gives 0, for [min,max] it gives 1
Run Code Online (Sandbox Code Playgroud)

此外,如果您有兴趣出于任何原因将预测转换为 [0,1] 或 [1,0],您可以将值四舍五入:

import numpy as np

preds = model.predict(some_data)
round_preds = np.around(preds)   # this would convert [0.87, 0.13] to [1., 0.]
Run Code Online (Sandbox Code Playgroud)

注意:四舍五入只适用于两个类,而不是当你有两个以上的类时(例如,[0.3, 0.4, 0.3] 在四舍五入后会变成 [0, 0, 0])。

注意 2:由于您使用 Keras 的 Sequential API 创建模型,因此作为argmax上述方法的替代方法,您可以直接使用model.predict_classes(some_data)它为您提供完全相同的输出。