Keras Sequential模型调用predict_proba报错,疑版本问题求助
解决Keras中
predict_proba属性不存在的问题 问题背景
你尝试通过以下代码获取分类模型的类别概率:
# example making new probability predictions for a classification problem from keras.models import Sequential from keras.layers import Dense from sklearn.datasets import make_blobs from sklearn.preprocessing import MinMaxScaler # generate 2d classification dataset X, y = make_blobs(n_samples=100, centers=2, n_features=2, random_state=1) scalar = MinMaxScaler() scalar.fit(X) X = scalar.transform(X) # define and fit the final model model = Sequential() model.add(Dense(4, input_shape=(2,), activation='relu')) model.add(Dense(4, activation='relu')) model.add(Dense(1, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam') model.fit(X, y, epochs=500, verbose=0) # new instances where we do not know the answer Xnew, _ = make_blobs(n_samples=3, centers=2, n_features=2, random_state=1) Xnew = scalar.transform(Xnew) # make a prediction ynew = model.predict_proba(Xnew) # show the inputs and predicted outputs for i in range(len(Xnew)): print("X=%s, Predicted=%s" % (Xnew[i], ynew[i]))
运行时出现错误:
AttributeError: 'Sequential' object has no attribute 'predict_proba'
推测是版本更新导致的方法移除。
解决方案
在TensorFlow 2.x整合后的Keras版本中,predict_proba方法已被移除,直接使用predict方法即可获取概率值:
- 对于二分类任务(如你的代码中使用
sigmoid激活),model.predict(Xnew)会直接返回每个样本属于正类的概率,和原predict_proba的输出完全一致。 - 对于多分类任务(使用
softmax激活),predict返回的是每个样本在所有类别上的概率分布,同样可以替代predict_proba。
修改后的核心代码行:
ynew = model.predict(Xnew)
修改后的完整代码
# example making new probability predictions for a classification problem from keras.models import Sequential from keras.layers import Dense from sklearn.datasets import make_blobs from sklearn.preprocessing import MinMaxScaler # generate 2d classification dataset X, y = make_blobs(n_samples=100, centers=2, n_features=2, random_state=1) scalar = MinMaxScaler() scalar.fit(X) X = scalar.transform(X) # define and fit the final model model = Sequential() model.add(Dense(4, input_shape=(2,), activation='relu')) model.add(Dense(4, activation='relu')) model.add(Dense(1, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam') model.fit(X, y, epochs=500, verbose=0) # new instances where we do not know the answer Xnew, _ = make_blobs(n_samples=3, centers=2, n_features=2, random_state=1) Xnew = scalar.transform(Xnew) # make a prediction - 使用predict替代predict_proba ynew = model.predict(Xnew) # show the inputs and predicted outputs for i in range(len(Xnew)): print("X=%s, Predicted=%s" % (Xnew[i], ynew[i]))
内容的提问来源于stack exchange,提问作者Phoenix
相关产品推荐
相关产品推荐

