tf.convert_to_tensor()

这是个很有用的函数,我们经常需要将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]]))#tensor
value_2 = my_func([[1, 2], [3, 4]])#python list
value_3 = my_func(np.array([[1.0, 2], [3, 4]], dtype=np.float32))#numpy arrays

with 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))


结果为


  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值