ML——keras

keras官网:https://keras.io/api/models/

参考:https://www.cnblogs.com/zb-ml/p/12704637.html

   http://www.manongjc.com/article/92196.html

创建keras 模型有三种方法:Sequential model、Functional API、Model subclassing  (初学者常用Sequential model)

There are three ways to create Keras models:

  • The Sequential model, which is very straightforward (a simple list of layers), but is limited to single-input, single-output stacks of layers (as the name gives away).
  • The Functional API, which is an easy-to-use, fully-featured API that supports arbitrary model architectures. For most people and most use cases, this is what you should be using. This is the Keras "industry strength" model.
  • Model subclassing, where you implement everything from scratch on your own. Use this if you have complex, out-of-the-box research use cases.

1、下载mnist数据集   

load_data function

tf.keras.datasets.mnist.load_data(path="mnist.npz")

returns(返回)

Tuple of Numpy arrays: (x_train, y_train), (x_test, y_test).  以元组的形式返回

x_train, x_test: uint8 arrays of grayscale image data with shapes (num_samples, 28, 28).

y_train, y_test: uint8 arrays of digit labels (integers in range 0-9) with shapes (num_samples,).

 

np_utils.to_categorical用于将标签转化为形如(nb_samples, nb_classes)的二值序列。

比如:

y_train = np_utils.to_categorical(y_train,10)
假设num_classes = 10。
如将[1,2,3,……4]转化成:
[[0,1,0,0,0,0,0,0]
[0,0,1,0,0,0,0,0]
[0,0,0,1,0,0,0,0]
……
[0,0,0,0,1,0,0,0]]
这样的形态。

 

Conv2D函数的用法:

 

tf.keras.layers.Conv2D(
    filters,
    kernel_size,
    strides=(1, 1),
    padding="valid",
    data_format=None,
    dilation_rate=(1, 1),
    activation=None,
    use_bias=True,
    kernel_initializer="glorot_uniform",
    bias_initializer="zeros",
    kernel_regularizer=None,
    bias_regularizer=None,
    activity_regularizer=None,
    kernel_constraint=None,
    bias_constraint=None,
    **kwargs
)

padding(填充 0):有“valid”“same”

  • 首先考虑VALID,这个意思就是说,程序按照指定的滤波器和步长进行滑动卷积,当出现剩余的像素值不够滤波器进行一次卷积时,就舍弃剩余所有像素。如下图所示:

如图所示输入像是1*10*10*1,filter大小是3*3*1*1,步长strides=[1,3,3,1],根据公式(10-3)/3=3,所以最终图像大小是3*3*1,操作中去掉了最右边和最下边一行像素,因为它不够3*3滤波器进行一次卷积。

总结:padding为VALID模式时,很简单粗暴直接从原始图像的首段开始卷积,到最后不能匹配卷积核的部分直接舍去。

  • 当padding=SAME时,处理方式与VALID有所不同,对于一个维度不够像素时,会进行填充0处理。至于如何填充,有两种情况。

情况一:相差偶数个元素时,比如一个10*10的图像使用3*3滤波器,以步长为3进行卷积,到了最后还剩1行(列)元素,也就是说还差2行元素,系统默认在整个图像的前后(左右)填充0;如果相差4个元素,就前后各加2个元素。已达到平均的目的。

最终输出4*4大小的图像(根据公式(10-3+2*2)/3+1=4)。

情况二:相差奇数个元素,比如一个11*11的图像使用3*3滤波器,以步长为3进行卷积,到了最后还剩2行(列)元素,也就是说还差1行元素,系统会在整个图像的前面(左边)填充0;如果相差3个元素,就前面加2个0元素,后面加1个0元素。

(输入图像是11*11,还相差1个元素,加在维度的前面(第一行,第一列),最终得到的还是4*4大小的图像。根据公式(10-3+2*1)/3+1=4)

总结:当padding为SAME时,系统会对图形进行填充0处理,不会舍弃任何一个元素。当相差偶数个元素时,在图像每一维的前面和后边添加各一般的0填充;当相差奇数个元素时,总是保持前面比后面多填充一个0元素

 

 

 

后续补充。。。。。

 

posted @ 2020-05-31 19:14  cfancy  阅读(145)  评论(0编辑  收藏  举报