【发布时间】:2022-04-05 19:37:01
【问题描述】:
我正在尝试根据Yarin Gal's article 在测试期间使用 Dropout 预测回归问题中的不确定性。我使用 stack overflow question's answer 提供的 Keras 的后端函数创建了一个类。该类将 NN 模型作为输入,并在测试期间随机丢弃神经元,以提供随机估计而不是确定性输出以进行时间序列预测。
我创建了一个简单的编码器-解码器模型,如下所示,用于在训练期间进行 0.1 dropout 的预测:
input_sequence = Input(shape=(lookback, train_x.shape[2]))
encoder = LSTM(128, return_sequences=False)(input_sequence)
r_vec = RepeatVector(forward_pred)(encoder)
decoder = LSTM(128, return_sequences=True, dropout=0.1)(r_vec) #maybe use dropout=0.1
output = TimeDistributed(Dense(train_y.shape[2], activation='linear'))(decoder)
# optimiser = optimizers.Adam(clipnorm=1)
enc_dec_model = Model(input_sequence, output)
enc_dec_model.compile(loss="mean_squared_error",
optimizer="adam",
metrics=['mean_squared_error'])
enc_dec_model.summary()
之后,我定义并调用 DropoutPrediction 类。
# Define the class:
class KerasDropoutPrediction(object):
def __init__(self ,model):
self.f = K.function(
[model.layers[0].input,
K.learning_phase()],
[model.layers[-1].output])
def predict(self ,x, n_iter=10):
result = []
for _ in range(n_iter):
result.append(self.f([x , 1]))
result = np.array(result).reshape(n_iter ,x.shape[0] ,x.shape[1]).T
return result
# Call the object:
kdp = KerasDropoutPrediction(enc_dec_model)
y_pred_do = kdp.predict(x_test,n_iter=100)
y_pred_do_mean = y_pred_do.mean(axis=1)
然而,在这条线上
kdp = KerasDropoutPrediction(enc_dec_model),当我调用 LSTM 模型时,
我收到以下错误消息,说明输入必须是 Keras 张量。谁能帮我解决这个错误?
错误信息:
ValueError:在处理 keras 函数模型的输入张量时发现意外实例。期待来自 tf.keras.Input() 或来自 keras 层 call() 的输出的 KerasTensor。得到:0
【问题讨论】:
标签: tensorflow keras lstm keras-layer dropout