gpt4 book ai didi

python - SparseTensor 与 tf.sparse_matmul 的矩阵乘法失败

转载 作者:行者123 更新时间:2023-11-30 22:33:39 26 4
gpt4 key购买 nike

为什么这不起作用:

pl_input = tf.sparse_placeholder('float32',shape=[None,30])
W = tf.Variable(tf.random_normal(shape=[30,1]), dtype='float32')
layer1a = tf.sparse_matmul(pl_input, weights, a_is_sparse=True, b_is_sparse=False)

错误信息是

TypeError: Failed to convert object of type <class 'tensorflow.python.framework.sparse_tensor.SparseTensor'> to Tensor. Contents: SparseTensor(indices=Tensor("Placeholder_11:0", shape=(?, ?), dtype=int64), values=Tensor("Placeholder_10:0", shape=(?,), dtype=float32), dense_shape=Tensor("Placeholder_9:0", shape=(?,), dtype=int64)). Consider casting elements to a supported type.

我希望创建一个 SparseTensorValue,从中检索批处理,然后将批处理输入到 pl_input 中。

最佳答案

TL;DR

使用tf.sparse_tensor_dense_matmul代替tf.sparse_matmul;看看documentation使用tf.nn.embedding_lookup_sparse作为替代方案。

关于稀疏矩阵和SparseTensors

该问题并非 sparse_placeholder 特有,而是由于 Tensorflow 术语的困惑造成的。

你有稀疏矩阵。然后你就有了SparseTensor。两者是相关但不同的概念。

  • SparseTensor 是一种对其值进行索引的结构,可以有效地表示稀疏矩阵或张量。
  • 稀疏矩阵是主要由 0 填充的矩阵。在tensorflow的文档中,它通常不是指代SparseTensor,而是指一个主要由0填充的普通旧Tensor

因此,查看函数参数的预期类型以找出答案非常重要。

例如,在 the documentation of tf.matmul 中,操作数必须是普通的 Tensor 而不是 SparseTensor,与 xxx_is_sparse 标志的值无关,这解释了您的错误。当这些标志为 True 时,tf.sparse_matmul 实际期望的是(密集)张量。换句话说,这些标志服务于 some optimization purposes而不是输入类型限制。 (顺便说一句,这些优化似乎只对 rather larger matrices 有用)。

关于python - SparseTensor 与 tf.sparse_matmul 的矩阵乘法失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45094041/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com