上学笔记TF054,深度学习初大家使用Keras创设和配置CNN模型

机械学习,神经网络,分类,回归,CNN,TensorFlow,Keras,深度学习等等那些词对您来讲并不素不相识。网络充斥着学习机器学习的能源。在过去的几年里,机器学习已经凌犯了大家平时生活的各样方面。直接或直接地,有意或无意识地,大家每日都与机械和工具学习算法进行互相。即便机器学习已经存在了几十年,但如今选取的剧增相当大程度上是由于大家未来怀有的相对化总计工夫。深度学习模型正在云上的可观复杂和强劲的硬件系统上开始展览操练和安顿。

元框架(metaframework)。

元框架(metaframework)。

本文将首要介绍怎样创设三个秀气机器学习项目。目标是令你理解怎么营造,培养和演练和配置自个儿的机械学习模型。使用流行的MNIST手写数字数据集创设袖珍卷积神经网络模型并将其铺排在地头计算机上的为主介绍。

TFLearn。模块化深度学习框架,更加高端API,快速实验,完全透明包容。

TFLearn。模块化深度学习框架,更加尖端API,急速实验,完全透明包容。

本课程的基本是利用Keras营造三个能够辨别手写数字的迷你CNN模型。我们将选取我们操练有素的模型来鉴定识别咱们使用鼠标指针在网页上编制的数字。那亟需大家应用HTML,Javascript和Flask创设一个小型Web应用程序。不过你能够复制并粘贴该部分的代码,因为大家的根本对象不是起家网址,而是选拔Keras制作CNN模型。

TFLearn实现AlexNet。

俄亥俄州立大学鲜花数据集(FlowerDataset)。
。提供14个品类鲜花数据,每种项目80张图纸,有恢宏态势、光变化。

TFLearn实现AlexNet。

浦项电影大学鲜花数据集(FlowerDataset)。
。提供14个类别鲜花数据,各样门类80张图纸,有雅量神态、光变化。

营造立模型型

# -*- coding: utf-8 -*-
“”” AlexNet.
Applying ‘Alexnet’ to Oxford’s 17 Category Flower Dataset classification
task.
References:

# -*- coding: utf-8 -*-
“”” AlexNet.
Applying ‘Alexnet’ to Oxford’s 17 Category Flower Dataset classification
task.
References:

