赞
踩
- from keras.layers.core import Activation, Dense
- model.add(Dense(64))
- model.add(Activation('tanh'))
- #等价于
- model.add(Dense(64, activation='tanh'))
也可以通过传递一个逐元素运算的Theano/TensorFlow函数来作为激活函数:
- 也可以通过传递一个逐元素运算的Theano/TensorFlow函数来作为激活函数:
- from keras import backend as K
- def tanh(x):
- return K.tanh(x)
- model.add(Dense(64, activation=tanh))
- model.add(Activation(tanh)
虽然我们称之为回调“函数”,但事实上Keras的回调函数是一个类,回调函数只是习惯性称呼
CallbackList
keras.callbacks.CallbackList(callbacks=[], queue_length=10)
Callback
keras.callbacks.Callback()
这是回调函数的抽象类,定义新的回调函数必须继承自该类
该回调函数在每个Keras模型中都会被自动调用
该回调函数用来将 metrics 指定的监视指标输出到标准输出上
该回调函数在Keras模型上会被自动调用, History 对象即为 fit 方法的返回值
这里是一个简单的保存每个batch的loss的回调函数:
- class LossHistory(keras.callbacks.Callback):
- def on_train_begin(self, logs={}):
- self.losses = []
- def on_batch_end(self, batch, logs={}):
- self.losses.append(logs.get('loss'))
-
- history = LossHistory()
- model.fit(X_train, Y_train, batch_size=128, nb_epoch=20, verbose=0, callbacks=[history])
- import keras.backend as K
- def mean_pred(y_true, y_pred):
- return K.mean(y_pred)
- def false_rates(y_true, y_pred):
- false_neg = ...
- false_pos = ...
- return {
- 'false_neg': false_neg,
- 'false_pos': false_pos,
- }
- model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy', mean_pred, false_rates])
传入可调用的对象,则该对象必须包含两个参数: shape (待初始化的变量的shape)和 name (该变量的名字),该可调用对象必须返回一个(Keras)变量,例如 K.variable() 返回的就是这种变量
- from keras import backend as K
- import numpy as np
- def my_init(shape, name=None):
- value = np.random.random(shape)
- return K.variable(value, name=name)
- model.add(Dense(64, init=my_init))
- from keras.applications.resnet50 import ResNet50
- from keras.preprocessing import image
- from keras.applications.resnet50 import preprocess_input, decode_predictions
- import numpy as np
- model = ResNet50(weights='imagenet')
- img_path = 'elephant.jpg'
- img = image.load_img(img_path, target_size=(224, 224))
- x = image.img_to_array(img)
- x = np.expand_dims(x, axis=0)
- x = preprocess_input(x)
- preds = model.predict(x)
- # decode the results into a list of tuples (class, description, probability)
- # (one such list for each sample in the batch)
- print('Predicted:', decode_predictions(preds, top=3)[0])
- # Predicted: [(u'n02504013', u'Indian_elephant', 0.82658225), (u'n01871265', u'tusker', 0.1122357),
- #(u'n02504458', u'African_elephant', 0.061040461)]

利用VGG16提取特征
- from keras.applications.vgg16 import VGG16
- from keras.preprocessing import image
- from keras.applications.vgg16 import preprocess_input
- import numpy as np
- model = VGG16(weights='imagenet', include_top=False)
- img_path = 'elephant.jpg'
- img = image.load_img(img_path, target_size=(224, 224))
- x = image.img_to_array(img)
- x = np.expand_dims(x, axis=0)
- x = preprocess_input(x)
- features = model.predict(x)
- from keras.datasets import cifar10
- (X_train, y_train), (X_test, y_test) = cifar10.load_data()
返回值:两个Tuple
- from keras.datasets import cifar100
- (X_train, y_train), (X_test, y_test) = cifar100.load_data(label_mode='fine')
label_mode:为‘fine’或‘coarse’之一,控制标签的精细度, ‘fine’获得的标签是100个小类的标签, ‘coarse’获得的
- from keras.datasets import imdb
- (X_train, y_train), (X_test, y_test) = imdb.load_data(path="imdb_full.pkl",
- nb_words=None,
- skip_top=0,
- maxlen=None,
- test_split=0.1)
- seed=113,
- start_char=1,
- oov_char=2,
- index_from=3)
- from keras.datasets import reuters
- (X_train, y_train), (X_test, y_test) = reuters.load_data(path="reuters.pkl",
- nb_words=None,
- skip_top=0,
- maxlen=None,
- test_split=0.2,
- seed=113,
- start_char=1,
- oov_char=2,
- index_from=3)
- from keras.datasets import mnist
- (X_train, y_train), (X_test, y_test) = mnist.load_data()
- from keras.utils.visualize_util import plot
- plot(model, to_file='model.png')
plot 接收两个可选参数:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。