在 Keras 中编辑模型时出错 - ValueError:函数的输入张量必须来自 `tf.keras.Input`

问题描述

我正在尝试使用 Keras 为神经网络生成预测区间。我找到了这个代码并想复制它:https://medium.com/hal24k-techblog/how-to-generate-neural-network-confidence-intervals-with-keras-e4c0b78ebbdf

这是我需要从中提取预测区间的模型:

model = Sequential()
model.add(LSTM(1,batch_input_shape=(1,x_train.shape[1],x_train.shape[2]),dropout=0.5,stateful=True))
model.add(Dropout(rate=0.5))
model.add(Dense(1))
model.compile(loss='mean_squared_error',optimizer='adam')

model.fit(x_train,y_train,epochs=10,batch_size=1,verbose=1)

这是我需要应用到之前模型的函数

def create_dropout_predict_function(model,dropout):
    """
    Create a keras function to predict with dropout
    model : keras model
    dropout : fraction dropout to apply to all layers
    
    Returns
    predict_with_dropout : keras function for predicting with dropout
    """
    
    # Load the config of the original model
    conf = model.get_config()
    # Add the specified dropout to all layers
    for layer in conf['layers']:
        # Dropout layers
        if layer["class_name"]=="Dropout":
            layer["config"]["rate"] = dropout
        # Recurrent layers with dropout
        elif "dropout" in layer["config"].keys():
            layer["config"]["dropout"] = dropout

    # Create a new model with specified dropout
    if type(model)==Sequential:
        # Sequential
        model_dropout = Sequential.from_config(conf)
    else:
        # Functional
        model_dropout = Model.from_config(conf)
    model_dropout.set_weights(model.get_weights()) 
    
    # Create a function to predict with the dropout on
    predict_with_dropout = K.function(model_dropout.inputs+[K.learning_phase()],model_dropout.outputs)
    
    return predict_with_dropout

后执行这个循环:

dropout = 0.5
num_iter = 20
num_samples = input_data[0].shape[0]

predict_with_dropout = create_dropout_predict_function(model,dropout)

predictions = np.zeros((num_samples,num_iter))
for i in range(num_iter):
    predictions[:,i] = predict_with_dropout(input_data+[1])[0].reshape(-1)

但是,出现以下错误

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-40-000a60ea05b8> in <module>()
      6 model = load_model(path_to_model)
      7 
----> 8 predict_with_dropout = create_dropout_predict_function(model,dropout)
      9 
     10 predictions = np.zeros((num_samples,num_iter))

6 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/functional.py in _validate_graph_inputs_and_outputs(self)
    689                          'must come from `tf.keras.Input`. '
    690                          'Received: ' + str(x) +
--> 691                          ' (missing prevIoUs layer Metadata).')
    692       # Check that x is an input tensor.
    693       # pylint: disable=protected-access

ValueError:函数的输入张量必须来自 tf.keras.Input。收到:0(缺少前一层元数据)。

可能是输入的数据不正确,有人可以帮帮我吗?

训练数据形状:numpy.array (824,30,10)

训练目标数据:numpy.array(824,1)

验证数据形状:numpy.array (391,10)

验证目标数据:numpy.array (391,1)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)