要起首应用,您能够展开Windows
cmd终端并激活安装了Keras和其余依赖项的Anaconda情状。activate MyEnvDL

  • Alex Krizhevsky, Ilya Sutskever & Geoffrey E. Hinton. ImageNet
    Classification with Deep Convolutional Neural Networks. NIPS, 2012.
  • 17 Category Flower Dataset. Maria-Elena Nilsback and Andrew
    Zisserman.
    Links:
  • [AlexNet
    Paper]()
  • [Flower Dataset
    (17)]()
    “””
    from __future__ import division, print_function, absolute_import
    import tflearn
    from tflearn.layers.core import input_data, dropout, fully_connected
    from tflearn.layers.conv import conv_2d, max_pool_2d
    from tflearn.layers.normalization import
    local_response_normalization
    from tflearn.layers.estimator import regression
    import tflearn.datasets.oxflower17 as oxflower17
    # 加载数据
    X, Y = oxflower17.load_data(one_hot=True, resize_pics=(227, 227))
    # Building ‘亚历克斯Net’ 营造网络模型
    network = input_data(shape=[None, 227, 227, 3])
    network = conv_2d(network, 96, 11, strides=4, activation=’relu’)
    network = max_pool_2d(network, 3, strides=2)
    network = local_response_normalization(network)
    network = conv_2d(network, 256, 5, activation=’relu’)
    network = max_pool_2d(network, 3, strides=2)
    network = local_response_normalization(network)
    network = conv_2d(network, 384, 3, activation=’relu’)
    network = conv_2d(network, 384, 3, activation=’relu’)
    network = conv_2d(network, 256, 3, activation=’relu’)
    network = max_pool_2d(network, 3, strides=2)
    network = local_response_normalization(network)
    network = fully_connected(network, 4096, activation=’tanh’)
    network = dropout(network, 0.5)
    network = fully_connected(network, 4096, activation=’tanh’)
    network = dropout(network, 0.5)
    network = fully_connected(network, 17, activation=’softmax’)
    network = regression(network, optimizer=’momentum’,
    loss=’categorical_crossentropy’,
    learning_rate=0.001)
    # Training 演练模型 载入亚历克斯Net模型检查点文件
    model = tflearn.DNN(network, checkpoint_path=’model_alexnet’,
    max_checkpoints=1, tensorboard_verbose=2)
    model.fit(X, Y, n_epoch=1000, validation_set=0.1, shuffle=True,
    show_可靠的线上网赌网站,metric=True, batch_size=64, snapshot_step=200,
    snapshot_epoch=False, run_id=’alexnet_oxflowers17′)
  • Alex Krizhevsky, Ilya Sutskever & Geoffrey E. Hinton. ImageNet
    Classification with Deep Convolutional Neural Networks. NIPS, 2012.
  • 17 Category Flower Dataset. Maria-Elena Nilsback and Andrew
    Zisserman.
    Links:
  • [AlexNet
    Paper]()
  • [Flower Dataset
    (17)]()
    “””
    from __future__ import division, print_function, absolute_import
    import tflearn
    from tflearn.layers.core import input_data, dropout, fully_connected
    from tflearn.layers.conv import conv_2d, max_pool_2d
    from tflearn.layers.normalization import
    local_response_normalization
    from tflearn.layers.estimator import regression
    import tflearn.datasets.oxflower17 as oxflower17
    # 加载数据
    X, Y = oxflower17.load_data(one_hot=True, resize_pics=(227, 227))
    # Building ‘亚历克斯Net’ 创设网络模型
    network = input_data(shape=[None, 227, 227, 3])
    network = conv_2d(network, 96, 11, strides=4, activation=’relu’)
    network = max_pool_2d(network, 3, strides=2)
    network = local_response_normalization(network)
    network = conv_2d(network, 256, 5, activation=’relu’)
    network = max_pool_2d(network, 3, strides=2)
    network = local_response_normalization(network)
    network = conv_2d(network, 384, 3, activation=’relu’)
    network = conv_2d(network, 384, 3, activation=’relu’)
    network = conv_2d(network, 256, 3, activation=’relu’)
    network = max_pool_2d(network, 3, strides=2)
    network = local_response_normalization(network)
    network = fully_connected(network, 4096, activation=’tanh’)
    network = dropout(network, 0.5)
    network = fully_connected(network, 4096, activation=’tanh’)
    network = dropout(network, 0.5)
    network = fully_connected(network, 17, activation=’softmax’)
    network = regression(network, optimizer=’momentum’,
    loss=’categorical_crossentropy’,
    learning_rate=0.001)
    # Training 练习模型 载入亚历克斯Net模型检查点文件
    model = tflearn.DNN(network, checkpoint_path=’model_alexnet’,
    max_checkpoints=1, tensorboard_verbose=2)
    model.fit(X, Y, n_epoch=1000, validation_set=0.1, shuffle=True,
    show_metric=True, batch_size=64, snapshot_step=200,
    snapshot_epoch=False, run_id=’alexnet_oxflowers17′)

激活情形后,意况名称将显得在cmd终端上,如下所示。在别的你喜欢的地点创建二个具备任何名称的新文件夹,然后运维Jupyter台式机。C:\Users\Administrator>mkdir
“Keras Deploy”

Keras。高端Python神经网络框架。

Keras。高等Python神经网络框架。

C:\Users\Administrator>cd “Keras Deploy”

Keras模型。Keras焦点数据结构是模型。模型组织互联网层。Sequential模型,互连网层顺序构成栈,单输入单输出,层间独有周边关系,轻巧模型。Model模型构建复杂模型。
Sequential模型。加载完数据,X_train,Y_train,X_test,Y_test。创设立模型型:
from keras.models import Sequential
from keras.layers.core import Dense, Dropout,Activation

