【问题标题】:ValueError: Data cardinality is ambiguous: x sizes: 10 y sizes: 1 Please provide data which shares the same first dimensionValueError:数据基数不明确:x 大小:10 y 大小:1 请提供具有相同第一个维度的数据
【发布时间】:2021-01-12 19:23:35
【问题描述】:

我正在尝试创建一个 Keras 模型。这是我的代码

init_data = np.array([1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0])
init_data = np.array(init_data,dtype="float").reshape(-1,1)

result_data = np.array([11.0])
result_data = np.array(result_data,dtype="float").reshape(-1,1)

stock_model = Sequential()
stock_model.add(LSTM(10, input_shape=(10,1), return_sequences=True))
stock_model.add(LSTM(5, activation="relu"))
return_sequences = True

stock_model.add(Dense(1))

sgd = SGD(lr=0.01)

stock_model.summary()
stock_model.compile(loss="mean_squared_error", optimizer=sgd, metrics=[tf.keras.metrics.mse])
stock_model.fit(init_data, result_data, epochs=100, verbose=1)

当我运行它时,我收到以下错误:

ValueError: Data cardinality is ambiguous:
  x sizes: 10
  y sizes: 1
Please provide data which shares the same first dimension.

我已经尝试了很多,但不幸的是还没有解决问题。我已经阅读了引用相同错误的其他问题,但我并不真正了解我需要更改什么。

【问题讨论】:

    标签: python tensorflow keras


    【解决方案1】:

    添加批次维度:

    init_data = np.array([1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0])
    init_data = np.array(init_data,dtype="float").reshape(1,-1,1) # <= add dimension here
    
    result_data = np.array([11.0])
    result_data = np.array(result_data,dtype="float").reshape(1,-1,1) # <= add dimension here
    

    编辑:

    对于二维数据:

    init_data = np.array([[1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0],[1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0]])
    init_data = init_data[..., tf.newaxis]
    

    【讨论】:

    • 谢谢!它如何与多维数组一起工作?
    • @mzwle 对不起,不明白你的问题。 TensorFlow 通常使用多维数组
    • 当我使用多维数组时,即np.array([[1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0],[1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0]]) 然后将stock_model.fit(...) 解释为一条记录,而不是两个或更多。
    • @mzwle fit() 会将其解释为两个序列
    • 这个警告是什么意思? WARNING:tensorflow:Model was constructed with shape (None, 10, 1) for input Tensor("lstm_input:0", shape=(None, 10, 1), dtype=float32), but it was called on an input with incompatible shape (None, 20, 1).
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    • 2022-10-07
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    • 2021-09-10
    • 1970-01-01
    相关资源
    最近更新 更多