张量流keras模型的动态历元数

时间:2018-07-19 13:40:43

标签: python tensorflow keras

我希望有一个神经网络进行训练,直到达到一定的准确性为止。是否有内置功能可以使用,而不是单独运行每个时期直到达到精度?

model = keras.Sequential([
    keras.layers.Flatten(input_shape=(28, 28)),
    keras.layers.Dense(128, activation=tf.nn.relu),
    keras.layers.Dense(128, activation=tf.nn.relu),
    keras.layers.Dense(128, activation=tf.nn.relu),
    keras.layers.Dense(128, activation=tf.nn.relu),
    keras.layers.Dense(10, activation=tf.nn.softmax)
])

model.compile(optimizer=tf.train.AdamOptimizer(), loss='sparse_categorical_crossentropy', metrics=['accuracy'])

epochs = 0
train_acc = 0
while 1-train_acc > .01:
    model.fit(train_images, train_labels,  initial_epoch=epochs, epochs=epochs+1,verbose=0)
    epochs += 1
    train_loss, train_acc = model.evaluate(train_images,train_labels)

1 个答案:

答案 0 :(得分:3)

不,没有任何内置函数可以执行此操作。但是,您可以轻松定义一个自定义回调,一旦训练准确性达到某个阈值,该回调就会停止训练:

import keras


class AccuracyStopping(keras.callbacks.Callback):
    def __init__(self, acc_threshold):
        super(AccuracyStopping, self).__init__()
        self._acc_threshold = acc_threshold

    def on_epoch_end(self, batch, logs={}):
        train_acc = logs.get('acc')
        self.model.stop_training = 1 - train_acc <= self._acc_threshold

这是一个简单的示例,展示了如何使用它:

import numpy as np
from keras.layers import Dense
from keras.models import Sequential

x = np.random.normal(size=(100,))
y = x > 0

model = Sequential()
model.add(Dense(1, input_dim=1, activation='sigmoid'))
model.compile('sgd', 'binary_crossentropy', metrics=['accuracy'])

acc_callback = AccuracyStopping(0.05)
model.fit(x, y, batch_size=8, epochs=1000, callbacks=[acc_callback])