Keras模型。Keras宗旨数据结构是模型。模型协会互连网层。Sequential模型,互连网层顺序构成栈,单输入单输出,层间唯有周围关系,轻巧模型。Model模型创设复杂模型。
Sequential模型。加载完数据,X_train,Y_train,X_test,Y_test。创设立模型型:
from keras.models import Sequential
from keras.layers.core import Dense, Dropout,Activation

C:\Users\Administrator\Keras Deploy>jupyter notebook

model = Sequential()
model.add(Dense(output_dim=64, input_dim=100))
model.add(Activation(‘relu’))
model.add(Dense(output_dim=10))
model.add(Activation(‘softmax’))

model = Sequential()
model.add(Dense(output_dim=64, input_dim=100))
model.add(Activation(‘relu’))
model.add(Dense(output_dim=10))
model.add(Activation(‘softmax’))

可靠的线上网赌网站 1

model.compile(loss=’categorical_crossentropy’, optimizer=’sgd’,
metrics=’accuracy’)
model.fit(X_train, Y_train, batch_size=32, nb_epoch=5)
loss_and_metrics = model.evaluate(X_test, Y_test, batch_size=32)

model.compile(loss=’categorical_crossentropy’, optimizer=’sgd’,
metrics=’accuracy’)
model.fit(X_train, Y_train, batch_size=32, nb_epoch=5)
loss_and_metrics = model.evaluate(X_test, Y_test, batch_size=32)

启航Jupyter Notebook后,遵照营造CNN模型。您可以在Jupyter
notebook中的不一致单元格中编辑上边包车型地铁各个代码片段。

Keras源码示例
:CIFA途胜10-图片分类(CNN、实时数据)、IMDB-电影视商酌论意见分类(LSTM)、Reuters-音信宗旨分类(多层感知器)、MNIST-手写数字识别(多层感知器、CNN)、OC奇骏-识别字符级文本生成(LSTM)。
设置。pip install keras 。采用依赖后端,~/.keras/keras.json
修改最终一行”backend”:”fensorflow” 。

Keras源码示例
:CIFARubicon10-图片分类(CNN、实时数据)、IMDB-电影视商量论意见分类(LSTM)、Reuters-信息主旨分类(多层感知器)、MNIST-手写数字识别(多层感知器、CNN)、OCR-识别字符级文本生成(LSTM)。
设置。pip install keras 。采用依赖后端,~/.keras/keras.json
修改最终一行”backend”:”fensorflow” 。

以下代码导入创设立模型型所需的画龙点睛keras包。它还导入MNIST数据集,该数据集是70k图像的手写数字的数据集,每一种图像的分寸为28像素×28像素。import
keras

Keras完毕卷积神经网络。

Keras完成卷积神经网络。

from keras.datasets import mnist

#!/usr/bin/python
# -*- coding:utf8 -*-
”’Trains a simple convnet on the MNIST dataset.
Gets to 99.25% test accuracy after 12 epochs
(there is still a lot of margin for parameter tuning).
16 seconds per epoch on a GRID K520 GPU.
”’
from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
batch_size = 128
num_classes = 10 # 分类数
epochs = 12 # 磨炼轮数
# input image dimensions 输入图片维度
img_rows, img_cols = 28, 28
# the data, shuffled and split between train and test sets
# 加载数据
(x_train, y_train), (x_test, y_test) = mnist.load_data()
if K.image_data_format() == ‘channels_first’:
#使用Theano顺序:(conv_dim1,channels,conv_dim2,conv_dim3)
x_train = x_train.reshape(x_train.shape[0], 1, img_rows,
img_cols)
x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
input_shape = (1, img_rows, img_cols)
else:
#使用TensorFlow顺序:(conv_dim1conv_dim2,conv_dim3,channels,)
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols,
1)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)
x_train = x_train.astype(‘float32’)
x_test = x_test.astype(‘float32’)
x_train /= 255
x_test /= 255
print(‘x_train shape:’, x_train.shape)
print(x_train.shape[0], ‘train samples’)
print(x_test.shape[0], ‘test samples’)
# convert class vectors to binary class matrices
将类向量调换为二进制类矩阵
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
#模型创设:2个卷积层、1个池化层、2个全连接层
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
activation=’relu’,
input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation=’relu’))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation=’relu’))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation=’softmax’))
# 模型编写翻译
model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.Adadelta(),
metrics=[‘accuracy’])
# 模型练习
model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(x_test, y_test))
# 模型评估
score = model.evaluate(x_test, y_test, verbose=0)
print(‘Test loss:’, score[0])
print(‘Test accuracy:’, score[1])

#!/usr/bin/python
# -*- coding:utf8 -*-
”’Trains a simple convnet on the MNIST dataset.
Gets to 99.25% test accuracy after 12 epochs
(there is still a lot of margin for parameter tuning).
16 seconds per epoch on a GRID K520 GPU.
”’
from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
batch_size = 128
num_classes = 10 # 分类数
epochs = 12 # 磨炼轮数
# input image dimensions 输入图片维度
img_rows, img_cols = 28, 28
# the data, shuffled and split between train and test sets
# 加载数据
(x_train, y_train), (x_test, y_test) = mnist.load_data()
if K.image_data_format() == ‘channels_first’:
#使用Theano顺序:(conv_dim1,channels,conv_dim2,conv_dim3)
x_train = x_train.reshape(x_train.shape[0], 1, img_rows,
img_cols)
x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
input_shape = (1, img_rows, img_cols)
else:
#使用TensorFlow顺序:(conv_dim1conv_dim2,conv_dim3,channels,)
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols,
1)
x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)
x_train = x_train.astype(‘float32’)
x_test = x_test.astype(‘float32’)
x_train /= 255
x_test /= 255
print(‘x_train shape:’, x_train.shape)
print(x_train.shape[0], ‘train samples’)
print(x_test.shape[0], ‘test samples’)
# convert class vectors to binary class matrices
将类向量调换为二进制类矩阵
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
#模型营造:2个卷积层、1个池化层、2个全连接层
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
activation=’relu’,
input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation=’relu’))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation=’relu’))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation=’softmax’))
# 模型编写翻译
model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.Adadelta(),
metrics=[‘accuracy’])
# 模型磨练
model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(x_test, y_test))
# 模型评估
score = model.evaluate(x_test, y_test, verbose=0)
print(‘Test loss:’, score[0])
print(‘Test accuracy:’, score[1])

from keras.models import Sequential

模型加载保存。


Keras的save_model、load_model方法将模型、权重保存到HDF5文件。包涵模型结构、权重、磨练陈设(损失函数、优化器)。方便中断后再持续磨炼。
from keras.models import save_model, load_model

模型加载保存。


Keras的save_model、load_model方法将模型、权重保存到HDF5文件。包含模型结构、权重、操练布署(损失函数、优化器)。方便中断后再持续磨练。
from keras.models import save_model, load_model

from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D

def test_sequential_model_saving():
model = Sequential()
model.add(Dense(2, input_shape=(3,)))
model.add(RepeatVector(3))
model.add(TimeDistributed(Dense(3)))
model.compile(loss=losses.MSE,
optimizer=optimizers.RMSprop(lr=0.0001),
metrics=[metrics.categorical_accuracy],
sample_weight_mode=’temporal’)
x = np.random.random((1, 3))
y = np.random.random((1, 3, 3))
model.train_on_batch(x, y)
out = model.predict(x)
_, fname = tempfile.mkstemp(‘.h5’) # 创建HDFS 5文件
save_model(model, fname)
new_model = load_model(fname)
os.remove(fname)
out2 = new_model.predict(x)
assert_allclose(out, out2, atol=1e-05)
# test that new updates are the same with both models
# 检查实验新保存的模型和事先定义的模型是不是同样
x = np.random.random((1, 3))
y = np.random.random((1, 3, 3))
model.train_on_batch(x, y)
new_model.train_on_batch(x, y)
out = model.predict(x)
out2 = new_model.predict(x)
assert_allclose(out, out2, atol=1e-05)
只保留模型结构。

