我正在尝试在Keras中实现全梯度下降。这意味着在每个epoch中,我都在整个数据集上进行训练。这就是为什么批次大小被定义为训练集的长度大小。
from keras.models import Sequentialfrom keras.layers import Densefrom keras.optimizers import SGD,Adamfrom keras import regularizersimport numpy as npimport matplotlib.pyplot as plt%matplotlib inline import randomfrom numpy.random import seedimport randomdef xrange(start_point,end_point,N,base): temp = np.logspace(0.1, 1, N,base=base,endpoint=False) temp=temp-temp.min() temp=(0.0+temp)/(0.0+temp.max()) #this is between 0 and 1 return (end_point-start_point)*temp +start_point #this is the rangedef train_model(x_train,y_train,x_test): #seed(1) model=Sequential() num_units=100 act='relu' model.add(Dense(num_units,input_shape=(1,),activation=act)) model.add(Dense(num_units,activation=act)) model.add(Dense(num_units,activation=act)) model.add(Dense(num_units,activation=act)) model.add(Dense(1,activation='tanh')) #output layer 1 unit ; activation='tanh' model.compile(Adam(),'mean_squared_error',metrics=['mse']) history=model.fit(x_train,y_train,batch_size=len(x_train),epochs=500,verbose=0,validation_split = 0.2 ) #train on the noise (not moshe) fit=model.predict(x_test) loss = history.history['loss'] val_loss = history.history['val_loss'] return fitN = 1024start_point=-5.25end_point=5.25base=500# the base of the log of the trainningtrain_step=0.0007x_test=np.arange(start_point,end_point,train_step+0.05)x_train=xrange(start_point,end_point,N,base)#random.shuffle(x_train)function_y=np.sin(3*x_train)/2noise=np.random.uniform(-0.2,0.2,len(function_y))y_train=function_y+noisefit=train_model(x_train,y_train,x_test)plt.scatter(x_train,y_train, facecolors='none', edgecolors='g') #plt.plot(x_value,sample,'bo')plt.scatter(x_test, fit, facecolors='none', edgecolors='b') #plt.plot(x_value,sample,'bo')
然而,当我取消注释#random.shuffle(x_train) – 以便打乱训练数据时。 :
我不明白为什么我得到不同的图表(绿色圆圈是训练数据,蓝色圆圈是模型学习的结果)。在两种情况下,批次都是整个数据集。所以打乱数据不应该改变任何事情。
谢谢你。
Ariel
回答:
出现这种情况有两个原因:
- 首先,当数据未被打乱时,训练/验证数据的分割是不合适的。
- 其次,全梯度下降在每个epoch中只进行一次更新,因此可能需要更多的训练epoch才能收敛。
为什么你的模型不匹配波形?
根据model.fit的说明:
- validation_split:介于0和1之间的浮点数。用作验证数据的训练数据的比例。模型将分离出这部分训练数据,不在其上进行训练,并在每个epoch结束时评估该数据上的损失和任何模型指标。验证数据是从提供的x和y数据的最后几个样本中选取的,在打乱之前。
这意味着你的验证集由最后20%的训练样本组成。因为你对自变量(x_train
)使用了对数刻度,结果你的训练/验证分割是这样的:
split_point = int(0.2*N)x_val = x_train[-split_point:]y_val = y_train[-split_point:]x_train_ = x_train[:-split_point]y_train_ = y_train[:-split_point]plt.scatter(x_train_, y_train_, c='g')plt.scatter(x_val, y_val, c='r')plt.show()
在前面的图表中,训练数据和验证数据分别用绿色和红色点表示。请注意,你的训练数据集并不代表整个总体。
为什么它仍然不匹配训练数据集?
除了不合适的训练/测试分割外,全梯度下降可能需要更多的训练epoch才能收敛(梯度噪声较少,但它在每个epoch中只进行一次梯度更新)。如果你改为训练你的模型约1500个epoch(或者使用小批量梯度下降,批次大小为32),你最终会得到: