tf.convert_to_tensor()

来源:互联网 发布:黑人枪杀 知乎 编辑:程序博客网 时间:2024/05/22 04:49

这是个很有用的函数,我们经常需要将python的数据类型转换成TensorFlow可用的tensor数据类型,所以仔细研究一下这个函数还是很有必要的。

参考官方说明文档

format:convert_to_tensor(value, dtype=None, name=None, preferred_dtype=None)

 Args:
      value: An object whose type has a registered `Tensor` conversion function.(这个说明这个函数只能转换特定的python数据类型)
      dtype: Optional element type for the returned tensor. If missing, the(可以指定转化成tensor后输出的数据类型)
        type is inferred from the type of `value`.
      name: Optional name to use if a new `Tensor` is created.
      preferred_dtype: Optional element type for the returned tensor,
        used when dtype is None. In some cases, a caller may not have a
        dtype in mind when converting to a tensor, so preferred_dtype
        can be used as a soft preference.  If the conversion to
        `preferred_dtype` is not possible, this argument has no effect.

    Returns:
      An `Output` based on `value`.(显然这个函数转换python成TensorFlow可用的tensor,但是具体的数类型还是有参数value决定)

This function converts Python objects of various types to `Tensor` objects. It accepts `Tensor` objects, numpy arrays, Python lists and Python scalars. 

翻译过来:这个函数把python的变量类型转换成tensor,而这个value可以是tensor,numpy arrays(numpy 的数组),python list(python 列表)python的表量

栗子

import numpy as np    def my_func(arg):    arg = tf.convert_to_tensor(arg)    return tf.matmul(arg, arg) + arg        # The following calls are equivalent.value_1 = my_func(tf.constant([[1, 2], [3, 4]]))#tensorvalue_2 = my_func([[1, 2], [3, 4]])#python listvalue_3 = my_func(np.array([[1.0, 2], [3, 4]], dtype=np.float32))#numpy arrayswith tf.Session() as sess:    result1,result2,result3=sess.run([value_1,value_2,value_3])    print('result1 = \n%s'%(result1))    print('result2 = \n%s'%(result2))    print('result3 = \n%s'%(result3))


结果为


原创粉丝点击