def test_sequential_model_saving():
model = Sequential()
model.add(Dense(2, input_shape=(3,)))
model.add(RepeatVector(3))
model.add(TimeDistributed(Dense(3)))
model.compile(loss=losses.MSE,
optimizer=optimizers.RMSprop(lr=0.0001),
metrics=[metrics.categorical_accuracy],
sample_weight_mode=’temporal’)
x = np.random.random((1, 3))
y = np.random.random((1, 3, 3))
model.train_on_batch(x, y)
out = model.predict(x)
_, fname = tempfile.mkstemp(‘.h5’) # 创建HDFS 5文件
save_model(model, fname)
new_model = load_model(fname)
os.remove(fname)
out2 = new_model.predict(x)
assert_allclose(out, out2, atol=1e-05)
# test that new updates are the same with both models
# 检验新保存的模子和在此之前定义的模型是否一律
x = np.random.random((1, 3))
y = np.random.random((1, 3, 3))
model.train_on_batch(x, y)
new_model.train_on_batch(x, y)
out = model.predict(x)
out2 = new_model.predict(x)
assert_allclose(out, out2, atol=1e-05)
只保留模型结构。

from keras import backend as K

json_string = model.to_jsion()
yaml_string = model.to_yaml()

json_string = model.to_jsion()
yaml_string = model.to_yaml()

可靠的线上网赌网站 2

手动编辑。

手动编辑。

大家将设置有些变量,比如用于反向传播批量轻重的类的数额以及图像的莫斯中国科学技术大学学和增长幅度。batch_size
= 128

from keras.models import model_from_json
model = model_from_json(json_string)
model = model_from_yaml(yaml_string)

from keras.models import model_from_json
model = model_from_json(json_string)
model = model_from_yaml(yaml_string)

num_classes = 10

只保留模型权重。

只保留模型权重。

epochs = 12

model.save_weights(‘my_model_weights.h5’)
model.load_weights(‘my_model_weights.h5’)

model.save_weights(‘my_model_weights.h5’)
model.load_weights(‘my_model_weights.h5’)

img_rows = 28

参谋资料:
《TensorFlow本事分析与实战》

参考资料:
《TensorFlow能力深入分析与实战》

img_cols = 28

迎接推荐新加坡机械学习工作时机,笔者的微信:qingxingfengzi

应接推荐香港(Hong Kong)机械学习专业时机,小编的微信:qingxingfengzi

x_train, y_train), (x_test, y_test) = mnist.load_data()

可靠的线上网赌网站 3

是因为图像的像素值范围为0-255,我们将把它们降低到0-1的限量。x_train =
x_train.astype(‘float32’)

x_test = x_test.astype(‘float32’)

x_train = x_train/255

x_test = x_test/255

可靠的线上网赌网站 4

你能够采纳此可选代码查看数据汇总的图像。改动x_train的目录以查看分歧的数字。import
matplotlib.pyplot as plt

%matplotlib inline

plt.imshow(x_train[0], cmap=’gray’)

上边包车型地铁代码管理图像输入模型的格式。if K.image_data_format() ==
‘channels_first’:

x_train = x_train.reshape(x_train.shape[0],1,img_rows,img_cols)

x_test = x_test.reshape(x_test.shape[0],1,img_rows,img_cols)

input_shape = (1, img_rows, img_cols)

else:

x_train = x_train.reshape(x_train.shape[0],img_rows,img_cols,1)

x_test = x_test.reshape(x_test.shape[0],img_rows,img_cols,1)

input_shape = (img_rows, img_cols, 1)

可靠的线上网赌网站 5

以下代码段创设了实际的CNN模型。今后,您将见到Keras提供的模块化功用,能够便捷构建和试验模型。model
= Sequential()

