一旦你在Keras中选择并适合最终的深度学习模型,你就可以用它来对新的数据实例进行预测。
在初学者中,对于究竟如何做这件事存在一些困惑。我经常看到这样的问题。
我如何用Keras中的模型进行预测?
在本教程中,你将发现究竟如何利用Keras Python库的最终深度学习模型来进行分类和回归预测。
完成本教程后,你将知道。
- 如何最终确定一个模型,以使其准备好进行预测。
- 如何在Keras中对分类问题进行类别和概率预测。
- 如何在Keras中进行回归预测。
教程概述
本教程分为3个部分,它们是
- 最终确定模型
- 分类预测
- 回归预测
1.最终确定模型
在你进行预测之前,你必须训练一个最终模型。
你可能已经使用k-fold交叉验证或数据的训练/测试分割来训练模型。这样做的目的是为了让你估计模型在非样本数据上的技能,例如新数据。
这些模型已经达到了它们的目的,现在可以被丢弃了。
你现在必须在所有可用数据上训练一个最终模型。你可以在这里了解更多关于如何训练一个最终模型的信息。
2.分类预测
分类问题是指模型学习输入特征和输出特征之间的映射,即一个标签,如 "垃圾邮件"和 "非垃圾邮件"。
下面是一个在Keras中为一个简单的两类(二进制)分类问题开发的最终神经网络模型的例子。
# example of training a final classification model
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=200, verbose=0)
在最终确定之后,你可能想把模型保存到文件中,例如通过Keras API。一旦保存,你就可以随时加载模型,用它来进行预测。关于这方面的例子,请看帖子。
为了简单起见,在本教程的例子中,我们将跳过这一步。
有两种类型的分类预测,我们可能希望用我们最终确定的模型进行预测;它们是类别预测和概率预测。
类别预测
类预测是给定最终模型和一个或多个数据实例,预测数据实例的类别。
我们不知道新数据的结果类别。这就是我们首先需要模型的原因。
我们可以在Keras中使用predict_classes()函数,用我们最终确定的分类模型来预测新数据实例的类别。注意,这个函数只适用于序列模型,而不是那些使用函数式API开发的模型。
例如,我们在一个名为Xnew的数组中拥有一个或多个数据实例。这可以被传递给我们模型上的*predict_classes()*函数,以便预测数组中每个实例的类值。
Xnew = [[...], [...]]
ynew = model.predict_classes(Xnew)
让我们用一个例子来具体说明这个问题。
# example making new class 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_classes(Xnew)
# show the inputs and predicted outputs
for i in range(len(Xnew)):
print("X=%s, Predicted=%s" % (Xnew[i], ynew[i]))
运行这个例子可以预测三个新的数据实例的类别,然后把数据和预测结果一起打印出来。
注意:鉴于算法或评估程序的随机性,或者数字精度的差异,你的结果可能会有所不同。考虑将这个例子运行几次并比较平均结果。
X=[0.89337759 0.65864154], Predicted=[0]
X=[0.29097707 0.12978982], Predicted=[1]
X=[0.78082614 0.75391697], Predicted=[0]
如果你只有一个新的数据实例,你可以把它作为一个用数组包装的实例提供给predict_classes()函数;例如:
# example making new class prediction 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
from numpy import array
# 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 instance where we do not know the answer
Xnew = array([[0.89337759, 0.65864154]])
# make a prediction
ynew = model.predict_classes(Xnew)
# show the inputs and predicted outputs
print("X=%s, Predicted=%s" % (Xnew[0], ynew[0]))
运行这个例子会打印出单个实例和预测的类别。
注意:鉴于算法或评估程序的随机性,或者数字精度的差异,你的结果可能会有所不同。请考虑多运行几次这个例子,并比较平均结果。
X=[0.89337759 0.65864154], Predicted=[0]
关于类标签的说明
请注意,当你准备你的数据时,你将把你的领域中的类值(如字符串)映射为整数值。
这个LabelEncoder可以被用来通过inverse_transform()函数将整数转换回字符串值。
出于这个原因,你可能想在拟合最终模型时保存(pickle)用于编码y值的LabelEncoder。
概率预测
你可能想做的另一种预测是数据实例属于每个类别的概率。
这被称为概率预测,给定一个新的实例,模型将每个结果类的概率作为0和1之间的值返回。
你可以通过调用*predict_proba()*函数在Keras中进行这些类型的预测;例如。
Xnew = [[...], [...]]
ynew = model.predict_proba(Xnew)
在两类(二进制)分类问题中,输出层通常使用sigmoid激活函数。预测的概率被认为是观察结果属于第1类的可能性,或者倒置(1-概率)以得到第0类的概率。
在多类分类问题的情况下,输出层通常使用softmax激活函数,每个类的观察概率被作为一个向量返回。
下面的例子对数据实例的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
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]))
运行实例进行概率预测,然后打印出输入数据实例和每个实例属于第1类的概率。
注意:鉴于算法或评估程序的随机性,或数字精度的差异,你的结果可能会有所不同。考虑将这个例子运行几次并比较平均结果。
X=[0.89337759 0.65864154], Predicted=[0.0087348]
X=[0.29097707 0.12978982], Predicted=[0.82020265]
X=[0.78082614 0.75391697], Predicted=[0.00693122]
如果你想把概率呈现给用户供专家解释,这在你的应用中会很有帮助。
3.回归预测
回归是一个有监督的学习问题,在这个问题上,给定的输入例子,模型会学习到合适的输出量的映射,如 "0.1 "和 "0.2",等等。
下面是一个最终完成的Keras回归模型的例子。
# example of training a final regression model
from keras.models import Sequential
from keras.layers import Dense
from sklearn.datasets import make_regression
from sklearn.preprocessing import MinMaxScaler
# generate regression dataset
X, y = make_regression(n_samples=100, n_features=2, noise=0.1, random_state=1)
scalarX, scalarY = MinMaxScaler(), MinMaxScaler()
scalarX.fit(X)
scalarY.fit(y.reshape(100,1))
X = scalarX.transform(X)
y = scalarY.transform(y.reshape(100,1))
# 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='linear'))
model.compile(loss='mse', optimizer='adam')
model.fit(X, y, epochs=1000, verbose=0)
我们可以通过对最终确定的模型调用predict()函数,用最终确定的回归模型来预测数量。
predict()函数接收一个或多个数据实例的数组。
下面的例子演示了如何对具有未知预期结果的多个数据实例进行回归预测。
# example of making predictions for a regression problem
from keras.models import Sequential
from keras.layers import Dense
from sklearn.datasets import make_regression
from sklearn.preprocessing import MinMaxScaler
# generate regression dataset
X, y = make_regression(n_samples=100, n_features=2, noise=0.1, random_state=1)
scalarX, scalarY = MinMaxScaler(), MinMaxScaler()
scalarX.fit(X)
scalarY.fit(y.reshape(100,1))
X = scalarX.transform(X)
y = scalarY.transform(y.reshape(100,1))
# 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='linear'))
model.compile(loss='mse', optimizer='adam')
model.fit(X, y, epochs=1000, verbose=0)
# new instances where we do not know the answer
Xnew, a = make_regression(n_samples=3, n_features=2, noise=0.1, random_state=1)
Xnew = scalarX.transform(Xnew)
# make a prediction
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]))
运行这个例子可以进行多次预测,然后将输入和预测结果并排打印出来,以供查阅。
注意:鉴于算法或评估程序的随机性,或数字精度的差异,你的结果可能会有所不同。考虑多运行几次这个例子,并比较平均结果。
X=[0.29466096 0.30317302], Predicted=[0.17097184]
X=[0.39445118 0.79390858], Predicted=[0.7475489]
X=[0.02884127 0.6208843 ], Predicted=[0.43370453]
同样的函数可以用来对单个数据实例进行预测,只要它被适当地包裹在周围的列表或数组中。
比如说。
# example of making predictions for a regression problem
from keras.models import Sequential
from keras.layers import Dense
from sklearn.datasets import make_regression
from sklearn.preprocessing import MinMaxScaler
from numpy import array
# generate regression dataset
X, y = make_regression(n_samples=100, n_features=2, noise=0.1, random_state=1)
scalarX, scalarY = MinMaxScaler(), MinMaxScaler()
scalarX.fit(X)
scalarY.fit(y.reshape(100,1))
X = scalarX.transform(X)
y = scalarY.transform(y.reshape(100,1))
# 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='linear'))
model.compile(loss='mse', optimizer='adam')
model.fit(X, y, epochs=1000, verbose=0)
# new instance where we do not know the answer
Xnew = array([[0.29466096, 0.30317302]])
# make a prediction
ynew = model.predict(Xnew)
# show the inputs and predicted outputs
print("X=%s, Predicted=%s" % (Xnew[0], ynew[0]))
运行该例子进行一次预测,并打印出数据实例和预测结果供审查。
注意:鉴于算法或评估程序的随机性,或数字精度的差异,你的结果可能会有所不同。考虑多运行几次这个例子,比较一下平均结果。
X=[0.29466096 0.30317302], Predicted=[0.17333156]
摘要
在本教程中,你发现了如何利用Keras Python库中的最终深度学习模型进行分类和回归预测。
具体来说,你学到了。
- 如何最终确定一个模型,以使其准备好进行预测。
- 如何在Keras中对分类问题进行类别和概率预测。
- 如何在Keras中进行回归预测。