Cannot perform matrix multiplication using tensor flow

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)

However, I get this error:

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?

0
source share
1 answer

Here are the docs for tf.matmul:

Both matrices must be of the same type. Supported types: float16, float32, float64, int32, complex64, complex128.

Changing the data type to one of the supported ones 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)
+2
source

Source: https://habr.com/ru/post/1678721/


All Articles