model.add(Conv2D(32, kernel_size=,activation=’relu’,
input_shape=input_shape))

model.add(Conv2D(64, kernel_size=, activation=’relu’))

model.add(MaxPooling2D(pool_size=

model.add(Dropout

model.add)

model.add(Dense(128, activation=’relu’))

model.add(Dropout

model.add(Dense(num_classes, activation=’softmax’))

可靠的线上网赌网站 6

如你所见,大家的模型中有多少个层。上边代码中的第一行伊始化了模型对象。然后使用种种model.add()向你的神经互联网增加一层。第一层是卷积层,内核或过滤器大小为
3×3,ReLU激活函数和三拾个过滤器。然后是另三个卷积层,接着是最大池化层,然后是一丝一毫连接的层。Dropout层是一种正则化技巧,用于抓牢泛化品质。请留心,您能够轻巧地在您的模型少将那么些层组合在联合model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.adam(), metrics=[‘accuracy’])

model.compile()配置我们的模子将如何学习。它定义了损失函数和用来反向传来的优化算法。编写翻译模型后,您能够见到你创设的神经互联网的摘要。model.summary()

_________________________________________________________________

Layer Output Shape Param #

=================================================================

conv2d_1 (None, 26, 26, 32) 320

_________________________________________________________________

conv2d_2 (None, 24, 24, 64) 18496

_________________________________________________________________

max_pooling2d_1 (MaxPooling2 (None, 12, 12, 64) 0

_________________________________________________________________

dropout_1 (None, 12, 12, 64) 0

_________________________________________________________________

flatten_1 (None, 9216) 0

_________________________________________________________________

dense_1 (None, 128) 1179776

_________________________________________________________________

dropout_2 (None, 128) 0

_________________________________________________________________

dense_2 1290

=================================================================

Total params: 1,199,882

Trainable params: 1,199,882

Non-trainable params: 0

_________________________________________________________________

可靠的线上网赌网站 7

请留神,第一个卷积层的输出是26×26并非28×28。您能够在卷积层中钦命填充参数,以保持经过过滤的输出图像与输入图像的尺寸同等。另请留心,大家的Mini落成中有大概120万个参数。

这段时间大家早已定义了我们的神经互联网架商谈我们想要使用的层。是时候陶冶大家的模子了:model.fit(x_train,
y_train, batch_size=batch_size, epochs=epochs, verbose=1,
validation_data=(x_test, y_test))

此命令将急需几分钟本领一鼓作气,具体取决于系统的速度。它接纳大家前边在model.compile()命令中钦命的磨练多少和参数以及优化算法来运行反向传播score
= model.evaluate(x_test, y_test, verbose=0)

print(‘Test loss:’, score[0])

print(‘Test accuracy:’, score[1])

Test loss: 0.029761945198223474

Test accuracy: 0.9911

可靠的线上网赌网站 8

作者们看出大家的模型精度达到了99.11%,非常好。大家的模子在10,000当中错误地分类了八十八个例子。您能够品味进一步调节模型以获得更加高的精度,然而以往我们将接二连三拓展此操作并保留模型。model_json
= model.to_json()

with open(“model.json”, “w”) as json_file:

json_file.write(model_json)

model.save_weights(“model.h5”)

可靠的线上网赌网站 9

我们就要布局中应用保留的model.json和model.h5文件。到近年来甘休,我们早就运用Keras飞速完结了三个CNN,并对其展开了教练,并在测验聚焦进行了测量试验。未来大家来寻访我们的模子能或无法识别大家写的数字。

配置模型

正如大家此前所说,本文的指标不是深入摸底创设Web应用程序的细节。Web应用程序仅用于证清热的,并检查大家的模子在实质上输入状态下的推市场价格况,最首要的是为了得到部分乐趣!

可靠的线上网赌网站 10

在脚下职业区中开创名称叫flask_deploy的目录C:\Users\Administrator>Keras
Deploy>mkdir flask_deploy

创办更加多目录以保留大家的CNN模型并存款和储蓄HTML,javascript,CSS和Flask文件。目录结构如下所示。不要顾忌文件的内容只是创建具备以下名称的空文件,大家稍后会在在那之中加多代码。将大家经过Jupyter
Notebook保存的keras模型复制到模型目录中。flask_deploy

|—- model

| |—- model.h5

| |—- model.json

|

|—- static

| |—- index.js

| |—- style.css

|

|—- templates

| |—- index.html

|

|—- keras_flask.py

可靠的线上网赌网站 11

在index.js文件中复制以下代码。那管理用户与Web页面包车型大巴并行。(function() {

var canvas = document.querySelector(“#canvas”);

var context = canvas.getContext;

canvas.width = 280;

canvas.height = 280;

var Mouse = { x: 0, y: 0 };

var lastMouse = { x: 0, y: 0 };

context.fillStyle = “black”;

context.fillRect(0, 0, canvas.width, canvas.height);

context.color = “white”;

context.lineWidth = 15;

context.lineJoin = context.lineCap = “round”;

clearCanvas();

canvas.addEventListener( “mousemove”,

function {

lastMouse.x = Mouse.x;

lastMouse.y = Mouse.y;

Mouse.x = e.pageX – this.offsetLeft;

Mouse.y = e.pageY – this.offsetTop;

}, false);

canvas.addEventListener(“mousedown”,

function {

canvas.addEventListener(“mousemove”, onDraw, false);

}, false);

canvas.addEventListener(“mouseup”,

function() {

canvas.removeEventListener(“mousemove”, onDraw, false);

}, false);

/* Canvas Draw */

var onDraw = function() {

context.lineWidth = context.lineWidth;

context.lineJoin = “round”;

context.lineCap = “round”;

context.strokeStyle = context.color;

context.beginPath();

context.moveTo(lastMouse.x, lastMouse.y);

context.lineTo(Mouse.x, Mouse.y);

context.closePath();

context.stroke();

};

/* This function clears the box */

function clearCanvas() {

var clearButton = $(“#clearButton”);

clearButton.on(“click”, function() {

context.clearRect(0, 0, 280, 280);

context.fillStyle = “black”;

context.fillRect(0, 0, canvas.width, canvas.height);

});

/* Slider control */

var slider = document.getElementById(“myRange”);

var output = document.getElementById(“sliderValue”);

output.innerHTML = slider.value;

slider.oninput = function() {

output.innerHTML = this.value;

context.lineWidth = $.val();

};

$(“#lineWidth”).change(function() {

context.lineWidth = $.val();

});

}})();

可靠的线上网赌网站 12

在index.html文件中复制以下代码。那是大家Web页面包车型客车着力构造及其内部的要素,如绘图框,滑块和按键。

MNIST Handwritten text recognition using keras

<!– Bootstrap core CSS –>

<link rel=”stylesheet”
href=””
integrity=”sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u”
crossorigin=”anonymous”/>

<link rel=”stylesheet” href=”{{
url_for(‘static’,filename=’style.css’) }}”/>

MNIST Handwritten CNN

Draw the digit inside this Box

Drag the slider to change the line width.

Value:

Predict

Clear

Get your prediction here!!!

Keras MNIST

<!– /container –>

<script
src=”;

<script src=”{{ url_for(‘static’,filename=’index.js’)
}}”></script><script type=”text/javascript”>

可靠的线上网赌网站 13

在style.css中复制以下代码。此文件定义了作者们的因素在大家的Web页面中的外观。body
{

padding-top: 20px;

padding-bottom: 20px;

}

.header, .footer {

padding-right: 15px;

padding-left: 15px;

}

.header {

padding-bottom: 20px;

border-bottom: 1px solid #e5e5e5;

}

.header h3 {

margin-top: 0;

margin-bottom: 0;

line-height: 40px;

}

.footer {

padding-top: 19px;

color: #777;

border-top: 1px solid #e5e5e5;

}

@media (min-width: 768px) {

.container {

max-width: 730px;

}

}

.container-narrow > hr {

margin: 30px 0;

}

.jumbotron {

text-align: center;

border-bottom: 1px solid #e5e5e5;

padding-top: 20px;

padding-bottom: 20px;

}

.bodyDiv{

text-align: center;

}

@media screen and (min-width: 768px) {

.header,

.footer {

padding-right: 0;

padding-left: 0;

}

.header {

margin-bottom: 30px;

}

.jumbotron {

border-bottom: 0;

}

}

@media screen and (max-width: 500px) {

.slidecontainer{

display: none;

}

}

.slidecontainer{

float: left;

width: 30%;

}

.jumbotronHeading{

margin-bottom: 7vh;

}

.canvasDiv{

display: flow-root;

text-align: center;

}

可靠的线上网赌网站 14

上述3个文件构成了大家的Web应用程序的前端,用户将与之相互。您将要贰个框内借助鼠标绘制四个图纸,该图片将转移为尺寸为28×28的图像,并将其传递给大家保留的模子。管理此调换的代码将由Flask管理。Flask是三个用以急忙支付网站的微框架,它是用Python编写的。

在keras_flask.py中复制以下代码。即便此代码中某些注释可协助你精晓它的功用,但精神上它会伊始化Web应用程序并从保存的文书营造CNN模型。一旦图像从Web页面发送过来,它就能因而经过磨炼的模子运营它,并赢得预测,将其传递回Web页面举办展示。#
Import flask which will handle our communication with the frontend

# Also import few other libraries

from flask import Flask, render_template, request

from scipy.misc import imread, imresize, imsave

import numpy as np

import re

import sys

import base64

import os

# Path to our saved model

sys.path.append(os.path.abspath(“./model”))

from load import *

# Initialize flask app

app = Flask

#Initialize some global variables

global model, graph

model, graph = init()

def convertImage:

imgstr = re.search(r’base64,’, str).group

with open(‘output.png’, ‘wb’) as output:

output.write(base64.b64decode

@app.route

def index():

return render_template(“index.html”)

@app.route(‘/predict/’, methods=[‘GET’, ‘POST’])

def predict():

# Predict method is called when we push the ‘Predict’ button

# on the webpage. We will feed the user drawn image to the model

# perform inference, and return the classification

imgData = request.get_data()

convertImage

# read the image into memory

x = imread(‘output.png’, mode=’L’)

# make it the right size

x = imresize(x, /255

#You can save the image to view later

imsave(‘final_image.jpg’, x)

x = x.reshape(1, 28, 28, 1)

with graph.as_default():

out = model.predict

response = np.argmax(out, axis=1)

return str(response[0])

if __name__ == “__main__”:

# run the app locally on the given port

app.run(host=’0.0.0.0′, port=5000)

可靠的线上网赌网站 15

完结此操作后,您可以步入flask_deploy目录并运转:python keras_flask.py

那将开行flask应用程序,并就要暗中认可浏览器中开荒一个选项卡。若无,请尝试在浏览器中张开http://
localhost:伍仟。若是你收到任何不当,“module not
found”,只需在你的情形中运营conda install {module name}。

只要一切顺遂,你应当看到贰个Web页面。如下所示:

可靠的线上网赌网站 16

假如您在黑框中画三个图纸。您应该从模型中收获多少个预测。

可靠的线上网赌网站 17

恭贺!您已构建并配置了第二个CNN模型。继续品尝写出不一样的数字,看看您的模子是还是不是能够预测。您的模型会有错误的前瞻。您能够保留模型预测不得法的数字,也得以运用这几个示例扩充磨炼集。您也足以品味运用分歧的参数陶冶模型,也许采取完全两样的模子。

那只是二个概述,你能够尝试用Keras,并享受一些纵深学习的野趣,相同的时候获取部分实际的就学。小编在此间压缩了好些个音讯,所以请花点时间读书代码并驾驭它。您可以在Keras网站上询问不一样的Keras选项和APIs。至于HTML、CSS、JS和Flask,在英特网有大多可用的能源。