如何用Keras进行预测

一旦你在Keras中选择并适合最终的深度学习模型,你就可以使用它对新数据实例进行预测。

在初学者中,有一些关于如何确切地做到这一点的困惑。我经常看到这样的问题:

我如何在Keras用我的模型进行预测?

在本教程中,你将确切了解如何使用Keras Python库的最终深度学习模型进行分类和回归预测。

完成本教程后,你将了解:

  • 如何最终确定模型,以便为进行预测做好准备。
  • 如何对Keras中的分类问题进行分类和概率预测。
  • 如何在“Keras”中进行回归预测。

我们开始吧。

教程概述

本教程分为3个部分,它们是:

  • 最终确定模型。
  • 分类预测。
  • 回归预测。

1.最终确定模型

在你做出预测之前,你必须训练一个最终的模型。

你可能已经使用数据的k倍交叉验证或训练/测试分离对模型进行了训练。这样做是为了让你评估模型在样本外数据(例如新数据)上的技

能。

这些模型已经达到了它们的目的,现在可以丢弃了。

现在,你必须根据所有可用的数据训练最终模型。你可以在此处了解有关如何训练最终模型的更多信息:

2.分类预测

分类问题是模型学习输入特征和作为标签的输出特征(如“垃圾邮件”和“非垃圾邮件”)之间的映射的问题。

下面是在Keras中为简单的两类(二进制)分类问题开发的最终神经网络模型的示例。

如果你对在Keras中开发神经网络模型很陌生,请参阅此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_dim=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()函数来预测新数据实例的类。请注意,此功能仅在

Sequential模型上可用,而不是使用Functional API开发的那些模型。

例如,我们在名为Xnew的数组中有一个或多个数据实例。为了预测数组中每个实例的类值,可以将其传递给我们模型上的

forecast_class()函数。

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_dim=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_dim=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]

关于类标号的一个注记

请注意,当你准备数据时,你会将域(如字符串)中的类值映射到整数值。你可能使用过LabelEncoding。

此LabelEncoding可用于通过inverse_transform()函数将整数转换回字符串值。

因此,你可能希望在拟合最终模型时保存(pickle)用于编码y值的LabelEncoding。

概率预测

你可能希望进行的另一种预测是数据实例属于每个类的概率。

这称为概率预测,在给定新实例的情况下,模型将每个结果类的概率作为介于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_dim=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_dim=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()函数来预测最终回归模型的数量。

函数的作用是:获取一个或多个数据实例的数组。

下面的示例演示了如何对具有未知预期结果的多个数据实例进行回归预测。

# 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_dim=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_dim=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”中进行回归预测。

00

Python

发表评论

邮箱地址不会被公开。 必填项已用*标注

什么阻碍了你实现迈入机器学习领域的目标?

什么阻碍了你实现迈入机器学习领域的目标?

2020-04-22 机器学习

如果你在为进入机器学习领域而挣扎,感觉到有什么东西阻止了自己的开始,那么你应该看看这篇文章。 在这篇文章中,我们会讨论阻止进入机器学习领域的自我限制的信念,让你明白面临的问题。 几乎总是一种自我限制的信念阻碍了你们的进步。 也许你会在一个或多个这样的信念中看到自己。如果是这样的话, [......]

了解详情

R语言机器学习迷你课程

R语言机器学习迷你课程

2020-08-12 机器学习

在这个迷你课程中,你将发现如何开始,构建精确的模型,并自信地完成在14天内使用R预测建模机器学习项目。 这是一个重要而重要的文章。你可能想把它书签。 了解如何准备数据,拟合机器学习模型,并用我的新书评估他们在r上的预测,包括14步教程、3个项目和完整源代码。 我们开始吧。 [......]

了解详情

关于机器学习的几点思考

关于机器学习的几点思考

2020-04-26 机器学习

机器学习是一个大的、跨学科的研究领域。 你可以通过机器学习获得令人印象深刻的结果,并找到非常具有挑战性的问题的解决方案。但这只是更广泛的机器学习领域的一小部分,通常被称为预测建模或预测分析。 在这篇文章中,你将发现如何改变你对机器学习的思考方式,以便更好地为你提供机器学习实践者的服务。 [......]

了解详情

找到你的机器学习部落

找到你的机器学习部落

2020-04-26 机器学习

机器学习是一个充满算法和数据的迷人而强大的研究领域。 问题是,有这么多不同类型的人对机器学习感兴趣,每个人都有不同的需求。重要的是要了解你想要从机器学习中得到什么,并根据这些需求调整你的自学。 如果你不这样做,你很容易就会陷入困境,迷失方向,失去兴趣,得不到你想要的东西。 找到 [......]

了解详情

应用机器学习过程

应用机器学习过程

2020-04-26 机器学习

随着时间的推移,在处理应用机器学习问题时,你会开发出一种模式或流程,以快速获得良好的正常结果。 一旦开发完成,你就可以在一个又一个项目上反复使用此过程。你的流程越健壮、越发达,你就能越快地获得可靠的结果。 在这篇文章中,我想与你分享我解决机器学习问题的过程框架。 你可以将其用作下一 [......]

了解详情