Write your first artificial neural network in Keras


Tutorial overview: You don't need to write much code here, but we'll show you step by step how to create your own models later. The tutorial will cover the following steps:

  • Download Data

  • Define the model

  • Compile the model

  • Train the model

  • Evaluation model

  • Combine all steps together

Prerequisites for this tutorial:

  • Environment and programming foundation with python 2 or 3

  • Install and configure the Scipy library (including Numpy)

  • You have Keras installed and have a backend (Theano or TensorFlow)

Create a new file named keras_first_network.py and copy the tutorial code step by step into it.

1. Load data


Whenever we use machine learning algorithms that use random processes (such as random numbers), it is a good practice to set the random number seed first.

This way you can run the same code again and again and get the same results. This is useful if you need to prove results, compare algorithms or debug code using random data.

You can initialize the random number generator and its seed, for example:

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

Now we can load our data. In this tutorial, we will use the Pima Indians Diabetes Dataset (http://archive.ics.uci.edu/ml/datasets/Pima+Indians+Diabetes). This is a standard machine learning from the UCI Machine Learning Database data set. It describes patients' medical records and whether they became ill within five years.

Therefore, it is a binary classification problem (1 if diabetes occurs, 0 otherwise). All input variables describing patients are numeric values. This facilitates direct use in neural networks that require numerical input and output, suitable for our first Keras neural network. Download the dataset and rename it to pima-indians-diabetes.csv into data/pima-indians-diabetes.csv in the directory where the python script is located.

You can just load the data directly using the loadtxt() method of the Numpy library, with a total of 8 output variables and 1 output variable (last column). After loading we can separate the data into X (output variables) and Y (output classifications)

# load pima indians dataset
dataset = numpy.loadtxt("data/pima-indians-diabetes.csv", delimiter=",")
# split into input (X) and output (Y) variables
X = dataset[:, 0:8]
Y = dataset[:, 8]

We've initialized our random number generator to ensure reproducible results, and loaded the data. We are now ready to define our neural network model.

2. Define the model


A model in Keras is defined as a series of layers.

We instantiate a Sequential model object, adding one layer at a time until we are satisfied with the topology of the network.

The first thing we need to make sure is the number of output neurons. This can be defined by setting the parameter input_dim when the model is created. We set this parameter to 8 corresponding to 8 output variables. How do we know the number of layers and their types?

This is a very difficult question to answer. This is heuristic, we find the best network structure by trial and error, in general, you need a large enough network to understand whether the structure is useful for the problem. In this example, we use a three-layer fully connected structure.

Fully connected layers are defined using Dense. We can define the number of neurons in the layer through the first parameter, the second parameter init defines the initialization method of the weights, and the activation parameter defines the activation function.

在这个例子中, 我们把权重初始化成一个服从均匀分布的小随机数(init='uniform'),在0到0.05直接(这是 Keras 标准均匀分布权重初始值)。另一种传统的选择是‘normal’,会从高斯分布(正态分布)中产生一个小的随机数。

我们在前两层使用 (relu)[https://en.wikipedia.org/wiki/Rectifier_(neural_networks)] 激活函数, 在输出层使用 Sigmoid 函数。曾经 Sigmoid 和 tanh 激活函数是所有的层首选的。但时至今日, 使用 relu 激活函数可以达到更好的性能。我们在输出层使用 Sigmoid 函数来确保网络输出在 0 和 1 之间,

我们可以添加每一层将这些东西放到一起。第一层有 12 个神经元、8个输出变量。第二层有 8 个神经元和最后 1 个神经元的输出层用于预测类别(糖尿病有无发病)

# create model
model = Sequential()
model.add(Dense(12, input_dim=8, init='uniform', activation='relu'))
model.add(Dense(8, init='uniform', activation='relu'))
model.add(Dense(1, init='uniform', activation='sigmoid'))

3. 编译模型


现在我们定义好模型, 那么就可以编译他了。

编译使用高效的数学库, 封装了 Theano 或者 TensorFlow(称为 backend)。后端(backend)在你的硬件上自动选择最好的方式去表现用于训练和预测的神经网络,比如 CPU、GPU 或者分布式。

编译时, 我们需要额外定义训练网络所需要的参数。记住, 训练网络意味着寻找最优的权重集去预测。

我们需要定义评估权重集的损失函数, 用于寻找不同权重的优化器以及我们希望在训练过程呈现的可选指标。

在这个例子中, 我们使用对数损失函数(logarithmic loss), 对于二分类问题, 其在 Keras 中称为“binary_crossentropy”。我们还将使用梯度下降算法‘adam’, 没有为什么, 它就是一种高效地默认方法。想了解更多这种算法可以查看论文: (Adam: A Method for Stochastic Optimization)[http://arxiv.org/abs/1412.6980]

最后, 以为这是一个分类问题, 所以我们会收集和汇报分类的准确率作为度量指标。

# Compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

4. 训练模型


我们已经定义和编译了模型, 他是为高效地计算而准备的。

现在是时候在数据上训练模型了。

我们可以在加载的数据上训练和拟合模型,通过 fit() 函数。

训练过程会在数据集迭代一定的次数,成为 epochs, 这个可以通过 nb_epoch 参数来设定。我们也可以设定 batch_size 参数来指定进行梯度下降时每个batch包含的样本数。训练时一个batch的样本会被计算一次梯度下降, 使目标函数优化一步。在这个例子中, 我们将迭代150次、批处理大小为10。再说一次, 这些参数可以通过试错来选择。

# Fit the model
model.fit(X, Y, nb_epoch=150, batch_size=10)

这就是在你的 CPU 或者 GPU 上发生的事情。

5. 评估模型


我们已经在整个数据集上训练了我们的神经网络, 我们可以在线通的数据集上评估神经网络的性能。

这只会告诉我们模型有多适合已有的数据(训练的准确率),但我们无从知道算法在新数据上的性能。

我们可以简单但很理想地把数据分为训练集和测试集来分别训练和评估模型。

你可以通过 evaluate() 函数在训练集评估你的模型, 使用你训练模型时相同的输出和输出。

这会针对每一个输出-输出产生预测并且收集分数,包括平均损失和其他我们定义的指标,比如准确率。

# evaluate the model
scores = model.evaluate(X, Y)
print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))

6. 将这些放在一起


你已经看到用 Keras 创建你的第一个神经网络有多么简单、

运行以上的代码, 将会看到150个迭代中, 每次迭代的损失和准确率,以及最终的模型在训练集上的评估结果, 在我的 CPU 上耗时 10s(使用 Theano 作为后端)

...Epoch 143/150768/768 [==============================] - 0s - loss: 0.4614 - acc: 0.7878Epoch 144/150768/768 [==============================] - 0s - loss: 0.4508 - acc: 0.7969Epoch 145/150768/768 [==============================] - 0s - loss: 0.4580 - acc: 0.7747Epoch 146/150768/768 [==============================] - 0s - loss: 0.4627 - acc: 0.7812Epoch 147/150768/768 [==============================] - 0s - loss: 0.4531 - acc: 0.7943Epoch 148/150768/768 [==============================] - 0s - loss: 0.4656 - acc: 0.7734Epoch 149/150768/768 [==============================] - 0s - loss: 0.4566 - acc: 0.7839Epoch 150/150768/768 [==============================] - 0s - loss: 0.4593 - acc: 0.7839768/768 [==============================] - 0sacc: 79.56%

如果你尝试在 IPython 或者 Jupyter , 你将会得到错误。原因是在训练期间输出进度条。你可以关闭这个, 通过让 model.fit() 的参数 verbose=0

福利: 做出预测


我被问得最多的一个问题是:

在我训练模型之后, 怎么预测新数据的分类?

这是个好问题。

我们拟合了上述例子, 用他来在训练集上作出预测, 假装我们之前没看到过这些数据。

做预测同样非常简单, 只需要使用 model.predict()。我们在输出层使用 Sigmoid 激活函数, 因此我们的预测值将会在 0 到 1 的区间内。在这个分类任务中,我们可以轻易地通过四舍五入转换为离散二分类。

预测训练集中每一个记录的完整例子如下:

# Create first network with Keras
from keras.models import Sequential
from keras.layers import Dense
import numpy
# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)
# load pima indians dataset
dataset = numpy.loadtxt("pima-indians-diabetes.csv", delimiter=",")
# split into input (X) and output (Y) variables
X = dataset[:,0:8]
Y = dataset[:,8]
# create model
model = Sequential()
model.add(Dense(12, input_dim=8, init='uniform', activation='relu'))
model.add(Dense(8, init='uniform', activation='relu'))
model.add(Dense(1, init='uniform', activation='sigmoid'))
# Compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
# Fit the model
model.fit(X, Y, nb_epoch=150, batch_size=10,  verbose=2)
# calculate predictions
predictions = model.predict(X)
# round predictions
rounded = [round(x) for x in predictions]
print(rounded)

运行这个修改过的例子, 将会打印出每个输出的预测值。如果有需要的话, 我们可以直接使用这些预测。

总结


在这篇文章当中, 我们学会了如何通过 Keras 创建自己的第一个神经网络模型。

特别是我们学会了 使用 Keras 来创建神经网络或深度学习模型时关键的 5 个步骤:

  • 加载数据

  • 定义模型

  • 编译模型

  • 训练模型

  • 评估模型

∞∞∞



640?wx_fmt=jpeg&wx_lazy=1

IT派 - {技术青年圈} 持续关注互联网、区块链、人工智能领域 640?wx_fmt=jpeg&wx_lazy=1



公众号回复“机器学习”

邀你加入{ IT派AI机器学习群 } 


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325762738&siteId=291194637