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

问题描述 投票:0回答:1

我正在尝试根据Yarin Gal 的文章在测试期间使用 Dropout 来预测回归问题的不确定性。我使用 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() 的 KerasTensor 或来自 keras 层 call() 的输出。得到:0

tensorflow keras lstm keras-layer dropout
1个回答
4
投票

要在推理时激活

Dropout
,您只需在感兴趣的层中指定
training=True
(TF>2.0)(在您的案例中的最后
LSTM
层)

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

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)

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)
© www.soinside.com 2019 - 2024. All rights reserved.