You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

构建仅执行点积的Keras模型:ValueError修复与可行性验证

问题描述

尝试编写TensorFlow/Keras代码构建仅对输入执行点积的模型,原代码如下:

from tensorflow.keras.models import Model
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
import tensorflow as tf
import numpy as np

x = np.array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1]).reshape(1, 10)
y = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]).reshape(1, 10)

x1 = [x for j in range(30)]
x2 = [y for j in range(30)]
y1 = [np.array([55]).reshape(1, 1) for j in range(30)]

input1 = Input(shape=(10,))
input2 = Input(shape=(10,))
dotted = Dot(axes=(1))([input1, input2])

model = Model(inputs = [input1, input2], outputs = [dotted])

model.compile(optimizer='rmsprop', loss='sparse_categorical_crossentropy')

history = model.fit(x=[x1, x2], y=np.array(y1))

运行时抛出如下ValueError:

ValueError: Data cardinality is ambiguous:
  x sizes: 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  y sizes: 30
Make sure all arrays contain the same number of samples.

咨询两个问题:

  1. 修复该ValueError后,该模型能否正常运行?
  2. 如何修复此ValueError?

解答

1. 修复ValueError后模型能否正常运行?

修复数据维度问题后,还需要调整损失函数才能让模型正常运行。原代码用了sparse_categorical_crossentropy——这个损失是为多分类任务设计的,但点积的输出是连续数值(这里是55),属于回归任务,得换成回归类损失比如mse(均方误差)。另外原代码漏导入了Input和Dot层,补上这两处后,模型就能正常运行并拟合点积结果。

2. 如何修复ValueError?

这个错误是数据维度不匹配导致的:你构建的x1和x2是包含30个形状为(1,10)的数组的列表,Keras会把每个小数组当成1个独立样本,导致输入的总样本数变成60个,而标签y1合并后只有30个样本,两者数量不匹配。

具体修复步骤

步骤1:修正数据维度

把列表形式的输入数据合并成单个numpy数组,让输入和标签的样本数统一为30:

# 用repeat快速生成重复的样本,结果形状为(30,10)
x1 = np.repeat(x, 30, axis=0)
x2 = np.repeat(y, 30, axis=0)
# 生成形状为(30,1)的标签数组
y1 = np.full((30,1), 55)

步骤2:补全缺失的层导入

原代码没导入Input和Dot层,需要补上:

from tensorflow.keras.layers import Input, Dot

步骤3:更换合适的损失函数

把分类损失换成回归损失:

model.compile(optimizer='rmsprop', loss='mse')

完整修复后的代码

from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Dot
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
import tensorflow as tf
import numpy as np

x = np.array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1]).reshape(1, 10)
y = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]).reshape(1, 10)

# 修正数据维度
x1 = np.repeat(x, 30, axis=0)
x2 = np.repeat(y, 30, axis=0)
y1 = np.full((30,1), 55)

input1 = Input(shape=(10,))
input2 = Input(shape=(10,))
dotted = Dot(axes=(1))([input1, input2])

model = Model(inputs = [input1, input2], outputs = [dotted])

# 使用回归损失函数
model.compile(optimizer='rmsprop', loss='mse')

history = model.fit(x=[x1, x2], y=y1)

内容的提问来源于stack exchange,提问作者adover

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 16:48:58