“ValueError:期望来自 tf.keras.Input() 的 KerasTensor”。使用 dropout 函数进行预测时出现错误

2024-02-10

我试图在测试期间使用 Dropout 来预测回归问题的不确定性亚林·加尔的文章 https://www.cs.ox.ac.uk/people/yarin.gal/website/blog_3d801aa532c1ce.html。我使用 Keras 的后端函数创建了一个类堆栈溢出问题的答案 https://stackoverflow.com/questions/43529931/how-to-calculate-prediction-uncertainty-using-keras。该类采用神经网络模型作为输入,并在测试过程中随机丢弃神经元,以给出随机估计,而不是时间序列预测的确定性输出。

我创建了一个简单的编码器-解码器模型,如下所示,用于在训练期间以 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() 的 KerasTensor 或来自 keras 层 call() 的输出。得到:0


激活Dropout在推理时,您只需指定training=True(TF>2.0) 在感兴趣的层中(在最后一个LSTM在你的情况下层)

with training=False

inp = Input(shape=(10, 1))
x = LSTM(1, dropout=0.3)(inp, training=False)
m = Model(inp,x)
# m.compile(...)
# m.fit(...)

X = np.random.uniform(0,1, (1,10,1))

output = []
for i in range(0,100):
    output.append(m.predict(X)) # always the same

with training=True

inp = Input(shape=(10, 1))
x = LSTM(1, dropout=0.3)(inp, training=True)
m = Model(inp,x)
# m.compile(...)
# m.fit(...)

X = np.random.uniform(0,1, (1,10,1))

output = []
for i in range(0,100):
    output.append(m.predict(X)) # always different

在您的示例中,这将变为:

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, training=True)
output = TimeDistributed(Dense(train_y.shape[2], activation='linear'))(decoder)

enc_dec_model = Model(input_sequence, output)
enc_dec_model.compile(
    loss="mean_squared_error",
    optimizer="adam",
    metrics=['mean_squared_error']
)

enc_dec_model.fit(train_x, train_y, epochs=10, batch_size=32)

and the KerasDropoutPrediction:

class KerasDropoutPrediction(object):
    def __init__(self, model):
        self.model = model
    def predict(self, X, n_iter=10):
        result = []
        for _ in range(n_iter):
            result.append(self.model.predict(X))
        result = np.array(result)
        return result

kdp = KerasDropoutPrediction(enc_dec_model)
y_pred_do = kdp.predict(test_x, n_iter=100)
y_pred_do_mean = y_pred_do.mean(axis=0)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

“ValueError:期望来自 tf.keras.Input() 的 KerasTensor”。使用 dropout 函数进行预测时出现错误 的相关文章

随机推荐