2017-06-07 142 views
0

在Tensorflow,我想用這個代碼做矩陣乘法:不能做矩陣乘法與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

您應該閱讀我的最新帖子,它完全涵蓋此示例:https://pgaleone.eu/tensorflow/go/2017/05/29/understanding-tensorflow-using-go/ – nessuno

回答

2

這裏是文檔爲tf.matmul

Both matrices must be of the same type. The supported types are: 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)