keras api(最近更新:2019/10/23)

一、关于keras

Keras 是一个用 Python 编写的高级神经网络 API,它能够以 TensorFlow, CNTK, 或者 Theano 作为后端运行。Keras 的开发重点是支持快速的实验。能够以最小的时延把你的想法转换为实验结果,是做好研究的关键。
在tensorflow中调用keras:tf.keras

二、.models

.Sequential()

2.1 方法

  1. .add():堆叠模型
  2. .compile(loss='categorical_crossentropy',optimizer='sgd',metrics=['accuracy']):配置

loss:损失函数,可以调用.losses中的方法,也可以简写。
optimizer:优化器,可以调用.optimizers中的方法,也可以简写。
metrics:评价指标,

.fit(x_train, y_train, epochs=5, batch_size=32)
.train_on_batch(x_batch, y_batch)
loss_and_metrics = model.evaluate(x_test, y_test, batch_size=128)
classes = model.predict(x_test, batch_size=128)

from keras.utils.np_utils import to_categorical

三、.layers

一些常见的层的api

  1. .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):2D卷积层

filters: 整数,过滤器个数,也是输出的维数。
kernel_size: 单个整数(两个数相同的略写)或两个整数组成的元组或列表,来指定卷积窗口的大小。
input_shape:当该层作为第一层时要加入输入维度,如input_shape=(28,28,3)
strides: 指定卷积步幅,同样可以用一个整数代替。
padding: 和tensorflow中一样,valid表示不加边,same表示加边到卷积后大小相同。
data_format: A string, one of “channels_last” or “channels_first”. The ordering of the dimensions in the inputs. “channels_last” corresponds to inputs with shape (batch, height, width, channels) while “channels_first” corresponds to inputs with shape (batch, channels, height, width). It defaults to the image_data_format value found in your Keras config file at ~/.keras/keras.json. If you never set it, then it will be “channels_last”.
dilation_rate: an integer or tuple/list of 2 integers, specifying the dilation rate to use for dilated convolution. Can be a single integer to specify the same value for all spatial dimensions. Currently, specifying any dilation_rate value != 1 is incompatible with specifying any stride value != 1.
activation: 见.activations章。
use_bias: Boolean, whether the layer uses a bias vector.
kernel_initializer: Initializer for the kernel weights matrix (see initializers).
bias_initializer: Initializer for the bias vector (see initializers).
kernel_regularizer: Regularizer function applied to the kernel weights matrix (see regularizer).
bias_regularizer: Regularizer function applied to the bias vector (see regularizer).
activity_regularizer: Regularizer function applied to the output of the layer (its “activation”). (see regularizer).
kernel_constraint: Constraint function applied to the kernel matrix (see constraints).
bias_constraint: Constraint function applied to the bias vector (see constraints).

  1. .MaxPooling2D(pool_size=(2, 2), strides=None, padding='valid', data_format=None)

pool_size:指定池化窗口大小,如(2,2),也可以只用一个2表示(2,2)
data_format: A string, one of channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch, height, width, channels) while channels_first corresponds to inputs with shape (batch, channels, height, width). It defaults to the image_data_format value found in your Keras config file at ~/.keras/keras.json. If you never set it, then it will be “channels_last”.

  1. .Dropout(rate, noise_shape=None, seed=None)

rate:即删除比率。

  1. .Flatten(data_format=None):铺平数据层
  2. .Dense(units, 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):全连接层

units:神经元个数。

四、.losses

.categorical_crossentropy

五、.optimizers

.SGD(lr=0.01, momentum=0.9, nesterov=True)

六、一些工具

.utils.to_categorical(y, num_classes=None, dtype='float32'):热编码

七、.activations

激活函数

  1. .relu(x, alpha=0.0, max_value=None, threshold=0.0)
  2. .tanh(x)
  3. .sigmoid(x)
  4. .linear(x):缺省时采用这个。
  5. .softmax(x, axis=-1)

八、.metrics

  1. .accuracy(y_true, y_pred)

九、.callbacks

  1. .ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=10, verbose=0, mode='auto', min_delta=0.0001, cooldown=0, min_lr=0)
    例如:
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2,
                              patience=5, min_lr=0.001)
model.fit(X_train, Y_train, callbacks=[reduce_lr])

十、.preprocessing

10.1 .image

  1. .ImageDataGenerator(featurewise_center=False, samplewise_center=False, featurewise_std_normalization=False, samplewise_std_normalization=False, zca_whitening=False, zca_epsilon=1e-06, rotation_range=0, width_shift_range=0.0, height_shift_range=0.0, brightness_range=None, shear_range=0.0, zoom_range=0.0, channel_shift_range=0.0, fill_mode='nearest', cval=0.0, horizontal_flip=False, vertical_flip=False, rescale=None, preprocessing_function=None, data_format='channels_last', validation_split=0.0, interpolation_order=1, dtype='float32')
发布了60 篇原创文章 · 获赞 32 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_42297855/article/details/102509049
今日推荐