我正在尝试将我的 Keras 神经网络包装在一个class对象中。我已经在类设置之外实现了以下内容,但我想让它更加对象友好。总而言之,我的model调用函数sequential_model创建了一个sequential模型。在这compile一步中,我定义了自己的损失函数weighted_categorical_crossentropy,我希望顺序模型实现它。但是,当我运行下面的代码时,出现以下错误:ValueError: No gradients provided for any variable:
我怀疑问题在于我如何定义该weighted_categorical_crossentropy函数以供sequential.
再次,我能够以非面向对象的方式完成这项工作。任何帮助都感激不尽。
from tensorflow.keras import Sequential, backend as K
class MyNetwork():
def __init__(self, file, n_output=4, n_hidden=20, epochs=3,
dropout=0.10, batch_size=64, metrics = ['categorical_accuracy'],
optimizer = 'rmsprop', activation = 'softmax'):
[...] //Other Class attributes
def model(self):
self.model = self.sequential_model(False)
self.model.summary()
def sequential_model(self, val):
K.clear_session()
if val == False:
self.epochs = 3
regressor = Sequential()
#regressor.run_eagerly = True
regressor.add(LSTM(units = self.n_hidden, dropout=self.dropout, return_sequences = True, input_shape = (self.X.shape[1], self.X.shape[2])))
regressor.add(LSTM(units = self.n_hidden, dropout=self.dropout, return_sequences = True))
regressor.add(Dense(units = self.n_output, activation=self.activation))
self.weights = np.array([0.025,0.225,0.78,0.020])
regressor.compile(optimizer = self.optimizer, loss = self.weighted_categorical_crossentropy(self.weights), metrics = [self.metrics])
regressor.fit(self.X, self.Y*1.0,batch_size=self.batch_size, epochs=self.epochs, verbose=1, validation_data=(self.Xval, self.Yval*1.0))
return regressor
白衣染霜花
相关分类