为啥我在使用 Scikit-Learn Keras 模型函数时,对于相同的网络配置会得到不同的准确度结果?

Posted

技术标签:

【中文标题】为啥我在使用 Scikit-Learn Keras 模型函数时,对于相同的网络配置会得到不同的准确度结果?【英文标题】:Why am I having different accuracy results for the same network configuration when I am using Scikit-Learn Keras model function?为什么我在使用 Scikit-Learn Keras 模型函数时,对于相同的网络配置会得到不同的准确度结果? 【发布时间】:2020-12-25 01:22:29 【问题描述】:

在构建 DNN 时,我使用了 Keras 的 scikit-learn 分类器 API,即“tf.keras.wrappers.scikit_learn.KerasClassifier”。我的平均简历分数为 53%。当我在不使用 Keraswrapper 函数的情况下执行相同的分类时,尽管我使用了相同的架构和超参数,但我的平均 cv 得分为 24.23%。我遵循了 Jason Brownlee 的“使用 Python 进行深度学习”一书中的代码。不使用包装函数我的代码是:

from keras.models import Sequential
from keras.layers import Dense
from sklearn.model_selection import StratifiedKFold
import numpy
# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)

kfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=seed)
cvscores = []

for train, test in kfold.split(X, y):
 model = Sequential()
 model.add(Dense(128, input_dim=76636, kernel_initializer='uniform', activation='relu'))
 model.add(Dense(64, activation='relu', kernel_initializer='uniform'))  
 model.add(Dense(2, kernel_initializer='uniform', activation='softmax'))
 # Compile model
 model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
 #Fit the model
 model.fit(X[train], y[train], epochs=50, batch_size=512, verbose=0)
 #Evaluate the model
 scores = model.evaluate(X[test], y[test], verbose=0)
 #print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
 cvscores.append(scores[1] * 100)

print("%.2f%% (+/- %.2f%%)" % (numpy.mean(cvscores), numpy.std(cvscores)))

我得到以下输出:24.23% (+/- 2.35%)

当我使用 Keraswrapper 函数时,我的代码是:

from keras.models import Sequential
from keras.layers import Dense
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import StratifiedKFold
from sklearn.model_selection import cross_val_score
import numpy

# Function to create model, required for KerasClassifier
def create_model():
 # create model
 model = Sequential()
 model.add(Dense(128, input_dim=76636, kernel_initializer='uniform', activation='relu'))
 model.add(Dense(64, activation='relu', kernel_initializer='uniform'))  
 model.add(Dense(2, kernel_initializer='uniform', activation='softmax'))
 # Compile model
 model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
 return model

# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)

model = KerasClassifier(build_fn=create_model, nb_epoch=50, batch_size=512, verbose=0)

# evaluate using 10-fold cross validation
kfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=seed)
results = cross_val_score(model, X, y, cv=kfold)
print(results.mean())

输出为:0.5315796375274658

【问题讨论】:

【参考方案1】:

我在 pima-indians-diabetes.csv 数据集上运行了您的代码,但无法重现您面临的问题。结果略有不同,但这可以通过numpy.std(cvscores) 来解释。

以下是运行详情 -

不使用包装函数:

%tensorflow_version 2.x
from keras.models import Sequential
from keras.layers import Dense
from sklearn.model_selection import StratifiedKFold
import numpy

# load pima indians dataset
dataset = np.loadtxt("/content/pima-indians-diabetes.csv", delimiter=",")

# split into input (X) and output (Y) variables
X = dataset[:,0:8]
y = dataset[:,8]

# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)

kfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=seed)
cvscores = []

for train, test in kfold.split(X, y):
 model = Sequential()
 model.add(Dense(128, input_dim=8, kernel_initializer='uniform', activation='relu'))
 model.add(Dense(64, activation='relu', kernel_initializer='uniform'))  
 model.add(Dense(2, kernel_initializer='uniform', activation='softmax'))
 # Compile model
 model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
 #Fit the model
 model.fit(X[train], y[train], epochs=50, batch_size=512, verbose=0)
 #Evaluate the model
 scores = model.evaluate(X[test], y[test], verbose=0)
 #print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
 cvscores.append(scores[1] * 100)

print("%.2f%% (+/- %.2f%%)" % (numpy.mean(cvscores), numpy.std(cvscores)))

输出 -

WARNING:tensorflow:6 out of the last 11 calls to <function Model.make_train_function.<locals>.train_function at 0x7fc2c1468ae8> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/tutorials/customization/performance#python_or_tensor_args and https://www.tensorflow.org/api_docs/python/tf/function for  more details.
WARNING:tensorflow:7 out of the last 30 calls to <function Model.make_test_function.<locals>.test_function at 0x7fc2c4579d90> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/tutorials/customization/performance#python_or_tensor_args and https://www.tensorflow.org/api_docs/python/tf/function for  more details.
WARNING:tensorflow:7 out of the last 11 calls to <function Model.make_test_function.<locals>.test_function at 0x7fc2c1604d08> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/tutorials/customization/performance#python_or_tensor_args and https://www.tensorflow.org/api_docs/python/tf/function for  more details.
48.70% (+/- 5.46%)

使用包装函数:

from keras.models import Sequential
from keras.layers import Dense
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import StratifiedKFold
from sklearn.model_selection import cross_val_score
import numpy

# load pima indians dataset
dataset = np.loadtxt("/content/pima-indians-diabetes.csv", delimiter=",")

# split into input (X) and output (Y) variables
X = dataset[:,0:8]
y = dataset[:,8]

# Function to create model, required for KerasClassifier
def create_model():
 # create model
 model = Sequential()
 model.add(Dense(128, input_dim=8, kernel_initializer='uniform', activation='relu'))
 model.add(Dense(64, activation='relu', kernel_initializer='uniform'))  
 model.add(Dense(2, kernel_initializer='uniform', activation='softmax'))
 # Compile model
 model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
 return model

# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)

model = KerasClassifier(build_fn=create_model, nb_epoch=50, batch_size=512, verbose=0)

# evaluate using 10-fold cross validation
kfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=seed)
results = cross_val_score(model, X, y, cv=kfold)
print(results.mean())

输出 -

WARNING:tensorflow:5 out of the last 13 calls to <function Model.make_test_function.<locals>.test_function at 0x7fc2c4b79ea0> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/tutorials/customization/performance#python_or_tensor_args and https://www.tensorflow.org/api_docs/python/tf/function for  more details.
WARNING:tensorflow:5 out of the last 107 calls to <function Model.make_train_function.<locals>.train_function at 0x7fc2d31262f0> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/tutorials/customization/performance#python_or_tensor_args and https://www.tensorflow.org/api_docs/python/tf/function for  more details.
WARNING:tensorflow:6 out of the last 14 calls to <function Model.make_test_function.<locals>.test_function at 0x7fc2c4b79a60> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/tutorials/customization/performance#python_or_tensor_args and https://www.tensorflow.org/api_docs/python/tf/function for  more details.
WARNING:tensorflow:6 out of the last 109 calls to <function Model.make_train_function.<locals>.train_function at 0x7fc2c4cc4268> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/tutorials/customization/performance#python_or_tensor_args and https://www.tensorflow.org/api_docs/python/tf/function for  more details.
WARNING:tensorflow:7 out of the last 15 calls to <function Model.make_test_function.<locals>.test_function at 0x7fc2c15a4268> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has experimental_relax_shapes=True option that relaxes argument shapes that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/tutorials/customization/performance#python_or_tensor_args and https://www.tensorflow.org/api_docs/python/tf/function for  more details.
0.4320685863494873

【讨论】:

我还能够使用 pima-indians-diabetes.csv 重现相同的结果。但是当我在我的 ABIDE 数据集中运行它时,我无法重现相同的结果。我认为问题可能出在我的数据集中,对吧?

以上是关于为啥我在使用 Scikit-Learn Keras 模型函数时,对于相同的网络配置会得到不同的准确度结果?的主要内容,如果未能解决你的问题,请参考以下文章

Scikit-Learn 包装器和 RandomizedSearchCV:RuntimeError

如何在 Python 中使用带有 Keras 的 scikit-learn 评估指标函数?

使用 scikit-learn 对具有多个输入的 Keras 模型进行交叉验证

从磁盘加载包含预训练 Keras 模型的 scikit-learn 管道

keras 和 scikit-learn 中 MLP 回归器的不同损失值和准确度

如何在 scikit-learn 管道中将时代添加到 Keras 网络