不能用张量流做矩阵乘法 [英] Can't do matrix multiplication with tensorflow
本文介绍了不能用张量流做矩阵乘法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Tensorflow 中,我想使用以下代码进行矩阵乘法:
In Tensorflow, I would like to do matrix multiplication using this code:
_X = np.array([[1, 2, 3], [4, 5, 6]])
_Y = np.array([[1, 1], [2, 2], [3, 3]])
X = tf.convert_to_tensor(_X)
Y = tf.convert_to_tensor(_Y)
res = tf.matmul(X, Y)
但是,我收到此错误:
TypeError Traceback (most recent call last)
<ipython-input-29-37c04c70cff8> in <module>()
4 Y = tf.convert_to_tensor(_Y)
5
----> 6 res = tf.matmul(X, Y)
/Downloads/tensorflow-exercises-master/lib/python3.5/site-packages/tensorflow/python/ops/math_ops.py in matmul(a, b, transpose_a, transpose_b, adjoint_a, adjoint_b, a_is_sparse, b_is_sparse, name)
1799 else:
1800 return gen_math_ops._mat_mul(
-> 1801 a, b, transpose_a=transpose_a, transpose_b=transpose_b, name=name)
1802
1803
/Downloads/tensorflow-exercises-master/lib/python3.5/site-packages/tensorflow/python/ops/gen_math_ops.py in _mat_mul(a, b, transpose_a, transpose_b, name)
1261 """
1262 result = _op_def_lib.apply_op("MatMul", a=a, b=b, transpose_a=transpose_a,
-> 1263 transpose_b=transpose_b, name=name)
1264 return result
1265
/Downloads/tensorflow-exercises-master/lib/python3.5/site-packages/tensorflow/python/framework/op_def_library.py in apply_op(self, op_type_name, name, **keywords)
588 _SatisfiesTypeConstraint(base_type,
589 _Attr(op_def, input_arg.type_attr),
--> 590 param_name=input_name)
591 attrs[input_arg.type_attr] = attr_value
592 inferred_from[input_arg.type_attr] = input_name
/Downloads/tensorflow-exercises-master/lib/python3.5/site-packages/tensorflow/python/framework/op_def_library.py in _SatisfiesTypeConstraint(dtype, attr_def, param_name)
59 "allowed values: %s" %
60 (param_name, dtypes.as_dtype(dtype).name,
---> 61 ", ".join(dtypes.as_dtype(x).name for x in allowed_list)))
62
63
TypeError: Value passed to parameter 'a' has DataType int64 not in list of allowed values: float16, float32, float64, int32, complex64, complex128
知道代码有什么问题吗?
Any idea what could be wrong with the code?
推荐答案
这里是 tf.matmul
的文档:
两个矩阵的类型必须相同.支持的类型有:float16
、float32
、float64
、int32
、complex64
、complex128代码>.
Both matrices must be of the same type. The supported types are:
float16
,float32
,float64
,int32
,complex64
,complex128
.
将数据类型更改为支持的一种可以消除错误.
Changing the data type to one of the supported eliminates the error.
_X = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int32)
_Y = np.array([[1, 1], [2, 2], [3, 3]], dtype=np.int32)
X = tf.convert_to_tensor(_X)
Y = tf.convert_to_tensor(_Y)
res = tf.matmul(X, Y)
sess = tf.Session()
res.eval(session=sess)
#array([[14, 14],
# [32, 32]], dtype=int32)
这篇关于不能用张量流做矩阵乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文