我正在使用keras
库在python
中拟合一个递归神经网络。我通过改变epoch
函数中的参数nb_epoch
来拟合不同的epoch
个数。目前我正在使用for
循环,每次我改变nb_epoch
时都会重新拟合,这是一个大量重复的工作。下面是我的代码(如果您想跳过代码详细信息的其他部分,则循环位于代码底部):
from __future__ import division
import numpy as np
import pandas
from keras.models import Sequential
from keras.layers.core import Dense, Activation, Dropout
from keras.layers.recurrent import LSTM
from sklearn.preprocessing import MinMaxScaler
from sklearn.learning_curve import learning_curve
####################################
###
### Here I do the data processing to create trainX, testX
###
####################################
#model create:
model = Sequential()
#this is the epoch array for different nb_epoch
####################################
###
### Here I define model architecture
###
####################################
model.compile(loss="mse", optimizer="rmsprop")
#################################################
#### Defining arrays for different epoch number
#################################################
epoch_array = range(100, 2100,100)
# I create the following arrays/matrices to store the result of NN fit
# different epoch number.
train_DBN_fitted_Y = np.zeros(shape=(len(epoch_array),trainX.shape[0]))
test_DBN_fitted_Y = np.zeros(shape=(len(epoch_array),testX.shape[0]))
###############################################
###
### Following loop is the heart of the question
###
##############################################
i = 0
for epoch in epoch_array:
model.fit( trainX, trainY,
batch_size = 16, nb_epoch = epoch, validation_split = 0.05, verbose = 2)
trainPredict = model.predict(trainX)
testPredict = model.predict(testX)
trainPredict = trainPredict.reshape(trainPredict.shape[0])
testPredict = testPredict.reshape(testPredict.shape[0])
train_DBN_fitted_Y[i] = trainPredict
test_DBN_fitted_Y[i] = testPredict
i = i + 1
现在这个循环效率很低。因为例如,当它设置为nb_epoch
=100时,它从epoch = 1
开始训练,到epoch = 100
结束,如下所示:
在循环的下一个迭代中,它说nb_epoch = 200
,它再次从epoch = 1
开始训练,并在epoch = 200
结束。但我想做的是,在这个迭代中,从循环的最后一次迭代中的地方开始训练,即epoch = 100
,然后epoch = 101
等等。。。。在
如何修改此循环以实现此目的?在
您可以使用fit的
initial_epoch
参数(请参见docs)连续调用
fit
是在进一步训练模型,从上一次调用留下的状态开始。要使它不继续,它必须重置模型的权重,fit
不会这样做。你只是没有看到它这样做,因为它总是从1开始计算时代。在所以最终问题是它没有打印出正确的纪元数(你不能改变)。在
如果这让您感到困扰,您可以通过定期调用^{} 来实现自己的
fit
。在相关问题 更多 >
编程相关推荐