Tensorflow.js:op最大值的梯度错误。输入“$a”的渐变具有形状“32200”,与输入“32,1”的形状不匹配
我构建了一个非常简单的Tensorflow操作,一切似乎都有意义,但当我调用fit函数时,模型无法反向传播梯度,并显示上述错误消息:Tensorflow.js:op最大值的梯度错误。输入“$a”的渐变具有形状“32200”,与输入“32,1”的形状不匹配,tensorflow,tensorflow.js,Tensorflow,Tensorflow.js,我构建了一个非常简单的Tensorflow操作,一切似乎都有意义,但当我调用fit函数时,模型无法反向传播梯度,并显示上述错误消息: Error in gradient for op maximum. The gradient of input '$a' has shape '32,200', which does not match the shape of the input '32,1' 以下是xTrain和yTrain的类型 以下是模型的预期输入和输出: model.input
Error in gradient for op maximum.
The gradient of input '$a' has shape '32,200',
which does not match the shape of the input '32,1'
以下是xTrain和yTrain的类型
以下是模型的预期输入和输出:
model.input
Array(3) [null, 20, 73]
float32
model.outputs[0]
Array(2) [null, 200]
float32
[编辑]我应该注意,我的问题只发生在我尝试使用
loss: 'cosineProximity'
这是我的密码:
console.log启动计算和保存模型;
常数模型=tf.sequential;
model.addtf.layers.simpleRN{
单位:嵌入的长度单位,//嵌入单位的数量单位,
递归初始化程序:“glorotNormal”,
inputShape:[最大长度,已识别字母.长度],
返回顺序:false,
};
console.logmodel.input.shape;
console.logmodel.input.dtype;
console.logmodel.outputs[0].shape;
console.logmodel.outputs[0].dtype;
console.logmodel.batchInputShape;
model.compile{
损失:“余邻性”,
优化器:“亚当”,
指标:['acc']
};
console.logstart compute_和_save_model fit
等待模型。fitxTrain,yTrain{
时代:2,
批量大小:32,
验证片段:0.2,
回调:{
onBatchBeginb{
console.logstarting compute_和_save_model fit:+b+;
}
}
};
可从
有人知道这里可能出了什么问题吗
编辑:我试图创建自己的cosineProximity实现,但得到了相同的错误。以下是我对余邻性的实施,以供参考:
const cosine=tf.layers.dot{axes:-1,normalize:true}
损失:功能A,b{
返回tf.negtf.meancosine.apply[a,b];
},
我花了一些时间在这上面,看起来这是Tensforflow.js实现中的一个错误 如果您面临同样的问题,您可以通过自己应用下面的补丁来修复它。我相信tfjs层维护人员最终会合并这个请求,所以希望您以后不会再遇到这个问题
我不知道到底什么是主要问题,但我通过用“meanSquaredError”损失替换“Cosinessilarity”损失,成功地运行了模型。我仍然有兴趣理解为什么cosinistality loss不起作用,以及我需要做些什么来让它起作用。你能添加更多关于你的模型、标签和特征形状的代码吗?@edkevek当然,除了有什么,你还希望有什么?据我所知,除了我粘贴的代码以及我在上文中已经描述过的张量xTrain和yTrain之外,没有什么比这更重要的了。你能用stackblitz.com做一个片段来抛出同样的错误吗?@edkeveked拉取请求现在已经合并了。
loss: 'cosineProximity'
| export function l2Normalize(x: Tensor, axis?: number): Tensor {
| return tidy(() => {
| const squareSum = tfc.sum(K.square(x), axis, true);
- const epsilonTensor = tfc.mul(scalar(epsilon()), tfc.onesLike(x));
+ const epsilonTensor = tfc.mul(scalar(epsilon()), tfc.onesLike(squareSum));
| const norm = tfc.sqrt(tfc.maximum(squareSum, epsilonTensor));
| return tfc.div(x, norm);
| });
| }