【问题标题】:ValueError: Data cardinality is ambiguous. Please provide data which shares the same first dimensionValueError:数据基数不明确。请提供具有相同第一维的数据
【发布时间】:2020-07-17 10:00:53
【问题描述】:

我正在尝试创建具有多个输入分支的 keras 模型,但 keras 不喜欢输入具有不同的大小。

这是一个最小的例子:

import numpy as np

from tensorflow import keras
from tensorflow.keras import layers


inputA = layers.Input(shape=(2,))
xA = layers.Dense(8, activation='relu')(inputA)

inputB = layers.Input(shape=(3,))
xB = layers.Dense(8, activation='relu')(inputB)

merged = layers.Concatenate()([xA, xB])

output = layers.Dense(8, activation='linear')(merged)    

model = keras.Model(inputs=[inputA, inputB], outputs=output)


a = np.array([1, 2])
b = np.array([3, 4, 5])    

model.predict([a, b])

这会导致错误:

ValueError: Data cardinality is ambiguous:
  x sizes: 2, 3
Please provide data which shares the same first dimension.

在 keras 中有没有更好的方法来做到这一点?我已经阅读了引用相同错误的其他问题,但我并不真正了解我需要更改什么。

【问题讨论】:

    标签: python tensorflow machine-learning keras


    【解决方案1】:

    您需要以正确的格式传递数组...(n_batch,n_feat)。一个简单的重塑就足以创建批量维度

    import numpy as np
    from tensorflow import keras
    from tensorflow.keras import layers
    
    
    inputA = layers.Input(shape=(2,))
    xA = layers.Dense(8, activation='relu')(inputA)
    
    inputB = layers.Input(shape=(3,))
    xB = layers.Dense(8, activation='relu')(inputB)
    
    merged = layers.Concatenate()([xA, xB])
    
    output = layers.Dense(8, activation='linear')(merged)    
    
    model = keras.Model(inputs=[inputA, inputB], outputs=output)
    
    
    a = np.array([1, 2]).reshape(1,-1)
    b = np.array([3, 4, 5]).reshape(1,-1)
    
    model.predict([a, b])
    

    【讨论】:

    • 呃。一大早就没有 keras 了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    • 2023-03-23
    • 2021-12-20
    • 2021-06-29
    相关资源
    最近更新 更多