在Tensorflow中,我想使用以下代码进行矩阵乘法:
_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
知道代码有什么问题吗?
答案 0 :(得分:2)
以下是tf.matmul
的文档:
两个矩阵必须属于同一类型。支持的类型是:
float16
,float32
,float64
,int32
,complex64
,complex128
。
将数据类型更改为支持的数据类型可消除错误。
_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)