提交 45f835d9 编写于 作者: W wizardforcel

code highlight

上级 a80998a0
......@@ -46,14 +46,14 @@ Keras 中神经网络模型的 5 步生命周期
例如,我们可以分两步完成:
```
```py
model = Sequential()
model.add(Dense(2))
```
但是我们也可以通过创建一个图层数组并将其传递给 Sequential 的构造函数来一步完成。
```
```py
layers = [Dense(2)]
model = Sequential(layers)
```
......@@ -62,7 +62,7 @@ model = Sequential(layers)
例如,一个小的多层感知器模型,在可见层中有 2 个输入,隐藏层中有 5 个神经元,输出层中有一个神经元,可以定义为:
```
```py
model = Sequential()
model.add(Dense(5, input_dim=2))
model.add(Dense(1))
......@@ -72,7 +72,7 @@ model.add(Dense(1))
这在 Keras 中是一个有用的概念,因为传统上与图层相关的关注点也可以拆分并作为单独的图层添加,清楚地显示它们在从输入到预测的数据转换中的作用。例如,可以提取转换来自层中每个神经元的求和信号的激活函数,并将其作为称为激活的层状对象添加到 Sequential 中。
```
```py
model = Sequential()
model.add(Dense(5, input_dim=2))
model.add(Activation('relu'))
......@@ -102,7 +102,7 @@ model.add(Activation('sigmoid'))
例如,下面是编译定义模型并指定随机梯度下降(sgd)优化算法和均方误差(mse)损失函数的情况,用于回归类型问题。
```
```py
model.compile(optimizer='sgd', loss='mse')
```
......@@ -128,7 +128,7 @@ model.compile(optimizer='sgd', loss='mse')
例如:
```
```py
model.compile(optimizer='sgd', loss='mse', metrics=['accuracy'])
```
......@@ -146,7 +146,7 @@ model.compile(optimizer='sgd', loss='mse', metrics=['accuracy'])
拟合网络的最小例子如下:
```
```py
history = model.fit(X, y, batch_size=10, epochs=100)
```
......@@ -164,7 +164,7 @@ history = model.fit(X, y, batch_size=10, epochs=100)
例如,对于使用精度度量编制的模型,我们可以在新数据集上对其进行评估,如下所示:
```
```py
loss, accuracy = model.evaluate(X, y)
```
......@@ -176,7 +176,7 @@ loss, accuracy = model.evaluate(X, y)
例如:
```
```py
predictions = model.predict(x)
```
......@@ -204,7 +204,7 @@ predictions = model.predict(x)
完整的代码清单如下。
```
```py
# Sample Multilayer Perceptron Neural Network in Keras
from keras.models import Sequential
from keras.layers import Dense
......@@ -233,7 +233,7 @@ print("Prediction Accuracy: %.2f%%" % (accuracy*100))
运行此示例将生成以下输出:
```
```py
...
768/768 [==============================] - 0s - loss: 0.5219 - acc: 0.7591
Epoch 99/100
......
......@@ -85,13 +85,13 @@ Theano 表达式的实际语法是象征性的,这对于习惯于正常软件
例如,您可以使用 pip 安装 Theano,如下所示:
```
```py
sudo pip install Theano
```
下面列出了一个可以用作起点的 Theano 程序的小例子:
```
```py
import theano
from theano import tensor
# declare two symbolic floating-point scalars
......@@ -121,13 +121,13 @@ TensorFlow 是一个用于 Google 创建和发布的快速数值计算的 Python
例如,您可以使用 pip 安装 TensorFlow:
```
```py
sudo pip install TensorFlow
```
下面列出了一个可以用作起点的 TensorFlow 程序的小例子:
```
```py
import tensorflow as tf
# declare two symbolic floating-point scalars
a = tf.placeholder(tf.float32)
......@@ -166,7 +166,7 @@ Keras 的重点是模型的概念。模型的生命周期可归纳如下:
例如,您可以使用 pip 安装 Keras:
```
```py
sudo pip install keras
```
......@@ -218,7 +218,7 @@ Keras 允许您在极少数代码行中开发和评估深度学习模型。
它假设您[将 Pima Indians 数据集](https://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data)下载到您当前的工作目录中,文件名为 _pima-indians-diabetes.csv_ (更新:[从这里下载](https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.data.csv)) 。
```
```py
# Create first network with Keras
from keras.models import Sequential
from keras.layers import Dense
......@@ -263,7 +263,7 @@ Keras 提供了一个包装类,允许您使用 scikit-learn 的深度学习模
例如,您可以定义 KerasClassifier 的实例和自定义函数来创建模型,如下所示:
```
```py
# Function to create model, required for KerasClassifier
def create_model():
# Create model
......@@ -296,7 +296,7 @@ Keras 提供了在训练深度学习模型时注册回调的功能。
例如,您可以打印历史记录对象收集的指标列表,如下所示:
```
```py
# list all data in history
history = model.fit(...)
print(history.history.keys())
......@@ -318,7 +318,7 @@ Keras 库通过回调 API 提供检查点功能。 ModelCheckpoint
您可以定义 ModelCheckpoint,每次观察到改进时,都会将网络权重保存到同一文件中。例如:
```
```py
from keras.callbacks import ModelCheckpoint
...
checkpoint = ModelCheckpoint('weights.best.hdf5', monitor='val_acc', save_best_only=True, mode='max')
......@@ -343,7 +343,7 @@ Dropout 是一种简单但非常有效的减少丢失的技术,并且已证明
例如,您可以创建一个概率为 20%的辍学图层,并将其添加到您的模型中,如下所示:
```
```py
from keras.layers import Dropout
...
model.add(Dropout(0.2))
......@@ -365,7 +365,7 @@ Keras 具有基于时间的学习速率计划,该计划内置于 SGD 类中的
例如,您可以指定从 0.1 开始的学习率计划,每个时期下降 0.0001,如下所示:
```
```py
from keras.optimizers import SGD
...
sgd = SGD(lr=0.1, momentum=0.9, decay=0.0001, nesterov=False)
......@@ -410,7 +410,7 @@ MNIST 数据集是用于评估手写数字识别问题的算法的标准问题
例如,您可以在 Keras 中加载 MNIST 数据集,如下所示:
```
```py
from keras.datasets import mnist
...
(X_train, y_train), (X_test, y_test) = mnist.load_data()
......@@ -420,14 +420,14 @@ from keras.datasets import mnist
作为提示,您将用作第一个隐藏层的 Keras [Conv2D](http://keras.io/layers/convolutional/) 层需要格式为 x 宽 x 高的格式的图像数据,其中 MNIST 数据具有 1 个通道,因为图像是灰度级的宽度和高度为 28 像素。您可以轻松地重塑 MNIST 数据集,如下所示:
```
```py
X_train = X_train.reshape(X_train.shape[0], 1, 28, 28)
X_test = X_test.reshape(X_test.shape[0], 1, 28, 28)
```
您还需要对输出类值进行单热编码,Keras 还提供了一个方便的辅助函数来实现:
```
```py
from keras.utils import np_utils
...
y_train = np_utils.to_categorical(y_train)
......@@ -436,7 +436,7 @@ y_test = np_utils.to_categorical(y_test)
作为最后的提示,这里是一个模型定义,您可以将其作为起点:
```
```py
model = Sequential()
model.add(Conv2D(32, (3, 3), padding='valid', input_shape=(1, 28, 28),
activation='relu'))
......@@ -465,7 +465,7 @@ CIFAR-10 图像的小样本
例如,您可以在 Keras 中加载 CIFAR-10 数据集并准备与卷积神经网络一起使用,如下所示:
```
```py
from keras.datasets import cifar10
from keras.utils import np_utils
# load data
......@@ -491,7 +491,7 @@ Keras 提供了一个图像增强 API,可以及时在数据集中创建图像
例如,下面的示例在 MNIST 数据集中创建最多 90 度图像的随机旋转。
```
```py
# Random Rotations
from keras.datasets import mnist
from keras.preprocessing.image import ImageDataGenerator
......
......@@ -44,7 +44,7 @@ Keras 允许您快速简单地设计和训练神经网络和深度学习模型
我们将首先导入我们需要的所有类和函数。
```
```py
import numpy
import pandas
from keras.models import Sequential
......@@ -59,7 +59,7 @@ from sklearn.pipeline import Pipeline
接下来,我们可以初始化随机数生成器,以确保在执行此代码时始终获得相同的结果。如果我们正在调试,这将有所帮助。
```
```py
# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)
......@@ -67,7 +67,7 @@ numpy.random.seed(seed)
现在我们可以使用 [pandas](http://pandas.pydata.org/) 加载数据集,并将列拆分为 60 个输入变量(X)和 1 个输出变量(Y)。我们使用 pandas 来加载数据,因为它可以轻松处理字符串(输出变量),而尝试使用 NumPy 直接加载数据会更加困难。
```
```py
# load dataset
dataframe = pandas.read_csv("sonar.csv", header=None)
dataset = dataframe.values
......@@ -80,7 +80,7 @@ Y = dataset[:,60]
我们可以使用 scikit-learn 中的 LabelEncoder 类来完成此操作。此类将通过 fit()函数使用整个数据集对所需的编码进行建模,然后应用编码以使用 transform()函数创建新的输出变量。
```
```py
# encode class values as integers
encoder = LabelEncoder()
encoder.fit(Y)
......@@ -99,7 +99,7 @@ encoded_Y = encoder.transform(Y)
最后,我们在训练期间使用对数损失函数(binary_crossentropy),这是二进制分类问题的首选损失函数。该模型还使用有效的 Adam 优化算法进行梯度下降,并在训练模型时收集精度度量。
```
```py
# baseline model
def create_baseline():
# create model
......@@ -115,7 +115,7 @@ def create_baseline():
我们再次使用合理的默认值将训练时期的数量传递给 KerasClassifier。假设模型将被创建 10 次以进行 10 次交叉验证,也会关闭详细输出。
```
```py
# evaluate model with standardized dataset
estimator = KerasClassifier(build_fn=create_baseline, epochs=100, batch_size=5, verbose=0)
kfold = StratifiedKFold(n_splits=10, shuffle=True, random_state=seed)
......@@ -125,7 +125,7 @@ print("Results: %.2f%% (%.2f%%)" % (results.mean()*100, results.std()*100))
运行此代码将生成以下输出,显示模型在未见数据上的估计精度的平均值和标准差。
```
```py
Baseline: 81.68% (7.26%)
```
......@@ -145,7 +145,7 @@ Baseline: 81.68% (7.26%)
我们可以使用 [Pipeline](http://scikit-learn.org/stable/modules/generated/sklearn.pipeline.Pipeline.html) 在 scikit-learn 中实现这一点。管道是一个包装器,它在交叉验证过程的传递中执行一个或多个模型。在这里,我们可以使用 StandardScaler 定义管道,然后使用我们的神经网络模型。
```
```py
# evaluate baseline model with standardized dataset
numpy.random.seed(seed)
estimators = []
......@@ -159,7 +159,7 @@ print("Standardized: %.2f%% (%.2f%%)" % (results.mean()*100, results.std()*100))
运行此示例提供以下结果。我们确实看到一个小而非常好的升力平均精度。
```
```py
Standardized: 84.56% (5.74%)
```
......@@ -181,7 +181,7 @@ Standardized: 84.56% (5.74%)
我们还将在数据准备的前一个实验中对数据进行标准化,并尝试利用性能的小提升。
```
```py
# smaller model
def create_smaller():
# create model
......@@ -204,7 +204,7 @@ print("Smaller: %.2f%% (%.2f%%)" % (results.mean()*100, results.std()*100))
这是一个很好的结果,因为我们在网络尺寸减半的情况下做得稍微好一些,而这只需要一半的时间来训练。
```
```py
Smaller: 86.04% (4.00%)
```
......@@ -216,7 +216,7 @@ Smaller: 86.04% (4.00%)
我们的网络现在具有拓扑结构:
```
```py
60 inputs -> [60 -> 30] -> 1 output
```
......@@ -224,7 +224,7 @@ Smaller: 86.04% (4.00%)
我们有一个额外的隐藏层来帮助这个过程,而不是压缩输入本身的表示。
```
```py
# larger model
def create_larger():
# create model
......@@ -246,7 +246,7 @@ print("Larger: %.2f%% (%.2f%%)" % (results.mean()*100, results.std()*100))
运行此示例将生成以下结果。我们可以看到,我们在模型性能方面没有得到提升。这可能是统计噪音或需要进一步培训的迹象。
```
```py
Larger: 83.14% (4.52%)
```
......
......@@ -23,14 +23,14 @@ Keras 库的重点是模型。
您可以创建一个 Sequential 模型并定义构造函数中的所有图层,例如:
```
```py
from keras.models import Sequential
model = Sequential(...)
```
更有用的习惯是创建一个 Sequential 模型并按照您希望执行的计算顺序添加图层,例如:
```
```py
from keras.models import Sequential
model = Sequential()
model.add(...)
......@@ -46,7 +46,7 @@ model.add(...)
例如,您可以按照 Dense 类型图层的 8 个输入定义输入,如下所示:
```
```py
Dense(16, input_dim=8)
```
......@@ -100,7 +100,7 @@ Keras 支持一系列标准神经元激活功能,例如:softmax,整流器
2. 损失功能。
3. 指标。
```
```py
model.compile(optimizer=, loss=, metrics=)
```
......@@ -110,14 +110,14 @@ model.compile(optimizer=, loss=, metrics=)
您可以创建优化器对象并通过优化器参数将其传递给编译函数。这允许您使用自己的参数(例如学习速率)配置优化过程。例如:
```
```py
sgd = SGD(...)
model.compile(optimizer=sgd)
```
您还可以通过为优化程序参数指定优化程序的名称来使用优化程序的默认参数。例如:
```
```py
model.compile(optimizer='sgd')
```
......@@ -153,7 +153,7 @@ model.compile(optimizer='sgd')
例如,使用 fit()函数在 NumPy 数组上训练模型
```
```py
model.fit(X, y, epochs=, batch_size=)
```
......@@ -185,19 +185,19 @@ model.fit(X, y, epochs=, batch_size=)
您可能希望输出模型的摘要。例如,您可以通过调用摘要函数来显示模型的摘要,例如:
```
```py
model.summary()
```
您还可以使用 get_config()函数检索模型配置的摘要,例如:
```
```py
model.get_config()
```
最后,您可以直接创建模型结构的图像。例如:
```
```py
from keras.utils.vis_utils import plot_model
plot(model, to_file='model.png')
```
......
......@@ -50,7 +50,7 @@ API 允许您指定要监控的度量标准,例如培训或验证数据集的
只有在验证数据集(monitor ='val_acc'和 mode ='max')的分类准确性有所提高时,才会设置检验点以保存网络权重。权重存储在一个文件中,该文件包含文件名中的分数(权重改进 - {val_acc = .2f} .hdf5)。
```
```py
# Checkpoint the weights when validation accuracy improves
from keras.models import Sequential
from keras.layers import Dense
......@@ -82,7 +82,7 @@ model.fit(X, Y, validation_split=0.33, epochs=150, batch_size=10, callbacks=call
运行该示例将生成以下输出(为简洁起见,将其截断):
```
```py
...
Epoch 00134: val_acc did not improve
Epoch 00135: val_acc did not improve
......@@ -104,7 +104,7 @@ Epoch 00149: val_acc did not improve
您将在工作目录中看到许多文件,其中包含 HDF5 格式的网络权重。例如:
```
```py
...
weights-improvement-53-0.76.hdf5
weights-improvement-71-0.76.hdf5
......@@ -122,7 +122,7 @@ weights-improvement-99-0.78.hdf5
在这种情况下,只有当验证数据集上模型的分类精度提高到目前为止最佳时,模型权重才会写入文件“weights.best.hdf5”。
```
```py
# Checkpoint the weights for best model on validation accuracy
from keras.models import Sequential
from keras.layers import Dense
......@@ -154,7 +154,7 @@ model.fit(X, Y, validation_split=0.33, epochs=150, batch_size=10, callbacks=call
运行此示例提供以下输出(为简洁起见,将其截断):
```
```py
...
Epoch 00139: val_acc improved from 0.79134 to 0.79134, saving model to weights.best.hdf5
Epoch 00140: val_acc did not improve
......@@ -171,7 +171,7 @@ Epoch 00149: val_acc did not improve
您应该在本地目录中看到权重文件。
```
```py
weights.best.hdf5
```
......@@ -187,7 +187,7 @@ weights.best.hdf5
然后使用该模型对整个数据集进行预测。
```
```py
# How to load and use weights from a checkpoint
from keras.models import Sequential
from keras.layers import Dense
......@@ -219,7 +219,7 @@ print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
运行该示例将生成以下输出:
```
```py
Created model and loaded weights from file
acc: 77.73%
```
......
......@@ -53,7 +53,7 @@
以下命令将使您登录到服务器实例。请记住将用户名和 IP 地址更改为相关的用户名和服务器实例 IP 地址。
```
```py
ssh -i ~/.ssh/aws-keypair.pem ec2-user@54.218.86.47
```
......@@ -63,7 +63,7 @@ ssh -i ~/.ssh/aws-keypair.pem ec2-user@54.218.86.47
以下示例在您的工作站上运行,将工作站本地目录中的 _script.py_ Python 脚本复制到您的服务器实例。
```
```py
scp -i ~/.ssh/aws-keypair.pem script.py ec2-user@54.218.86.47:~/
```
......@@ -75,7 +75,7 @@ scp -i ~/.ssh/aws-keypair.pem script.py ec2-user@54.218.86.47:~/
根据我的经验,所有这些都是长期运行脚本以适应大型深度学习模型所必需的。
```
```py
nohup python /home/ec2-user/script.py >/home/ec2-user/script.py.log </dev/null 2>&1 &
```
......@@ -101,7 +101,7 @@ nohup python /home/ec2-user/script.py >/home/ec2-user/script.py.log </dev/null 2
我们可以使用上面相同的命令来运行脚本并指定要使用的特定 GPU 设备,如下所示:
```
```py
CUDA_VISIBLE_DEVICES=0 nohup python /home/ec2-user/script.py >/home/ec2-user/script.py.log </dev/null 2>&1 &
```
......@@ -121,7 +121,7 @@ CUDA_VISIBLE_DEVICES=0 nohup python /home/ec2-user/script.py >/home/ec2-user/scr
此示例将列出脚本日志文件的最后几行,并在脚本中添加新行时更新输出。
```
```py
tail -f script.py.log
```
......@@ -129,7 +129,7 @@ tail -f script.py.log
另一种方法是使用 watch 命令。我发现亚马逊将保持这个终端开放:
```
```py
watch "tail script.py.log"
```
......@@ -146,13 +146,13 @@ watch "tail script.py.log"
您可以使用将每隔几秒更新一次的 top 命令来执行此操作。
```
```py
top -M
```
如果您知道其进程标识符(PID),还可以监视系统和进程。
```
```py
top -p PID -M
```
......@@ -164,7 +164,7 @@ top -p PID -M
您可以使用 _nvidia-smi_ 命令来关注 GPU 的使用情况。我喜欢使用 _watch_ 命令来保持终端打开并清除每个新结果的屏幕。
```
```py
watch "nvidia-smi"
```
......@@ -176,7 +176,7 @@ watch "nvidia-smi"
同样,我喜欢使用 watch 命令来保持终端打开。
```
```py
watch "ps -ef | grep python"
```
......@@ -188,7 +188,7 @@ watch "ps -ef | grep python"
下面的示例将在 vi 中打开您的脚本。
```
```py
vi ~/script.py
```
......@@ -206,7 +206,7 @@ vi ~/script.py
以下示例从您的工作站运行,并将所有 PNG 文件从您的主目录复制到您的工作站。
```
```py
scp -i ~/.ssh/aws-keypair.pem ec2-user@54.218.86.47:~/*.png .
```
......
......@@ -38,7 +38,7 @@ Keras 允许您列出在模型培训期间要监控的指标。
例如:
```
```py
model.compile(..., metrics=['mse'])
```
......@@ -61,7 +61,7 @@ model.compile(..., metrics=['mse'])
下面的示例演示了这个简单的人为回归问题的 4 个内置回归指标。
```
```py
from numpy import array
from keras.models import Sequential
from keras.layers import Dense
......@@ -85,7 +85,7 @@ pyplot.show()
运行该示例将在每个纪元的末尾打印度量标准值。
```
```py
...
Epoch 96/100
0s - loss: 1.0596e-04 - mean_squared_error: 1.0596e-04 - mean_absolute_error: 0.0088 - mean_absolute_percentage_error: 3.5611 - cosine_proximity: -1.0000e+00
......@@ -109,13 +109,13 @@ Epoch 100/100
我们还可以使用其扩展名称指定指标,如下所示:
```
```py
model.compile(loss='mse', optimizer='adam', metrics=['mean_squared_error', 'mean_absolute_error', 'mean_absolute_percentage_error', 'cosine_proximity'])
```
如果将函数名称导入脚本,我们也可以直接指定它们。
```
```py
from keras import metrics
model.compile(loss='mse', optimizer='adam', metrics=[metrics.mean_squared_error, metrics.mean_absolute_error, metrics.mean_absolute_percentage_error, metrics.cosine_proximity])
```
......@@ -124,7 +124,7 @@ model.compile(loss='mse', optimizer='adam', metrics=[metrics.mean_squared_error,
例如,您可以使用均方对数误差( _mean_squared_logarithmic_error_ , _MSLE_ 或 _msle_ )损失函数作为度量,如下所示:
```
```py
model.compile(loss='mse', optimizer='adam', metrics=['msle'])
```
......@@ -144,7 +144,7 @@ model.compile(loss='mse', optimizer='adam', metrics=['msle'])
下面是一个二进制分类问题的示例,其中显示了内置的精度指标。
```
```py
from numpy import array
from keras.models import Sequential
from keras.layers import Dense
......@@ -166,7 +166,7 @@ pyplot.show()
运行该示例报告每个训练时期结束时的准确性。
```
```py
...
Epoch 396/400
0s - loss: 0.5934 - acc: 0.9000
......@@ -196,7 +196,7 @@ Epoch 400/400
例如,下面是 Keras 中 [mean_squared_error 损失函数和度量的代码。](https://github.com/fchollet/keras/blob/master/keras/losses.py)
```
```py
def mean_squared_error(y_true, y_pred):
return K.mean(K.square(y_pred - y_true), axis=-1)
```
......@@ -207,7 +207,7 @@ K 是 Keras 使用的后端。
例如,我们可以编写自定义指标来计算 RMSE,如下所示:
```
```py
from keras import backend
def rmse(y_true, y_pred):
......@@ -218,7 +218,7 @@ def rmse(y_true, y_pred):
我们可以在我们的回归示例中对此进行如下测试。请注意,我们只是直接列出函数名称,而不是将其作为 Keras 要解析的字符串或别名提供。
```
```py
from numpy import array
from keras.models import Sequential
from keras.layers import Dense
......@@ -244,7 +244,7 @@ pyplot.show()
运行该示例在每个训练时期结束时报告自定义 RMSE 度量标准。
```
```py
...
Epoch 496/500
0s - loss: 1.2992e-06 - rmse: 9.7909e-04
......
......@@ -101,7 +101,7 @@ p3.2xlarge EC2 实例
* 12.打开终端并将目录更改为您下载密钥对的位置。
* 13.如果尚未执行此操作,请限制密钥对文件的访问权限。这需要作为对服务器的 SSH 访问的一部分。例如:
```
```py
cd Downloads
chmod 600 keras-aws-keypair.pem
```
......@@ -123,7 +123,7 @@ chmod 600 keras-aws-keypair.pem
* 2.将“公共 IP”(在“描述”中的屏幕底部)复制到剪贴板。在此示例中,我的 IP 地址是 54.186.97.77。 **请勿使用此 IP 地址**,您的 IP 地址会有所不同。
* 3.打开终端并将目录更改为您下载密钥对的位置。使用 SSH 登录您的服务器,例如:
```
```py
ssh -i keras-aws-keypair.pem ec2-user@54.186.97.77
```
......@@ -141,7 +141,7 @@ ssh -i keras-aws-keypair.pem ec2-user@54.186.97.77
您可以键入以下内容来激活此虚拟环境:
```
```py
source activate tensorflow_p36
```
......@@ -161,7 +161,7 @@ source activate tensorflow_p36
* 1.在终端注销您的实例,例如您可以输入:
```
```py
exit
```
......@@ -192,7 +192,7 @@ exit
您可以轻松地执行以下操作:
```
```py
nohup /path/to/script >/path/to/script.log 2>&1 < /dev/null &
```
......
......@@ -28,14 +28,14 @@ Keras 提供了在训练深度学习模型时注册回调的功能。
例如,您可以在训练模型后使用以下代码段列出历史记录对象中收集的指标:
```
```py
# list all data in history
print(history.history.keys())
```
例如,对于使用验证数据集训练分类问题的模型,这可能会产生以下列表:
```
```py
['acc', 'loss', 'val_acc', 'val_loss']
```
......@@ -60,7 +60,7 @@ print(history.history.keys())
1. 训练时期训练和验证数据集的准确性图。
2. 训练和验证数据集在训练时期的损失图。
```
```py
# Visualize training history
from keras.models import Sequential
from keras.layers import Dense
......
......@@ -51,7 +51,7 @@ Dropout 是 Srivastava 等人提出的神经网络模型的正则化技术。在
下面列出了完整的基线模型。
```
```py
# Baseline Model on the Sonar Dataset
import numpy
from pandas import read_csv
......@@ -104,7 +104,7 @@ print("Baseline: %.2f%% (%.2f%%)" % (results.mean()*100, results.std()*100))
运行该示例可生成 86%的估计分类准确度。
```
```py
Baseline: 86.04% (4.58%)
```
......@@ -120,7 +120,7 @@ Dropout 可以应用于称为可见层的输入神经元。
继续上面的基线示例,下面的代码使用输入丢失来运行相同的网络。
```
```py
# dropout in the input layer with weight constraint
def create_model():
# create model
......@@ -146,7 +146,7 @@ print("Visible: %.2f%% (%.2f%%)" % (results.mean()*100, results.std()*100))
运行该示例至少在单次测试运行中提供了分类精度的小幅下降。
```
```py
Visible: 83.52% (7.68%)
```
......@@ -156,7 +156,7 @@ Dropout 可以应用于网络模型体内的隐藏神经元。
在下面的示例中,Dropout 应用于两个隐藏层之间以及最后一个隐藏层和输出层之间。再次使用 20%的辍学率,以及对这些层的权重约束。
```
```py
# dropout in hidden layers with weight constraint
def create_model():
# create model
......@@ -185,7 +185,7 @@ print("Hidden: %.2f%% (%.2f%%)" % (results.mean()*100, results.std()*100))
可能需要额外的训练时期或者需要进一步调整学习速率。
```
```py
Hidden: 83.59% (7.31%)
```
......
......@@ -54,7 +54,7 @@ Keras 可以将训练数据的一部分分离为验证数据集,并在每个
下面的示例演示了如何在小二进制分类问题上使用自动验证数据集。本文中的所有实例均使用[皮马印第安人糖尿病数据集](http://archive.ics.uci.edu/ml/datasets/Pima+Indians+Diabetes)。您可以[从 UCI 机器学习库下载](http://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data),并使用文件名 **pima-indians-diabetes.csv** 将数据文件保存到当前工作目录中(更新:[从这里](https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.data.csv))。
```
```py
# MLP with automatic validation set
from keras.models import Sequential
from keras.layers import Dense
......@@ -79,7 +79,7 @@ model.fit(X, Y, validation_split=0.33, epochs=150, batch_size=10)
运行该示例,您可以看到每个时期的详细输出显示了训练数据集和验证数据集的损失和准确性。
```
```py
...
Epoch 145/150
514/514 [==============================] - 0s - loss: 0.5252 - acc: 0.7335 - val_loss: 0.5489 - val_acc: 0.7244
......@@ -103,7 +103,7 @@ Keras 还允许您手动指定在训练期间用于验证的数据集。
可以通过 **validation_data** 参数将验证数据集指定给 Keras 中的 **fit** ()函数。它需要输入和输出数据集的元组。
```
```py
# MLP with manual validation set
from keras.models import Sequential
from keras.layers import Dense
......@@ -132,7 +132,7 @@ model.fit(X_train, y_train, validation_data=(X_test,y_test), epochs=150, batch_s
与之前一样,运行该示例提供了详细的训练输出,其中包括模型在每个时期的训练和验证数据集上的丢失和准确性。
```
```py
...
Epoch 145/150
514/514 [==============================] - 0s - loss: 0.4847 - acc: 0.7704 - val_loss: 0.5668 - val_acc: 0.7323
......@@ -164,7 +164,7 @@ Epoch 150/150
为每个型号打印性能并将其存储。然后在运行结束时打印模型性能的平均值和标准偏差,以提供模型精度的稳健估计。
```
```py
# MLP for Pima Indians Dataset with 10-fold cross validation
from keras.models import Sequential
from keras.layers import Dense
......@@ -200,7 +200,7 @@ print("%.2f%% (+/- %.2f%%)" % (numpy.mean(cvscores), numpy.std(cvscores)))
运行该示例将花费不到一分钟,并将产生以下输出:
```
```py
acc: 77.92%
acc: 68.83%
acc: 72.73%
......
......@@ -50,7 +50,7 @@
例如,这里有一些用于使用列车测试分割来评估模型的伪代码:
```
```py
train, test = split(data)
model = fit(train.X, train.y)
predictions = model.predict(test.X)
......@@ -69,7 +69,7 @@ skill = compare(test.y, predictions)
例如,这里有一些使用 k 折交叉验证评估模型的伪代码:
```
```py
scores = list()
for i in k:
train, test = split_old(data, i)
......@@ -81,13 +81,13 @@ for i in k:
技能分数更有用,因为我们可以采用均值并报告模型的平均预期性能,这可能更接近实际模型的实际性能。例如:
```
```py
mean_skill = sum(scores) / count(scores)
```
我们还可以使用 mean_skill 计算标准偏差,以了解 mean_skill 周围的平均分数差异:
```
```py
standard_deviation = sqrt(1/count(scores) * sum( (score - mean_skill)^2 ))
```
......@@ -106,7 +106,7 @@ standard_deviation = sqrt(1/count(scores) * sum( (score - mean_skill)^2 ))
一种方法是每次模型拟合时使用相同的随机性。我们可以通过修复系统使用的随机数种子然后评估或拟合模型来做到这一点。例如:
```
```py
seed(1)
scores = list()
for i in k:
......@@ -132,7 +132,7 @@ for i in k:
例如:
```
```py
scores = list()
for i in repeats:
run_scores = list()
......@@ -151,7 +151,7 @@ for i in repeats:
因为重复通常&gt; = 30,所以我们可以很容易地计算出平均模型技能的标准误差,即模型技能得分的估计平均值与未知的实际平均模型技能的差异(例如,mean_skill 可能有多差)
```
```py
standard_error = standard_deviation / sqrt(count(scores))
```
......@@ -159,7 +159,7 @@ standard_error = standard_deviation / sqrt(count(scores))
例如,95%的间隔是平均技能周围的(1.96 *标准误差)。
```
```py
interval = standard_error * 1.96
lower_interval = mean_skill - interval
upper_interval = mean_skill + interval
......
......@@ -41,7 +41,7 @@
下面的伪代码草图总结了梯度下降算法:
```
```py
model = initialization(...)
n_epochs = ...
train_data = ...
......
......@@ -51,7 +51,7 @@ Keras 模型可以通过使用 **KerasClassifier** 或 **KerasRegressor** 类包
例如:
```
```py
def create_model():
...
return model
......@@ -63,7 +63,7 @@ model = KerasClassifier(build_fn=create_model)
例如:
```
```py
def create_model():
...
return model
......@@ -75,7 +75,7 @@ model = KerasClassifier(build_fn=create_model, epochs=10)
例如:
```
```py
def create_model(dropout_rate=0.0):
...
return model
......@@ -101,7 +101,7 @@ model = KerasClassifier(build_fn=create_model, dropout_rate=0.2)
下面是定义简单网格搜索的示例:
```
```py
param_grid = dict(epochs=[10,20,30])
grid = GridSearchCV(estimator=model, param_grid=param_grid, n_jobs=-1)
grid_result = grid.fit(X, Y)
......@@ -127,7 +127,7 @@ grid_result = grid.fit(X, Y)
如果您收到如下错误:
```
```py
INFO (theano.gof.compilelock): Waiting for existing lock by process '55614' (I am process '55613')
INFO (theano.gof.compilelock): To manually release the lock, delete ...
```
......@@ -146,7 +146,7 @@ INFO (theano.gof.compilelock): To manually release the lock, delete ...
完整的代码清单如下。
```
```py
# Use scikit-learn to grid search the batch size and epochs
import numpy
from sklearn.model_selection import GridSearchCV
......@@ -189,7 +189,7 @@ for mean, stdev, param in zip(means, stds, params):
运行此示例将生成以下输出。
```
```py
Best: 0.686198 using {'epochs': 100, 'batch_size': 20}
0.348958 (0.024774) with: {'epochs': 10, 'batch_size': 10}
0.348958 (0.024774) with: {'epochs': 50, 'batch_size': 10}
......@@ -225,7 +225,7 @@ Keras 提供一套不同的最先进的优化算法。
完整的代码清单如下。
```
```py
# Use scikit-learn to grid search the batch size and epochs
import numpy
from sklearn.model_selection import GridSearchCV
......@@ -267,7 +267,7 @@ for mean, stdev, param in zip(means, stds, params):
运行此示例将生成以下输出。
```
```py
Best: 0.704427 using {'optimizer': 'Adam'}
0.348958 (0.024774) with: {'optimizer': 'SGD'}
0.348958 (0.024774) with: {'optimizer': 'RMSprop'}
......@@ -294,7 +294,7 @@ Best: 0.704427 using {'optimizer': 'Adam'}
完整的代码清单如下。
```
```py
# Use scikit-learn to grid search the learning rate and momentum
import numpy
from sklearn.model_selection import GridSearchCV
......@@ -339,7 +339,7 @@ for mean, stdev, param in zip(means, stds, params):
运行此示例将生成以下输出。
```
```py
Best: 0.680990 using {'learn_rate': 0.01, 'momentum': 0.0}
0.348958 (0.024774) with: {'learn_rate': 0.001, 'momentum': 0.0}
0.348958 (0.024774) with: {'learn_rate': 0.001, 'momentum': 0.2}
......@@ -387,7 +387,7 @@ Best: 0.680990 using {'learn_rate': 0.01, 'momentum': 0.0}
完整的代码清单如下。
```
```py
# Use scikit-learn to grid search the weight initialization
import numpy
from sklearn.model_selection import GridSearchCV
......@@ -429,7 +429,7 @@ for mean, stdev, param in zip(means, stds, params):
运行此示例将生成以下输出。
```
```py
Best: 0.720052 using {'init_mode': 'uniform'}
0.720052 (0.024360) with: {'init_mode': 'uniform'}
0.348958 (0.024774) with: {'init_mode': 'lecun_uniform'}
......@@ -455,7 +455,7 @@ Best: 0.720052 using {'init_mode': 'uniform'}
完整的代码清单如下。
```
```py
# Use scikit-learn to grid search the activation function
import numpy
from sklearn.model_selection import GridSearchCV
......@@ -497,7 +497,7 @@ for mean, stdev, param in zip(means, stds, params):
运行此示例将生成以下输出。
```
```py
Best: 0.722656 using {'activation': 'linear'}
0.649740 (0.009744) with: {'activation': 'softmax'}
0.720052 (0.032106) with: {'activation': 'softplus'}
......@@ -525,7 +525,7 @@ Best: 0.722656 using {'activation': 'linear'}
完整的代码清单如下。
```
```py
# Use scikit-learn to grid search the dropout rate
import numpy
from sklearn.model_selection import GridSearchCV
......@@ -571,7 +571,7 @@ for mean, stdev, param in zip(means, stds, params):
运行此示例将生成以下输出。
```
```py
Best: 0.723958 using {'dropout_rate': 0.2, 'weight_constraint': 4}
0.696615 (0.031948) with: {'dropout_rate': 0.0, 'weight_constraint': 1}
0.696615 (0.031948) with: {'dropout_rate': 0.0, 'weight_constraint': 2}
......@@ -639,7 +639,7 @@ Best: 0.723958 using {'dropout_rate': 0.2, 'weight_constraint': 4}
完整的代码清单如下。
```
```py
# Use scikit-learn to grid search the number of neurons
import numpy
from sklearn.model_selection import GridSearchCV
......@@ -684,7 +684,7 @@ for mean, stdev, param in zip(means, stds, params):
运行此示例将生成以下输出。
```
```py
Best: 0.714844 using {'neurons': 5}
0.700521 (0.011201) with: {'neurons': 1}
0.714844 (0.011049) with: {'neurons': 5}
......
......@@ -49,7 +49,7 @@ Keras 深度学习库提供了一种加载 MNIST 数据集的便捷方法。
为了演示加载 MNIST 数据集是多么容易,我们将首先编写一个小脚本来下载和可视化训练数据集中的前 4 个图像。
```
```py
# Plot ad hoc mnist instances
from keras.datasets import mnist
import matplotlib.pyplot as plt
......@@ -82,7 +82,7 @@ MNIST 数据集中的示例
让我们从导入我们需要的类和函数开始。
```
```py
import numpy
from keras.datasets import mnist
from keras.models import Sequential
......@@ -93,7 +93,7 @@ from keras.utils import np_utils
将随机数生成器初始化为常量始终是一个好主意,以确保脚本的结果是可重现的。
```
```py
# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)
......@@ -101,7 +101,7 @@ numpy.random.seed(seed)
现在我们可以使用 Keras 辅助函数加载 MNIST 数据集。
```
```py
# load data
(X_train, y_train), (X_test, y_test) = mnist.load_data()
```
......@@ -110,7 +110,7 @@ numpy.random.seed(seed)
我们可以使用 NumPy 数组上的 [reshape()函数](http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.reshape.html)轻松地进行转换。我们还可以通过强制像素值的精度为 32 位来降低我们的内存需求,这是 Keras 使用的默认精度。
```
```py
# flatten 28*28 images to a 784 vector for each image
num_pixels = X_train.shape[1] * X_train.shape[2]
X_train = X_train.reshape(X_train.shape[0], num_pixels).astype('float32')
......@@ -119,7 +119,7 @@ X_test = X_test.reshape(X_test.shape[0], num_pixels).astype('float32')
像素值是 0 到 255 之间的灰度级。在使用神经网络模型时,执行输入值的某些缩放几乎总是一个好主意。因为比例是众所周知的并且表现良好,所以我们可以通过将每个值除以最大值 255 来非常快速地将像素值标准化到 0 和 1 的范围。
```
```py
# normalize inputs from 0-255 to 0-1
X_train = X_train / 255
X_test = X_test / 255
......@@ -129,7 +129,7 @@ X_test = X_test / 255
我们可以使用 Keras 中内置的 np_utils.to_categorical()辅助函数轻松完成此操作。
```
```py
# one hot encode outputs
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
......@@ -138,7 +138,7 @@ num_classes = y_test.shape[1]
我们现在准备创建我们简单的神经网络模型。我们将在函数中定义我们的模型。如果您想稍后扩展示例并尝试获得更好的分数,这将非常方便。
```
```py
# define baseline model
def baseline_model():
# create model
......@@ -158,7 +158,7 @@ def baseline_model():
最后,测试数据集用于评估模型并打印分类错误率。
```
```py
# build the model
model = baseline_model()
# Fit the model
......@@ -170,7 +170,7 @@ print("Baseline Error: %.2f%%" % (100-scores[1]*100))
在 CPU 上运行时运行该示例可能需要几分钟。您应该看到下面的输出。在极少数代码行中定义的这种非常简单的网络实现了 1.91%的可观错误率。
```
```py
Train on 60000 samples, validate on 10000 samples
Epoch 1/10
8s - loss: 0.2797 - acc: 0.9209 - val_loss: 0.1413 - val_acc: 0.9576
......@@ -205,7 +205,7 @@ Keras 确实为[创建卷积神经网络](http://keras.io/layers/convolutional/)
第一步是导入所需的类和函数。
```
```py
import numpy
from keras.datasets import mnist
from keras.models import Sequential
......@@ -221,7 +221,7 @@ K.set_image_dim_ordering('th')
同样,我们总是将随机数生成器初始化为恒定的种子值,以便重现结果。
```
```py
# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)
......@@ -231,7 +231,7 @@ numpy.random.seed(seed)
在 RGB 的情况下,对于红色,绿色和蓝色分量,第一维像素将是 3,并且对于每个彩色图像将具有 3 个图像输入。在 MNIST 中像素值是灰度级的情况下,像素尺寸设置为 1。
```
```py
# load data
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# reshape to be [samples][pixels][width][height]
......@@ -241,7 +241,7 @@ X_test = X_test.reshape(X_test.shape[0], 1, 28, 28).astype('float32')
和以前一样,最好将像素值标准化为 0 和 1 范围,并对输出变量进行热编码。
```
```py
# normalize inputs from 0-255 to 0-1
X_train = X_train / 255
X_test = X_test / 255
......@@ -264,7 +264,7 @@ num_classes = y_test.shape[1]
如前所述,使用对数损失和 ADAM 梯度下降算法训练模型。
```
```py
def baseline_model():
# create model
model = Sequential()
......@@ -281,7 +281,7 @@ def baseline_model():
我们使用多层感知器以与以前相同的方式评估模型。 CNN 适用于 10 个时期,批量为 200。
```
```py
# build the model
model = baseline_model()
# Fit the model
......@@ -295,7 +295,7 @@ print("CNN Error: %.2f%%" % (100-scores[1]*100))
时期可能需要大约 45 秒才能在 GPU 上运行(例如在 AWS 上)。您可以看到网络的错误率达到 1.03,这比我们上面的简单多层感知器模型要好。
```
```py
Train on 60000 samples, validate on 10000 samples
Epoch 1/10
60000/60000 [==============================] - 120s - loss: 0.2346 - acc: 0.9334 - val_loss: 0.0774 - val_acc: 0.9762
......@@ -326,7 +326,7 @@ CNN Error: 1.03%
我们导入类和函数,然后加载和准备数据与前一个 CNN 示例相同。
```
```py
# Larger CNN for the MNIST Dataset
import numpy
from keras.datasets import mnist
......@@ -368,7 +368,7 @@ num_classes = y_test.shape[1]
8. 完全连接的层有 50 个神经元和整流器激活。
9. 输出层。
```
```py
# define the larger model
def larger_model():
# create model
......@@ -389,7 +389,7 @@ def larger_model():
与前两个实验一样,该模型适用于 10 个时期,批量大小为 200。
```
```py
# build the model
model = larger_model()
# Fit the model
......@@ -403,7 +403,7 @@ print("Large CNN Error: %.2f%%" % (100-scores[1]*100))
该模型每个时期运行大约需要 100 秒。这个略大的模型实现了 0.89%的可观分类错误率。
```
```py
Train on 60000 samples, validate on 10000 samples
Epoch 1/10
60000/60000 [==============================] - 45s - loss: 0.3912 - acc: 0.8798 - val_loss: 0.0874 - val_acc: 0.9726
......
......@@ -53,7 +53,7 @@
* [用 Keras 逐步开发 Python 中的第一个神经网络](https://machinelearningmastery.com/tutorial-first-neural-network-python-keras/)
```
```py
# example of training a final classification model
from keras.models import Sequential
from keras.layers import Dense
......@@ -91,14 +91,14 @@ model.fit(X, y, epochs=200, verbose=0)
例如,我们在名为 _Xnew_ 的数组中有一个或多个数据实例。这可以传递给我们模型上的 _predict_classes()_ 函数,以便预测数组中每个实例的类值。
```
```py
Xnew = [[...], [...]]
ynew = model.predict_classes(Xnew)
```
让我们通过一个例子来具体化:
```
```py
# example making new class predictions for a classification problem
from keras.models import Sequential
from keras.layers import Dense
......@@ -128,7 +128,7 @@ for i in range(len(Xnew)):
运行该示例预测三个新数据实例的类,然后将数据和预测一起打印。
```
```py
X=[0.89337759 0.65864154], Predicted=[0]
X=[0.29097707 0.12978982], Predicted=[1]
X=[0.78082614 0.75391697], Predicted=[0]
......@@ -136,7 +136,7 @@ X=[0.78082614 0.75391697], Predicted=[0]
如果您只有一个新的数据实例,则可以将其作为包含在数组中的实例提供给 _predict_classes()_ 函数;例如:
```
```py
# example making new class prediction for a classification problem
from keras.models import Sequential
from keras.layers import Dense
......@@ -165,7 +165,7 @@ print("X=%s, Predicted=%s" % (Xnew[0], ynew[0]))
运行该示例将打印单个实例和预测类。
```
```py
X=[0.89337759 0.65864154], Predicted=[0]
```
......@@ -185,7 +185,7 @@ X=[0.89337759 0.65864154], Predicted=[0]
您可以通过调用 _predict_proba()_ 函数在 Keras 中进行这些类型的预测;例如:
```
```py
Xnew = [[...], [...]]
ynew = model.predict_proba(Xnew)
```
......@@ -196,7 +196,7 @@ ynew = model.predict_proba(Xnew)
以下示例对数据实例的 _Xnew_ 数组中的每个示例进行概率预测。
```
```py
# example making new probability predictions for a classification problem
from keras.models import Sequential
from keras.layers import Dense
......@@ -226,7 +226,7 @@ for i in range(len(Xnew)):
运行实例会进行概率预测,然后打印输入数据实例以及属于类 1 的每个实例的概率。
```
```py
X=[0.89337759 0.65864154], Predicted=[0.0087348]
X=[0.29097707 0.12978982], Predicted=[0.82020265]
X=[0.78082614 0.75391697], Predicted=[0.00693122]
......@@ -240,7 +240,7 @@ X=[0.78082614 0.75391697], Predicted=[0.00693122]
下面是用于回归的最终 Keras 模型的示例。
```
```py
# example of training a final regression model
from keras.models import Sequential
from keras.layers import Dense
......@@ -268,7 +268,7 @@ _predict()_ 函数采用一个或多个数据实例的数组。
下面的示例演示了如何对具有未知预期结果的多个数据实例进行回归预测。
```
```py
# example of making predictions for a regression problem
from keras.models import Sequential
from keras.layers import Dense
......@@ -300,7 +300,7 @@ for i in range(len(Xnew)):
运行该示例会进行多次预测,然后并排打印输入和预测以供审阅。
```
```py
X=[0.29466096 0.30317302], Predicted=[0.17097184]
X=[0.39445118 0.79390858], Predicted=[0.7475489]
X=[0.02884127 0.6208843 ], Predicted=[0.43370453]
......@@ -310,7 +310,7 @@ X=[0.02884127 0.6208843 ], Predicted=[0.43370453]
例如:
```
```py
# example of making predictions for a regression problem
from keras.models import Sequential
from keras.layers import Dense
......@@ -341,7 +341,7 @@ print("X=%s, Predicted=%s" % (Xnew[0], ynew[0]))
运行该示例进行单个预测并打印数据实例和预测以供审阅。
```
```py
X=[0.29466096 0.30317302], Predicted=[0.17333156]
```
......
......@@ -36,7 +36,7 @@ Keras 提供 [ImageDataGenerator](http://keras.io/preprocessing/image/) 类,
可以如下创建增强图像生成器:
```
```py
datagen = ImageDataGenerator()
```
......@@ -44,19 +44,19 @@ API 不是在内存中对整个图像数据集执行操作,而是通过深度
创建并配置 **ImageDataGenerator** 后,必须将其放在数据上。这将计算实际执行图像数据转换所需的任何统计信息。您可以通过调用数据生成器上的 **fit()**函数并将其传递给训练数据集来完成此操作。
```
```py
datagen.fit(train)
```
数据生成器本身实际上是一个迭代器,在请求时返回批量的图像样本。我们可以通过调用 **flow()**函数来配置批量大小并准备数据生成器并获取批量图像。
```
```py
X_batch, y_batch = datagen.flow(train, train, batch_size=32)
```
最后我们可以使用数据生成器。我们必须调用 **fit_generator()**函数并传入数据生成器和所需的时间长度以及总数,而不是在我们的模型上调用 **fit()**函数。要训​​练的时代数。
```
```py
fit_generator(datagen, samples_per_epoch=len(train), epochs=100)
```
......@@ -68,7 +68,7 @@ fit_generator(datagen, samples_per_epoch=len(train), epochs=100)
我们将在这些示例中使用 MNIST 手写数字识别任务。首先,让我们看一下训练数据集中的前 9 个图像。
```
```py
# Plot images
from keras.datasets import mnist
from matplotlib import pyplot
......@@ -94,7 +94,7 @@ pyplot.show()
您可以通过在 ImageDataGenerator 类上设置 featurewise_center 和 featurewise_std_normalization 参数来执行功能标准化。实际上,默认情况下这些设置为 True,并且创建没有参数的 ImageDataGenerator 实例将具有相同的效果。
```
```py
# Standardize images across the dataset, mean=0, stdev=1
from keras.datasets import mnist
from keras.preprocessing.image import ImageDataGenerator
......@@ -140,7 +140,7 @@ for X_batch, y_batch in datagen.flow(X_train, y_train, batch_size=9):
您可以通过将 zca_whitening 参数设置为 True 来执行 ZCA 白化转换。
```
```py
# ZCA whitening
from keras.datasets import mnist
from keras.preprocessing.image import ImageDataGenerator
......@@ -184,7 +184,7 @@ ZCA 美白 MNIST 图像
下面的示例通过设置 rotation_range 参数创建最多 90 度的 MNIST 数字的随机旋转。
```
```py
# Random Rotations
from keras.datasets import mnist
from keras.preprocessing.image import ImageDataGenerator
......@@ -226,7 +226,7 @@ MNIST 图像的随机旋转
您可以通过人工创建训练数据的移位版本来训练您的深度学习网络以期望并且当前处理偏离中心的对象。 Keras 通过 width_shift_range 和 height_shift_range 参数支持训练数据的单独水平和垂直随机移位。
```
```py
# Random Shifts
from keras.datasets import mnist
from keras.preprocessing.image import ImageDataGenerator
......@@ -269,7 +269,7 @@ for X_batch, y_batch in datagen.flow(X_train, y_train, batch_size=9):
Keras 支持使用 vertical_flip 和 horizo​​ntal_flip 参数沿垂直轴和水平轴进行随机翻转。
```
```py
# Random Flips
from keras.datasets import mnist
from keras.preprocessing.image import ImageDataGenerator
......@@ -315,7 +315,7 @@ Keras 允许您保存训练期间生成的图像。可以在训练之前将目
下面的示例演示了这一点,并将 9 个图像写入“images”子目录,前缀为“aug”,文件类型为 PNG。
```
```py
# Save augmented images to file
from keras.datasets import mnist
from keras.preprocessing.image import ImageDataGenerator
......
......@@ -45,7 +45,7 @@ Keras 由[FrançoisChollet](https://www.linkedin.com/in/fchollet)开发和维护
使用 [PyPI](https://pypi.python.org/pypi) 可以轻松安装 Keras,如下所示:
```
```py
sudo pip install keras
```
......@@ -53,19 +53,19 @@ sudo pip install keras
您可以使用以下代码段在命令行上检查您的 Keras 版本:
```
```py
python -c "import keras; print keras.__version__"
```
运行上面的脚本你会看到:
```
```py
1.1.0
```
您可以使用相同的方法升级 Keras 的安装:
```
```py
sudo pip install --upgrade keras
```
......@@ -75,13 +75,13 @@ sudo pip install --upgrade keras
最简单的方法是在主目录中添加或编辑 Keras 配置文件:
```
```py
~/.keras/keras.json
```
其格式如下:
```
```py
{
"image_dim_ordering": "tf",
"epsilon": 1e-07,
......@@ -94,26 +94,26 @@ sudo pip install --upgrade keras
您可以在命令行上使用以下代码段确认 Keras 使用的后端:
```
```py
python -c "from keras import backend; print backend._BACKEND"
```
使用默认配置运行此选项,您将看到:
```
```py
Using TensorFlow backend.
tensorflow
```
您还可以通过指定 KERAS_BACKEND 环境变量在命令行上指定 Keras 使用的后端,如下所示:
```
```py
KERAS_BACKEND=theano python -c "from keras import backend; print(backend._BACKEND)"
```
运行此示例打印:
```
```py
Using Theano backend.
theano
```
......
......@@ -47,7 +47,7 @@ TensorFlow 适用于 Python 2.7 和 Python 3.3+。您可以按照 TensorFlow 网
第一个示例是 [TensorFlow 网站](https://github.com/tensorflow/tensorflow)上的示例的修改版本。它显示了如何使用会话创建会话,定义常量和使用这些常量执行计算。
```
```py
import tensorflow as tf
sess = tf.Session()
a = tf.constant(10)
......@@ -57,7 +57,7 @@ print(sess.run(a+b))
运行此示例显示:
```
```py
42
```
......@@ -69,7 +69,7 @@ print(sess.run(a+b))
我们对 TensorFlow 有一定的了解,它将计算的定义和声明与会话中的执行和运行调用分开。
```
```py
import tensorflow as tf
import numpy as np
......@@ -107,7 +107,7 @@ for step in xrange(201):
运行此示例将输出以下输出:
```
```py
(0, array([ 0.2629351], dtype=float32), array([ 0.28697217], dtype=float32))
(20, array([ 0.13929555], dtype=float32), array([ 0.27992988], dtype=float32))
(40, array([ 0.11148042], dtype=float32), array([ 0.2941364], dtype=float32))
......@@ -129,13 +129,13 @@ for step in xrange(201):
首先,您需要找出系统上 TensorFlow 的安装位置。例如,您可以使用以下 Python 脚本:
```
```py
python -c 'import os; import inspect; import tensorflow; print(os.path.dirname(inspect.getfile(tensorflow)))'
```
例如,这可能是:
```
```py
/usr/lib/python2.7/site-packages/tensorflow
```
......
......@@ -33,7 +33,7 @@ Theano 假设使用 [SciPy](https://www.scipy.org/) 工作的 Python 2 或 Pytho
使用 Python 和 SciPy 环境,安装 Theano 相对简单。来自 PyPI 使用 pip,例如:
```
```py
pip install Theano
```
......@@ -41,7 +41,7 @@ pip install Theano
可能会发布新版本,您需要更新以获取任何错误修复和效率改进。您可以使用 pip 升级 Theano,如下所示:
```
```py
sudo pip install --upgrade --no-deps theano
```
......@@ -49,7 +49,7 @@ sudo pip install --upgrade --no-deps theano
对于一些使用前沿 API 更改的包装器库,可能需要这样做。您可以直接从 Github 结帐安装 Theano,如下所示:
```
```py
pip install --upgrade --no-deps git+git://github.com/Theano/Theano.git
```
......@@ -69,7 +69,7 @@ pip install --upgrade --no-deps git+git://github.com/Theano/Theano.git
最后,我们使用我们的编译表达式,插入一些实际值并使用高效的编译 Theano 代码执行计算。
```
```py
import theano
from theano import tensor
# declare two symbolic floating-point scalars
......
......@@ -42,7 +42,7 @@ Keras 中的功能 API 是创建模型的另一种方式,它提供了更多的
例如,可以定义图层并将其作为数组传递给 Sequential:
```
```py
from keras.models import Sequential
from keras.layers import Dense
model = Sequential([Dense(2, input_dim=1), Dense(1)])
......@@ -50,7 +50,7 @@ model = Sequential([Dense(2, input_dim=1), Dense(1)])
图层也可以分段添加:
```
```py
from keras.models import Sequential
from keras.layers import Dense
model = Sequential()
......@@ -80,7 +80,7 @@ Keras 功能 API 为定义模型提供了更灵活的方式。
当输入数据是一维的时,例如对于多层感知器,形状必须明确留出空间,以便在训练网络时分割数据时使用的小批量大小的形状。因此,当输入是一维(2,)时,形状元组总是用挂起的最后一个维度定义,例如:
```
```py
from keras.layers import Input
visible = Input(shape=(2,))
```
......@@ -93,7 +93,7 @@ visible = Input(shape=(2,))
让我们用一个简短的例子来说明这一点。我们可以像上面那样创建输入层,然后创建一个隐藏层作为 Dense,它只接收来自输入层的输入。
```
```py
from keras.layers import Input
from keras.layers import Dense
visible = Input(shape=(2,))
......@@ -112,7 +112,7 @@ hidden = Dense(2)(visible)
Keras 提供了一个 Model 类,您可以使用它从创建的图层创建模型。它要求您只指定输入和输出图层。例如:
```
```py
from keras.models import Model
from keras.layers import Input
from keras.layers import Dense
......@@ -141,7 +141,7 @@ model = Model(inputs=visible, outputs=hidden)
该模型具有 10 个输入,3 个具有 10,20 和 10 个神经元的隐藏层,以及具有 1 个输出的输出层。在每个隐藏层中使用校正的线性激活函数,并且在输出层中使用 S 形激活函数,用于二进制分类。
```
```py
# Multilayer Perceptron
from keras.utils import plot_model
from keras.models import Model
......@@ -161,7 +161,7 @@ plot_model(model, to_file='multilayer_perceptron_graph.png')
运行该示例将打印网络结构。
```
```py
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
......@@ -193,7 +193,7 @@ _________________________________________________________________
该模型接收黑白 64×64 图像作为输入,然后具有两个卷积和池化层的序列作为特征提取器,接着是完全连接的层来解释特征,输出层具有用于两类预测的 S 形激活。
```
```py
# Convolutional Neural Network
from keras.utils import plot_model
from keras.models import Model
......@@ -219,7 +219,7 @@ plot_model(model, to_file='convolutional_neural_network.png')
运行该示例总结了模型层。
```
```py
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
......@@ -257,7 +257,7 @@ _________________________________________________________________
该模型需要 100 个时间步长作为输入。该模型具有单个 LSTM 隐藏层以从序列中提取特征,随后是完全连接的层以解释 LSTM 输出,接着是用于进行二元预测的输出层。
```
```py
# Recurrent Neural Network
from keras.utils import plot_model
from keras.models import Model
......@@ -277,7 +277,7 @@ plot_model(model, to_file='recurrent_neural_network.png')
运行该示例总结了模型层。
```
```py
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
......@@ -315,7 +315,7 @@ _________________________________________________________________
该模型采用尺寸为 64×64 像素的黑白图像。有两个共享此输入的 CNN 特征提取子模型;第一个内核大小为 4,第二个内核大小为 8.这些特征提取子模型的输出被平展为向量并连接成一个长向量,并传递到完全连接的层以进行解释,然后最终输出层生成二进制分类。
```
```py
# Shared Input Layer
from keras.utils import plot_model
from keras.models import Model
......@@ -350,7 +350,7 @@ plot_model(model, to_file='shared_input_layer.png')
运行该示例总结了模型层。
```
```py
____________________________________________________________________________________________________
Layer (type) Output Shape Param # Connected to
====================================================================================================
......@@ -393,7 +393,7 @@ ________________________________________________________________________________
模型的输入是 1 个特征的 100 个时间步长。具有 10 个存储器单元的 LSTM 层解释该序列。第一个解释模型是浅单个完全连接层,第二个是深 3 层模型。两个解释模型的输出被连接成一个长向量,该向量被传递到用于进行二进制预测的输出层。
```
```py
# Shared Feature Extraction Layer
from keras.utils import plot_model
from keras.models import Model
......@@ -424,7 +424,7 @@ plot_model(model, to_file='shared_feature_extractor.png')
运行该示例总结了模型层。
```
```py
____________________________________________________________________________________________________
Layer (type) Output Shape Param # Connected to
====================================================================================================
......@@ -469,13 +469,13 @@ ________________________________________________________________________________
请注意,在创建 Model()实例时,我们将两个输入层定义为数组。特别:
```
```py
model = Model(inputs=[visible1, visible2], outputs=output)
```
下面列出了完整的示例。
```
```py
# Multiple Inputs
from keras.utils import plot_model
from keras.models import Model
......@@ -514,7 +514,7 @@ plot_model(model, to_file='multiple_inputs.png')
运行该示例总结了模型层。
```
```py
____________________________________________________________________________________________________
Layer (type) Output Shape Param # Connected to
====================================================================================================
......@@ -569,7 +569,7 @@ ________________________________________________________________________________
LSTM 层解释输入序列并返回每个时间步的隐藏状态。第一个输出模型创建堆叠 LSTM,解释特征并进行二元预测。第二输出模型使用相同的输出层对每个输入时间步进行实值预测。
```
```py
# Multiple Outputs
from keras.utils import plot_model
from keras.models import Model
......@@ -597,7 +597,7 @@ plot_model(model, to_file='multiple_outputs.png')
运行该示例总结了模型层。
```
```py
____________________________________________________________________________________________________
Layer (type) Output Shape Param # Connected to
====================================================================================================
......@@ -644,7 +644,7 @@ ________________________________________________________________________________
例如,给定:
```
```py
...
dense1 = Dense(32)(input)
...
......@@ -662,7 +662,7 @@ dense1 = Dense(32)(input)
我们可以用两行来做同样的事情:
```
```py
# create layer
dense1 = Dense(32)
# connect layer to previous layer
......@@ -671,7 +671,7 @@ dense1(input)
我想我们也可以明确地调用对象上的 ___call __()_ 函数,虽然我从未尝试过:
```
```py
# create layer
dense1 = Dense(32)
# connect layer to previous layer
......
......@@ -41,7 +41,7 @@ Keras 深度学习库的多类分类教程
这包括我们需要 Keras 的功能,还包括 [pandas](http://pandas.pydata.org/) 的数据加载以及 [scikit-learn](http://scikit-learn.org/) 的数据准备和模型评估。
```
```py
import numpy
import pandas
from keras.models import Sequential
......@@ -60,7 +60,7 @@ from sklearn.pipeline import Pipeline
这对于确保我们可以再次精确地实现从该模型获得的结果非常重要。它确保可以再现训练神经网络模型的随机过程。
```
```py
# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)
......@@ -70,7 +70,7 @@ numpy.random.seed(seed)
可以直接加载数据集。因为输出变量包含字符串,所以最简单的方法是使用 pandas 加载数据。然后我们可以将属性(列)拆分为输入变量(X)和输出变量(Y)。
```
```py
# load dataset
dataframe = pandas.read_csv("iris.csv", header=None)
dataset = dataframe.values
......@@ -88,7 +88,7 @@ Y = dataset[:,4]
例如,在这个问题中,三个类值是 Iris-setosa,Iris-versicolor 和 Iris-virginica。如果我们有观察结果:
```
```py
Iris-setosa
Iris-versicolor
Iris-virginica
......@@ -96,7 +96,7 @@ Iris-virginica
我们可以将其转换为每个数据实例的单热编码二进制矩阵,如下所示:
```
```py
Iris-setosa, Iris-versicolor, Iris-virginica
1, 0, 0
0, 1, 0
......@@ -105,7 +105,7 @@ Iris-setosa, Iris-versicolor, Iris-virginica
我们可以通过首先使用 scikit-learn 类 LabelEncoder 将字符串一致地编码为整数来完成此操作。然后使用 Keras 函数 to_categorical()将整数向量转换为一个热编码。
```
```py
# encode class values as integers
encoder = LabelEncoder()
encoder.fit(Y)
......@@ -126,7 +126,7 @@ Keras 中有一个 KerasClassifier 类,可以用作 scikit-learn 中的 Estima
这个简单的单层神经网络的网络拓扑可以概括为:
```
```py
4 inputs -> [8 hidden nodes] -> 3 outputs
```
......@@ -134,7 +134,7 @@ Keras 中有一个 KerasClassifier 类,可以用作 scikit-learn 中的 Estima
最后,网络使用具有对数损失函数的高效 Adam 梯度下降优化算法,在 Keras 中称为“ _categorical_crossentropy_ ”。
```
```py
# define baseline model
def baseline_model():
# create model
......@@ -150,7 +150,7 @@ def baseline_model():
我们还可以在构造 KerasClassifier 类中传递参数,该类将传递给内部用于训练神经网络的 fit()函数。在这里,我们将时期数传递为 200,批量大小为 5,以便在训练模型时使用。通过将 verbose 设置为 0,在训练时也会关闭调试。
```
```py
estimator = KerasClassifier(build_fn=baseline_model, epochs=200, batch_size=5, verbose=0)
```
......@@ -162,7 +162,7 @@ scikit-learn 具有使用一套技术评估模型的出色能力。评估机器
首先,我们可以定义模型评估程序。在这里,我们将折叠数设置为 10(一个很好的默认值)并在分区之前对数据进行洗牌。
```
```py
kfold = KFold(n_splits=10, shuffle=True, random_state=seed)
```
......@@ -170,14 +170,14 @@ kfold = KFold(n_splits=10, shuffle=True, random_state=seed)
评估模型仅需要大约 10 秒钟,并返回一个对象,该对象描述了对数据集的每个分割的 10 个构建模型的评估。
```
```py
results = cross_val_score(estimator, X, dummy_y, cv=kfold)
print("Baseline: %.2f%% (%.2f%%)" % (results.mean()*100, results.std()*100))
```
结果总结为数据集上模型精度的均值和标准差。这是对看不见的数据的模型性能的合理估计。对于这个问题,它也属于已知的最佳结果范围。
```
```py
Accuracy: 97.33% (4.42%)
```
......
......@@ -41,7 +41,7 @@ Keras 可以自动下载 CIFAR-10 等标准数据集,并使用 cifar10.load_da
数据集存储为酸洗训练和测试集,准备在 Keras 中使用。每个图像表示为三维矩阵,具有红色,绿色,蓝色,宽度和高度的尺寸。我们可以使用 [matplotlib](http://matplotlib.org/) 直接绘制图像。
```
```py
# Plot ad hoc CIFAR10 instances
from keras.datasets import cifar10
from matplotlib import pyplot
......@@ -68,7 +68,7 @@ CIFAR-10 图像的小样本
我们可以通过定义本例中需要的所有类和函数来快速入门。
```
```py
# Simple CNN model for CIFAR-10
import numpy
from keras.datasets import cifar10
......@@ -87,7 +87,7 @@ K.set_image_dim_ordering('th')
好的做法是,我们接下来用常数初始化随机数种子,以确保结果可重复。
```
```py
# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)
......@@ -95,7 +95,7 @@ numpy.random.seed(seed)
接下来,我们可以加载 CIFAR-10 数据集。
```
```py
# load data
(X_train, y_train), (X_test, y_test) = cifar10.load_data()
```
......@@ -106,7 +106,7 @@ numpy.random.seed(seed)
注意,数据作为整数加载,因此我们必须将其转换为浮点值才能执行除法。
```
```py
# normalize inputs from 0-255 to 0.0-1.0
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
......@@ -118,7 +118,7 @@ X_test = X_test / 255.0
我们可以使用一个热编码将它们转换为二进制矩阵,以便最好地对分类问题进行建模。我们知道这个问题有 10 个类,所以我们可以期望二进制矩阵的宽度为 10。
```
```py
# one hot encode outputs
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
......@@ -142,7 +142,7 @@ num_classes = y_test.shape[1]
对数损失函数与随机梯度下降优化算法一起使用,该算法配置有大动量和重量衰减开始,学习率为 0.01。
```
```py
# Create the model
model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=(3, 32, 32), padding='same', activation='relu', kernel_constraint=maxnorm(3)))
......@@ -168,7 +168,7 @@ print(model.summary())
一旦模型适合,我们在测试数据集上对其进行评估并打印出分类准确度。
```
```py
# Fit the model
model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=epochs, batch_size=32)
# Final evaluation of the model
......@@ -178,7 +178,7 @@ print("Accuracy: %.2f%%" % (scores[1]*100))
运行此示例提供以下结果。首先总结网络结构,确认我们的设计是正确实施的。
```
```py
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
......@@ -206,7 +206,7 @@ _________________________________________________________________
在训练和测试数据集的每个时期打印分类准确度和损失。该模型在测试装置上进行评估,达到 70.85%的准确度,这并不是很好。
```
```py
...
Epoch 20/25
50000/50000 [==============================] - 143s - loss: 0.2858 - acc: 0.9011 - val_loss: 1.0091 - val_acc: 0.7063
......@@ -257,7 +257,7 @@ Accuracy: 70.85%
我们可以很容易地在 Keras 中定义这种网络拓扑,如下所示:
```
```py
# Create the model
model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=(3, 32, 32), activation='relu', padding='same'))
......@@ -290,7 +290,7 @@ print(model.summary())
我们可以使用与上述相同的程序和相同数量的时期来拟合和评估该模型,但是通过一些小的实验发现更大的批量大小为 64。
```
```py
numpy.random.seed(seed)
model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=epochs, batch_size=64)
# Final evaluation of the model
......@@ -300,7 +300,7 @@ print("Accuracy: %.2f%%" % (scores[1]*100))
运行此示例将在每个时期打印训练和测试数据集的分类准确性和损失。最终模型的分类精度估计值为 80.18%,比我们的简单模型好近 10 个点。
```
```py
# 50000/50000 [==============================] - 34s - loss: 0.4993 - acc: 0.8230 - val_loss: 0.5994 - val_acc: 0.7932
# Epoch 20/25
# 50000/50000 [==============================] - 34s - loss: 0.4877 - acc: 0.8271 - val_loss: 0.5986 - val_acc: 0.7932
......
......@@ -47,7 +47,7 @@ keras.datasets.imdb.load_data()允许您以可用于神经网络和深度学
让我们加载数据集并计算它的一些属性。我们将首先加载一些库并将整个 IMDB 数据集作为训练数据集加载。
```
```py
import numpy
from keras.datasets import imdb
from matplotlib import pyplot
......@@ -59,7 +59,7 @@ y = numpy.concatenate((y_train, y_test), axis=0)
接下来,我们可以显示训练数据集的形状。
```
```py
# summarize size
print("Training data: ")
print(X.shape)
......@@ -68,7 +68,7 @@ print(y.shape)
运行此代码段,我们可以看到有 50,000 条记录。
```
```py
Training data:
(50000,)
(50000,)
......@@ -76,7 +76,7 @@ Training data:
我们还可以打印唯一的类值。
```
```py
# Summarize number of classes
print("Classes: ")
print(numpy.unique(y))
......@@ -84,14 +84,14 @@ print(numpy.unique(y))
我们可以看到,这是一个二元分类问题,在评论中有好的和坏的情绪。
```
```py
Classes:
[0 1]
```
接下来,我们可以了解数据集中唯一单词的总数。
```
```py
# Summarize number of words
print("Number of words: ")
print(len(numpy.unique(numpy.hstack(X))))
......@@ -99,14 +99,14 @@ print(len(numpy.unique(numpy.hstack(X))))
有趣的是,我们可以看到整个数据集中只有不到 100,000 个单词。
```
```py
Number of words:
88585
```
最后,我们可以了解平均审核长度。
```
```py
# Summarize review length
print("Review length: ")
result = [len(x) for x in X]
......@@ -118,7 +118,7 @@ pyplot.show()
我们可以看到,平均评论不到 300 字,标准差超过 200 字。
```
```py
Review length:
Mean 234.76 words (172.911495)
```
......@@ -147,20 +147,20 @@ Keras 提供了一种方便的方法,可以将单词的正整数表示转换
我们将加载 IMDB 数据集,如下所示:
```
```py
imdb.load_data(nb_words=5000)
```
然后,我们将使用 Keras 实用程序使用 sequence.pad_sequences()函数将数据集截断或填充到每个观察的长度 500。
```
```py
X_train = sequence.pad_sequences(X_train, maxlen=500)
X_test = sequence.pad_sequences(X_test, maxlen=500)
```
最后,稍后,我们模型的第一层将是使用 Embedding 类创建的单词嵌入层,如下所示:
```
```py
Embedding(5000, 32, input_length=500)
```
......@@ -176,7 +176,7 @@ Embedding(5000, 32, input_length=500)
让我们首先导入此模型所需的类和函数,并将随机数生成器初始化为常量值,以确保我们可以轻松地重现结果。
```
```py
# MLP for the IMDB problem
import numpy
from keras.datasets import imdb
......@@ -194,7 +194,7 @@ numpy.random.seed(seed)
我们还将使用 50%/ 50%的数据集拆分进行培训和测试。这是一种很好的标准拆分方法。
```
```py
# load the dataset but only keep the top n words, zero the rest
top_words = 5000
(X_train, y_train), (X_test, y_test) = imdb.load_data(num_words=top_words)
......@@ -202,7 +202,7 @@ top_words = 5000
我们将以 500 字的方式绑定评论,截断更长的评论和零填充更短的评论。
```
```py
max_words = 500
X_train = sequence.pad_sequences(X_train, maxlen=max_words)
X_test = sequence.pad_sequences(X_test, maxlen=max_words)
......@@ -214,7 +214,7 @@ X_test = sequence.pad_sequences(X_test, maxlen=max_words)
该模型使用对数损失,并使用有效的 ADAM 优化程序进行优化。
```
```py
# create the model
model = Sequential()
model.add(Embedding(top_words, 32, input_length=max_words))
......@@ -229,7 +229,7 @@ print(model.summary())
有很多数据,所以我们将使用 128 的批量大小。在训练模型后,我们评估其在测试数据集上的准确性。
```
```py
# Fit the model
model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=2, batch_size=128, verbose=2)
# Final evaluation of the model
......@@ -239,7 +239,7 @@ print("Accuracy: %.2f%%" % (scores[1]*100))
运行此示例适合模型并总结估计的性能。我们可以看到,这个非常简单的模型获得了近 86.94%的分数,这是在原始论文的附近,只需很少的努力。
```
```py
Train on 25000 samples, validate on 25000 samples
Epoch 1/2
39s - loss: 0.5160 - acc: 0.7040 - val_loss: 0.2982 - val_acc: 0.8716
......@@ -260,7 +260,7 @@ Keras 分别支持 Conv1D 和 MaxPooling1D 类的一维卷积和池化。
再次,让我们导入此示例所需的类和函数,并将随机数生成器初始化为常量值,以便我们可以轻松地重现结果。
```
```py
# CNN for the IMDB problem
import numpy
from keras.datasets import imdb
......@@ -278,7 +278,7 @@ numpy.random.seed(seed)
我们也可以像以前一样加载和准备我们的 IMDB 数据集。
```
```py
# load the dataset but only keep the top n words, zero the rest
top_words = 5000
(X_train, y_train), (X_test, y_test) = imdb.load_data(num_words=top_words)
......@@ -292,7 +292,7 @@ X_test = sequence.pad_sequences(X_test, maxlen=max_words)
卷积层之后是 1D max pooling layer,其长度和步幅为 2,使卷积层的特征映射的大小减半。网络的其余部分与上面的神经网络相同。
```
```py
# create the model
model = Sequential()
model.add(Embedding(top_words, 32, input_length=max_words))
......@@ -307,7 +307,7 @@ print(model.summary())
我们也像以前一样适应网络。
```
```py
# Fit the model
model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=2, batch_size=128, verbose=2)
# Final evaluation of the model
......@@ -319,7 +319,7 @@ print("Accuracy: %.2f%%" % (scores[1]*100))
运行该示例对上述神经网络模型提供了一个小但令人欢迎的改进,准确率接近 87.79%。
```
```py
Train on 25000 samples, validate on 25000 samples
Epoch 1/2
38s - loss: 0.4451 - acc: 0.7640 - val_loss: 0.3107 - val_acc: 0.8660
......
......@@ -43,7 +43,7 @@ Keras 是一个深度学习库,包含高效的数字库 Theano 和 TensorFlow
让我们从包含本教程所需的所有函数和对象开始。
```
```py
import numpy
import pandas
from keras.models import Sequential
......@@ -59,7 +59,7 @@ from sklearn.pipeline import Pipeline
事实上,数据集在 UCI 机器学习库中不是 CSV 格式,而是用空格分隔属性。我们可以使用 pandas 库轻松加载它。然后我们可以分割输入(X)和输出(Y)属性,以便使用 Keras 和 scikit-learn 更容易建模。
```
```py
# load dataset
dataframe = pandas.read_csv("housing.csv", delim_whitespace=True, header=None)
dataset = dataframe.values
......@@ -76,7 +76,7 @@ Keras 包装器需要一个函数作为参数。我们必须定义的这个函
使用有效的 ADAM 优化算法并且优化均方误差损失函数。这将与我们用于评估模型性能的指标相同。这是一个理想的指标,因为通过取平方根给出了一个误差值,我们可以在问题的背景下直接理解(数千美元)。
```
```py
# define base model
def baseline_model():
# create model
......@@ -92,7 +92,7 @@ def baseline_model():
我们还使用常量随机种子初始化随机数生成器,我们将为本教程中评估的每个模型重复该过程。这是为了确保我们一致地比较模型。
```
```py
# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)
......@@ -102,7 +102,7 @@ estimator = KerasRegressor(build_fn=baseline_model, epochs=100, batch_size=5, ve
最后一步是评估此基线模型。我们将使用 10 倍交叉验证来评估模型。
```
```py
kfold = KFold(n_splits=10, random_state=seed)
results = cross_val_score(estimator, X, Y, cv=kfold)
print("Results: %.2f (%.2f) MSE" % (results.mean(), results.std()))
......@@ -110,7 +110,7 @@ print("Results: %.2f (%.2f) MSE" % (results.mean(), results.std()))
运行此代码可以估算出模型在看不见的数据问题上的表现。结果报告了均方误差,包括交叉验证评估的所有 10 倍的平均值和标准偏差(平均方差)。
```
```py
Baseline: 31.64 (26.82) MSE
```
......@@ -126,7 +126,7 @@ Baseline: 31.64 (26.82) MSE
下面的代码创建了一个 scikit-learn Pipeline,它首先标准化数据集,然后创建和评估基线神经网络模型。
```
```py
# evaluate model with standardized dataset
numpy.random.seed(seed)
estimators = []
......@@ -140,7 +140,7 @@ print("Standardized: %.2f (%.2f) MSE" % (results.mean(), results.std()))
运行该示例可提供比基线模型更高的性能,而无需标准化数据,从而丢弃错误。
```
```py
Standardized: 29.54 (27.87) MSE
```
......@@ -160,7 +160,7 @@ Standardized: 29.54 (27.87) MSE
在本节中,我们将评估向模型添加一个隐藏层的效果。这就像定义一个新函数一样简单,这个函数将创建这个更深层次的模型,从上面的基线模型中复制出来。然后我们可以在第一个隐藏层之后插入一个新行。在这种情况下,神经元的数量约为一半。
```
```py
# define the model
def larger_model():
# create model
......@@ -175,13 +175,13 @@ def larger_model():
我们的网络拓扑现在看起来像:
```
```py
13 inputs -> [13 -> 6] -> 1 output
```
我们可以采用与上述相同的方式评估此网络拓扑,同时还使用上面显示的数据集的标准化来提高性能。
```
```py
numpy.random.seed(seed)
estimators = []
estimators.append(('standardize', StandardScaler()))
......@@ -194,7 +194,7 @@ print("Larger: %.2f (%.2f) MSE" % (results.mean(), results.std()))
运行此模型确实表明性能从 28 降至 24,000 平方美元进一步改善。
```
```py
Larger: 22.83 (25.33) MSE
```
......@@ -206,7 +206,7 @@ Larger: 22.83 (25.33) MSE
同样,我们需要做的就是定义一个创建神经网络模型的新函数。在这里,与 13 到 20 的基线模型相比,我们增加了隐藏层中神经元的数量。
```
```py
# define wider model
def wider_model():
# create model
......@@ -220,13 +220,13 @@ def wider_model():
我们的网络拓扑现在看起来像:
```
```py
13 inputs -> [20] -> 1 output
```
我们可以使用与上面相同的方案评估更广泛的网络拓扑:
```
```py
numpy.random.seed(seed)
estimators = []
estimators.append(('standardize', StandardScaler()))
......@@ -239,7 +239,7 @@ print("Wider: %.2f (%.2f) MSE" % (results.mean(), results.std()))
建立模型的确看到误差进一步下降到大约 2.1 万平方美元。对于这个问题,这不是一个糟糕的结果。
```
```py
Wider: 21.64 (23.75) MSE
```
......
......@@ -75,7 +75,7 @@
下面列出了准备数据的代码。
```
```py
# create sequence
length = 10
sequence = [i/float(length) for i in range(length)]
......@@ -96,7 +96,7 @@ X, y = values[:,0], values[:,1]
网络代码如下所示。
```
```py
# design network
model = Sequential()
model.add(Dense(10, input_dim=1))
......@@ -113,7 +113,7 @@ print(mean_squared_error(y, yhat[:,0]))
完整的代码清单如下。
```
```py
from pandas import DataFrame
from pandas import concat
from keras.models import Sequential
......@@ -153,7 +153,7 @@ for _ in range(repeats):
您的具体结果会有所不同。下面提供了一个示例输出。
```
```py
0.0282584265697
0.0457025913022
0.145698137198
......@@ -202,7 +202,7 @@ for _ in range(repeats):
我们可以通过从随机模块调用 [seed()函数](https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.seed.html)来播种 NumPy 随机数生成器,如下所示:
```
```py
from numpy.random import seed
seed(1)
```
......@@ -215,7 +215,7 @@ seed(1)
每次运行代码时都应该看到相同的均方误差值列表(可能由于不同机器上的精度而有一些微小的变化),如下所示:
```
```py
0.169326527063
2.75750621228e-05
0.0183287291562
......@@ -236,21 +236,21 @@ Keras 确实从 NumPy 随机数生成器获得随机源,因此无论您使用
必须通过在任何其他导入或其他代码之前调用文件顶部的 [seed()函数](https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.seed.html)来播种。
```
```py
from numpy.random import seed
seed(1)
```
此外,TensorFlow 还有自己的随机数生成器,必须通过在 NumPy 随机数生成器之后立即调用 [set_random_seed()函数](https://www.tensorflow.org/api_docs/python/tf/set_random_seed)来播种,如下所示:
```
```py
from tensorflow import set_random_seed
set_random_seed(2)
```
为了清楚起见,代码文件的顶部必须在任何其他文件之前有以下 4 行;
```
```py
from numpy.random import seed
seed(1)
from tensorflow import set_random_seed
......@@ -261,7 +261,7 @@ set_random_seed(2)
将这 4 行添加到上面的示例将允许代码在每次运行时生成相同的结果。您应该看到与下面列出的相同的均方误差值(由于不同机器上的精度,可能会有一些微小的变化):
```
```py
0.224045112999
0.00154879478823
0.00387589994044
......
......@@ -56,7 +56,7 @@
运行单个脚本( _myscript.py_ )如下所示:
```
```py
python -u myscript.py >myscript.py.log 2>&1
```
......@@ -68,7 +68,7 @@ python -u myscript.py >myscript.py.log 2>&1
创建一个 shell 脚本,按顺序列出多个实验。例如:
```
```py
#!/bin/sh
# run experiments
......@@ -83,7 +83,7 @@ python -u myscript5.py >myscript5.py.log 2>&1
例如,如果所有代码和 run.sh 脚本都位于“ _ec2-user_ ”主目录的“ _experiments_ ”目录中,则脚本将按如下方式运行:
```
```py
nohup /home/ec2-user/experiments/run.sh > /home/ec2-user/experiments/run.sh.log </dev/null 2>&1 &
```
......
......@@ -40,7 +40,7 @@ Keras 将保存模型架构和保存模型权重的问题分开。
注意:您可能需要先安装 _h5py_ :
```
```py
sudo pip install h5py
```
......@@ -58,7 +58,7 @@ Keras 提供了使用带有 _to_json()_ 函数的 JSON 格式描述任何模
以相同的方式评估模型,打印相同的评估分数。
```
```py
# MLP for Pima Indians Dataset Serialize to JSON and HDF5
from keras.models import Sequential
from keras.layers import Dense
......@@ -112,7 +112,7 @@ print("%s: %.2f%%" % (loaded_model.metrics_names[1], score[1]*100))
运行此示例提供下面的输出。
```
```py
acc: 78.78%
Saved model to disk
Loaded model from disk
......@@ -121,7 +121,7 @@ acc: 78.78%
该模型的 JSON 格式如下所示:
```
```py
{
"keras_version":"2.0.2",
"backend":"theano",
......@@ -229,7 +229,7 @@ acc: 78.78%
使用 YAML 描述模型,保存到文件 model.yaml,然后通过 _model_from_yaml()_ 函数加载到新模型中。权重的处理方式与上面 HDF5 格式相同,如 model.h5。
```
```py
# MLP for Pima Indians Dataset serialize to YAML and HDF5
from keras.models import Sequential
from keras.layers import Dense
......@@ -284,7 +284,7 @@ print("%s: %.2f%%" % (loaded_model.metrics_names[1], score[1]*100))
运行该示例将显示以下输出:
```
```py
acc: 78.78%
Saved model to disk
Loaded model from disk
......@@ -293,7 +293,7 @@ acc: 78.78%
以 YAML 格式描述的模型如下所示:
```
```py
backend: theano
class_name: Sequential
config:
......
......@@ -52,7 +52,7 @@ Phil Whitehouse 的照片,保留一些权利。
您可以使用您喜欢的任何种子初始化随机数生成器,例如:
```
```py
from keras.models import Sequential
from keras.layers import Dense
import numpy
......@@ -71,13 +71,13 @@ numpy.random.seed(7)
下载数据集并将其放在本地工作目录中,与 python 文件相同。使用文件名保存:
```
```py
pima-indians-diabetes.csv
```
您现在可以使用 NumPy 函数 **loadtxt()**直接加载文件。有八个输入变量和一个输出变量(最后一列)。加载后,我们可以将数据集拆分为输入变量(X)和输出类变量(Y)。
```
```py
# load pima indians dataset
dataset = numpy.loadtxt("pima-indians-diabetes.csv", delimiter=",")
# split into input (X) and output (Y) variables
......@@ -113,7 +113,7 @@ Keras 中的模型被定义为层序列。
我们可以通过添加每一层将它们拼凑在一起。第一层有 12 个神经元,需要 8 个输入变量。第二个隐藏层有 8 个神经元,最后,输出层有 1 个神经元来预测类别(是否发生糖尿病)。
```
```py
# create model
model = Sequential()
model.add(Dense(12, input_dim=8, activation='relu'))
......@@ -135,7 +135,7 @@ model.add(Dense(1, activation='sigmoid'))
最后,因为它是一个分类问题,我们将收集并报告分类准确度作为指标。
```
```py
# Compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
```
......@@ -152,7 +152,7 @@ model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']
对于这个问题,我们将运行少量迭代(150)并使用相对较小的批量大小 10.再次,这些可以通过试验和错误通过实验选择。
```
```py
# Fit the model
model.fit(X, Y, epochs=150, batch_size=10)
```
......@@ -173,7 +173,7 @@ model.fit(X, Y, epochs=150, batch_size=10)
这将为每个输入和输出对生成预测并收集分数,包括平均损失和您配置的任何指标,例如准确性。
```
```py
# evaluate the model
scores = model.evaluate(X, Y)
print("\n%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
......@@ -185,7 +185,7 @@ print("\n%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
让我们将它们组合成一个完整的代码示例。
```
```py
# Create your first MLP in Keras
from keras.models import Sequential
from keras.layers import Dense
......@@ -215,7 +215,7 @@ print("\n%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
在带有 Theano 后端的 CPU 上运行的工作站上执行大约需要 10 秒钟。
```
```py
...
Epoch 145/150
768/768 [==============================] - 0s - loss: 0.5105 - acc: 0.7396
......@@ -257,7 +257,7 @@ acc: 78.26%
下面列出了为训练数据中的每条记录进行预测的完整示例。
```
```py
# Create first network with Keras
from keras.models import Sequential
from keras.layers import Dense
......@@ -288,7 +288,7 @@ print(rounded)
现在运行此修改示例将打印每个输入模式的预测。如果需要,我们可以直接在我们的应用程序中使用这些预测
```
```py
[1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0]
```
......
......@@ -39,7 +39,7 @@
首先,让我们导入我们计划在本教程中使用的所有类和函数。
```
```py
import numpy
from keras.models import Sequential
from keras.layers import Dense
......@@ -49,7 +49,7 @@ from keras.utils import np_utils
接下来,我们可以为随机数生成器播种,以确保每次执行代码时结果都相同。
```
```py
# fix random seed for reproducibility
numpy.random.seed(7)
```
......@@ -58,7 +58,7 @@ numpy.random.seed(7)
神经网络模型编号,因此我们需要将字母表的字母映射为整数值。我们可以通过创建字符索引的字典(map)来轻松完成此操作。我们还可以创建反向查找,以便将预测转换回字符以便以后使用。
```
```py
# define the raw dataset
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
# create mapping of characters to integers (0-25) and the reverse
......@@ -70,7 +70,7 @@ int_to_char = dict((i, c) for i, c in enumerate(alphabet))
例如,我们使用输入长度 1.从原始输入数据的开头开始,我们可以读出第一个字母“A”和下一个字母作为预测“B”。我们沿着一个角色移动并重复直到我们达到“Z”的预测。
```
```py
# prepare the dataset of input to output pairs encoded as integers
seq_length = 1
dataX = []
......@@ -87,7 +87,7 @@ for i in range(0, len(alphabet) - seq_length, 1):
将代码运行到此点将产生以下输出,总结长度为 1 的输入序列和单个输出字符。
```
```py
A -> B
B -> C
C -> D
......@@ -117,21 +117,21 @@ Y -> Z
我们需要将 NumPy 阵列重新整形为 LSTM 网络所期望的格式,即[_ 样本,时间步长,特征 _]。
```
```py
# reshape X to be [samples, time steps, features]
X = numpy.reshape(dataX, (len(dataX), seq_length, 1))
```
一旦重新整形,我们就可以将输入整数归一化到 0 到 1 的范围,即 LSTM 网络使用的 S 形激活函数的范围。
```
```py
# normalize
X = X / float(len(alphabet))
```
最后,我们可以将此问题视为序列分类任务,其中 26 个字母中的每一个代表不同的类。因此,我们可以使用 Keras 内置函数 **to_categorical()**将输出(y)转换为一个热编码。
```
```py
# one hot encode the output variable
y = np_utils.to_categorical(dataY)
```
......@@ -148,7 +148,7 @@ y = np_utils.to_categorical(dataY)
该模型适用于 500 个时期,批量大小为 1。
```
```py
# create and fit the model
model = Sequential()
model.add(LSTM(32, input_shape=(X.shape[1], X.shape[2])))
......@@ -159,7 +159,7 @@ model.fit(X, y, epochs=500, batch_size=1, verbose=2)
在我们拟合模型之后,我们可以评估和总结整个训练数据集的性能。
```
```py
# summarize performance of the model
scores = model.evaluate(X, y, verbose=0)
print("Model Accuracy: %.2f%%" % (scores[1]*100))
......@@ -167,7 +167,7 @@ print("Model Accuracy: %.2f%%" % (scores[1]*100))
然后,我们可以通过网络重新运行训练数据并生成预测,将输入和输出对转换回原始字符格式,以便直观地了解网络如何了解问题。
```
```py
# demonstrate some model predictions
for pattern in dataX:
x = numpy.reshape(pattern, (1, len(pattern), 1))
......@@ -181,7 +181,7 @@ for pattern in dataX:
下面提供了整个代码清单,以确保完整性。
```
```py
# Naive LSTM to learn one-char to one-char mapping
import numpy
from keras.models import Sequential
......@@ -233,7 +233,7 @@ for pattern in dataX:
运行此示例将生成以下输出。
```
```py
Model Accuracy: 84.00%
['A'] -> B
['B'] -> C
......@@ -278,14 +278,14 @@ Model Accuracy: 84.00%
在这里,我们将序列长度从 1 增加到 3,例如:
```
```py
# prepare the dataset of input to output pairs encoded as integers
seq_length = 3
```
这创建了以下培训模式:
```
```py
ABC -> D
BCD -> E
CDE -> F
......@@ -293,20 +293,20 @@ CDE -> F
然后,序列中的每个元素作为新的输入特征提供给网络。这需要修改数据准备步骤中输入序列的重新形成方式:
```
```py
# reshape X to be [samples, time steps, features]
X = numpy.reshape(dataX, (len(dataX), 1, seq_length))
```
在演示模型的预测时,还需要修改样本模式的重新整形方式。
```
```py
x = numpy.reshape(pattern, (1, 1, len(pattern)))
```
下面提供了整个代码清单,以确保完整性。
```
```py
# Naive LSTM to learn three-char window to one-char mapping
import numpy
from keras.models import Sequential
......@@ -358,7 +358,7 @@ for pattern in dataX:
运行此示例提供以下输出。
```
```py
Model Accuracy: 86.96%
['A', 'B', 'C'] -> D
['B', 'C', 'D'] -> E
......@@ -397,13 +397,13 @@ Model Accuracy: 86.96%
我们可以采用我们的第一个例子,只需将序列长度从 1 更改为 3。
```
```py
seq_length = 3
```
同样,这会创建输入 - 输出对,如下所示:
```
```py
ABC -> D
BCD -> E
CDE -> F
......@@ -412,14 +412,14 @@ DEF -> G
不同之处在于输入数据的重新整形将序列作为一个特征的时间步长序列,而不是多个特征的单个时间步长。
```
```py
# reshape X to be [samples, time steps, features]
X = numpy.reshape(dataX, (len(dataX), seq_length, 1))
```
这是为 Keras 中的 LSTM 提供序列上下文的正确用途。完整性代码示例如下所示。
```
```py
# Naive LSTM to learn three-char time steps to one-char mapping
import numpy
from keras.models import Sequential
......@@ -471,7 +471,7 @@ for pattern in dataX:
运行此示例提供以下输出。
```
```py
Model Accuracy: 100.00%
['A', 'B', 'C'] -> D
['B', 'C', 'D'] -> E
......@@ -516,7 +516,7 @@ LSTM 的 Keras 实现在每批之后重置网络状态。
此外,Keras 在每个训练时期之前对训练数据集进行混洗。为确保训练数据模式保持连续,我们可以禁用此改组。
```
```py
model.fit(X, y, epochs=5000, batch_size=len(dataX), verbose=2, shuffle=False)
```
......@@ -524,7 +524,7 @@ model.fit(X, y, epochs=5000, batch_size=len(dataX), verbose=2, shuffle=False)
完整性代码示例如下所示。
```
```py
# Naive LSTM to learn one-char to one-char mapping with all data in each batch
import numpy
from keras.models import Sequential
......@@ -591,7 +591,7 @@ for i in range(0,20):
运行该示例提供以下输出。
```
```py
Model Accuracy: 100.00%
['A'] -> B
['B'] -> C
......@@ -659,14 +659,14 @@ Test a Random Pattern:
我们首先需要将 LSTM 层定义为有状态。这样,我们必须明确指定批量大小作为输入形状的维度。这也意味着,当我们评估网络或进行预测时,我们还必须指定并遵守相同的批量大小。现在这不是一个问题,因为我们使用批量大小为 1.当批量大小不是一个时,这可能会在进行预测时带来困难,因为需要批量和按顺序进行预测。
```
```py
batch_size = 1
model.add(LSTM(50, batch_input_shape=(batch_size, X.shape[1], X.shape[2]), stateful=True))
```
训练有状态 LSTM 的一个重要区别是我们一次手动训练一个时期并在每个时期后重置状态。我们可以在 for 循环中执行此操作。同样,我们不会改变输入,保留输入训练数据的创建顺序。
```
```py
for i in range(300):
model.fit(X, y, epochs=1, batch_size=batch_size, verbose=2, shuffle=False)
model.reset_states()
......@@ -674,7 +674,7 @@ for i in range(300):
如上所述,我们在评估整个训练数据集的网络性能时指定批量大小。
```
```py
# summarize performance of the model
scores = model.evaluate(X, y, batch_size=batch_size, verbose=0)
model.reset_states()
......@@ -683,7 +683,7 @@ print("Model Accuracy: %.2f%%" % (scores[1]*100))
最后,我们可以证明网络确实学会了整个字母表。我们可以用第一个字母“A”播种它,请求预测,将预测反馈作为输入,并一直重复该过程到“Z”。
```
```py
# demonstrate some model predictions
seed = [char_to_int[alphabet[0]]]
for i in range(0, len(alphabet)-1):
......@@ -698,7 +698,7 @@ model.reset_states()
我们还可以看到网络是否可以从任意字母开始进行预测。
```
```py
# demonstrate a random starting point
letter = "K"
seed = [char_to_int[letter]]
......@@ -715,7 +715,7 @@ model.reset_states()
下面提供了整个代码清单,以确保完整性。
```
```py
# Stateful LSTM to learn one-char to one-char mapping
import numpy
from keras.models import Sequential
......@@ -784,7 +784,7 @@ model.reset_states()
运行该示例提供以下输出。
```
```py
Model Accuracy: 100.00%
A -> B
B -> C
......@@ -827,7 +827,7 @@ E -> F
为了真实地预测“K”,需要将网络的状态反复加热,将字母从“A”加到“J”。这告诉我们,通过准备以下训练数据,我们可以通过“无状态”LSTM 实现相同的效果:
```
```py
---a -> b
--ab -> c
-abc -> d
......@@ -848,7 +848,7 @@ abcd -> e
我们还需要定义要创建的随机序列的数量,在本例中为 1000.这也可能更多或更少。我希望实际上需要更少的模式。
```
```py
# prepare the dataset of input to output pairs encoded as integers
num_inputs = 1000
max_len = 5
......@@ -866,7 +866,7 @@ for i in range(num_inputs):
在更广泛的上下文中运行此代码将创建如下所示的输入模式:
```
```py
PQRST -> U
W -> X
O -> P
......@@ -880,7 +880,7 @@ GHIJ -> K
输入序列的长度在 1 和 **max_len** 之间变化,因此需要零填充。这里,我们使用左侧(前缀)填充和 **pad_sequences()**函数中内置的 Keras。
```
```py
X = pad_sequences(dataX, maxlen=max_len, dtype='float32')
```
......@@ -888,7 +888,7 @@ X = pad_sequences(dataX, maxlen=max_len, dtype='float32')
完整性代码清单如下所示。
```
```py
# LSTM with Variable Length Input Sequences to One Character Output
import numpy
from keras.models import Sequential
......@@ -951,7 +951,7 @@ for i in range(20):
运行此代码将生成以下输出:
```
```py
Model Accuracy: 98.90%
['Q', 'R'] -> S
['W', 'X'] -> Y
......
......@@ -55,7 +55,7 @@ Keras 中的 KerasClassifier 和 KerasRegressor 类接受一个参数 **build_fn
我们使用 scikit-learn 函数 **cross_val_score()**来使用交叉验证方案评估我们的模型并打印结果。
```
```py
# MLP for Pima Indians Dataset with 10-fold cross validation via sklearn
from keras.models import Sequential
from keras.layers import Dense
......@@ -93,7 +93,7 @@ print(results.mean())
运行该示例显示每个纪元的模型技能。创建和评估总共 10 个模型,并显示最终的平均精度。
```
```py
0.646838691487
```
......@@ -120,7 +120,7 @@ print(results.mean())
最后,显示最佳模型的性能和配置组合,然后显示所有参数组合的性能。
```
```py
# MLP for Pima Indians Dataset with grid search via sklearn
from keras.models import Sequential
from keras.layers import Dense
......@@ -170,7 +170,7 @@ for mean, stdev, param in zip(means, stds, params):
我们可以看到,网格搜索发现使用统一初始化方案,rmsprop 优化器,150 个历元和 5 个批处理大小在此问题上实现了大约 75%的最佳交叉验证分数。
```
```py
Best: 0.752604 using {'init': 'uniform', 'optimizer': 'adam', 'batch_size': 5, 'epochs': 150}
0.707031 (0.025315) with: {'init': 'glorot_uniform', 'optimizer': 'rmsprop', 'batch_size': 5, 'epochs': 50}
0.589844 (0.147095) with: {'init': 'glorot_uniform', 'optimizer': 'adam', 'batch_size': 5, 'epochs': 50}
......
......@@ -92,7 +92,7 @@ Keras 通过 VGG16 和 VGG19 类提供 16 层和 19 层版本。让我们关注
可以按如下方式创建模型:
```
```py
from keras.applications.vgg16 import VGG16
model = VGG16()
```
......@@ -109,7 +109,7 @@ model = VGG16()
例如,您可以打印网络层的摘要,如下所示:
```
```py
from keras.applications.vgg16 import VGG16
model = VGG16()
print(model.summary())
......@@ -119,7 +119,7 @@ print(model.summary())
您还可以看到,默认情况下,模型要求图像作为输入,大小为 224 x 224 像素,具有 3 个通道(例如颜色)。
```
```py
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
......@@ -177,7 +177,7 @@ _________________________________________________________________
我们还可以在 VGG 模型中创建图层,如下所示:
```
```py
from keras.applications.vgg16 import VGG16
from keras.utils.vis_utils import plot_model
model = VGG16()
......@@ -224,7 +224,7 @@ _VGG()_ 类需要一些参数,如果您希望在自己的项目中使用
加载 VGG-16 型号的重量,就像我们在上一节中所做的那样。
```
```py
from keras.applications.vgg16 import VGG16
# load the model
model = VGG16()
......@@ -238,7 +238,7 @@ Keras 提供了一些帮助完成此步骤的工具。
首先,我们可以使用 _load_img()_ 函数加载图像并将其大小调整为所需的 224×224 像素大小。
```
```py
from keras.preprocessing.image import load_img
# load an image from file
image = load_img('mug.jpg', target_size=(224, 224))
......@@ -246,7 +246,7 @@ image = load_img('mug.jpg', target_size=(224, 224))
接下来,我们可以将像素转换为 NumPy 数组,以便我们可以在 Keras 中使用它。我们可以使用 _img_to_array()_ 函数。
```
```py
from keras.preprocessing.image import img_to_array
# convert the image pixels to a numpy array
image = img_to_array(image)
......@@ -256,7 +256,7 @@ image = img_to_array(image)
我们只有一个样本(一个图像)。我们可以通过调用 _reshape()_ 并添加额外的维度来重新整形数组。
```
```py
# reshape data for the model
image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))
```
......@@ -269,7 +269,7 @@ image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))
Keras 提供了一个名为 _preprocess_input()_ 的函数来为网络准备新的输入。
```
```py
from keras.applications.vgg16 import preprocess_input
# prepare the image for the VGG model
image = preprocess_input(image)
......@@ -281,7 +281,7 @@ image = preprocess_input(image)
我们可以在模型上调用 _predict()_ 函数,以便预测属于 1000 种已知对象类型中的每一种的图像的概率。
```
```py
# predict the probability across all output classes
yhat = model.predict(image)
```
......@@ -296,7 +296,7 @@ Keras 提供了解释称为 _decode_predictions()_ 的概率的函数。
我们将报告第一个最可能的对象。
```
```py
from keras.applications.vgg16 import decode_predictions
# convert the probabilities to class labels
label = decode_predictions(yhat)
......@@ -312,7 +312,7 @@ print('%s (%.2f%%)' % (label[1], label[2]*100))
将所有这些结合在一起,下面列出了完整的示例:
```
```py
from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.applications.vgg16 import preprocess_input
......@@ -340,7 +340,7 @@ print('%s (%.2f%%)' % (label[1], label[2]*100))
运行该示例,我们可以看到图像被正确分类为“_ 咖啡杯 _”,可能性为 75%。
```
```py
coffee_mug (75.27%)
```
......
......@@ -45,13 +45,13 @@ Keras 内置了基于时间的学习率计划。
SGD 类中的随机梯度下降优化算法实现具有称为衰减的参数。该参数用于基于时间的学习率衰减调度方程如下:
```
```py
LearningRate = LearningRate * 1/(1 + decay * epoch)
```
当衰减参数为零(默认值)时,这对学习速率没有影响。
```
```py
LearningRate = 0.1 * 1/(1 + 0.0 * 1)
LearningRate = 0.1
```
......@@ -60,7 +60,7 @@ LearningRate = 0.1
例如,如果我们使用 0.1 的初始学习率值和 0.001 的衰减,前 5 个时期将调整学习率如下:
```
```py
Epoch Learning Rate
1 0.1
2 0.0999000999
......@@ -77,7 +77,7 @@ Epoch Learning Rate
您可以通过设置衰减值来创建一个不错的默认计划,如下所示:
```
```py
Decay = LearningRate / Epochs
Decay = 0.1 / 100
Decay = 0.001
......@@ -95,7 +95,7 @@ Decay = 0.001
下面列出了完整的示例。
```
```py
# Time Based Learning Rate Decay
from pandas import read_csv
import numpy
......@@ -135,7 +135,7 @@ model.fit(X, Y, validation_split=0.33, epochs=epochs, batch_size=28, verbose=2)
运行该示例显示分类准确度为 99.14%。如果没有学习率下降或动量,这高于 95.69%的基线。
```
```py
...
Epoch 45/50
0s - loss: 0.0622 - acc: 0.9830 - val_loss: 0.0929 - val_acc: 0.9914
......@@ -169,7 +169,7 @@ LearningRateScheduler 回调允许我们定义一个调用函数,该函数将
在下面的代码中,我们在 Ionosphere 数据集上的单个隐藏层网络之前使用相同的示例。定义了一个新的 step_decay()函数来实现等式:
```
```py
LearningRate = InitialLearningRate * DropRate^floor(Epoch / EpochDrop)
```
......@@ -177,7 +177,7 @@ LearningRate = InitialLearningRate * DropRate^floor(Epoch / EpochDrop)
请注意,我们将 SGD 类中的学习速率设置为 0,以清楚地表明它未被使用。不过,如果您想在此学习率计划中使用动量,则可以设置新元的动量项。
```
```py
# Drop-Based Learning Rate Decay
import pandas
from pandas import read_csv
......@@ -226,7 +226,7 @@ model.fit(X, Y, validation_split=0.33, epochs=50, batch_size=28, callbacks=callb
运行该示例会导致验证数据集的分类准确率达到 99.14%,这也是问题模型基线的改进。
```
```py
...
Epoch 45/50
0s - loss: 0.0546 - acc: 0.9830 - val_loss: 0.0634 - val_acc: 0.9914
......
......@@ -36,13 +36,13 @@ Keras Python 深度学习库提供了可视化和更好地理解您的神经网
例如:
```
```py
[1 input] -> [2 neurons] -> [1 output]
```
下面提供了该网络的代码清单。
```
```py
from keras.models import Sequential
from keras.layers import Dense
model = Sequential()
......@@ -65,7 +65,7 @@ Keras 提供了一种总结模型的方法。
下面是打印已创建模型摘要的更新示例。
```
```py
from keras.models import Sequential
from keras.layers import Dense
model = Sequential()
......@@ -76,7 +76,7 @@ print(model.summary())
运行此示例将打印下表。
```
```py
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
......@@ -109,7 +109,7 @@ Keras 中的 _plot_model()_ 功能将创建您的网络图。这个函数有
注意,该示例假设您已安装 [graphviz 图形库](http://www.graphviz.org/)[Python 接口](https://pypi.python.org/pypi/graphviz)
```
```py
from keras.models import Sequential
from keras.layers import Dense
from keras.utils.vis_utils import plot_model
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册