美文网首页
TF - 常量

TF - 常量

作者: 大地瓜_ | 来源:发表于2019-01-09 22:10 被阅读0次

在TF中,所有的数据都通过张量Tensor来表示

import tensorflow as tf
a = tf.constant([1,2,3], name ="a")
# <tf.Tensor 'a_1:0' shape=(3,) dtype=int32>

TFtensor主要保存三个属性:名字name 维度shape 类型type

张量维度shape

第一阶张量为向量,也就是一维数组;第二阶张量为矩阵

b = tf.constant([[1,2],[3,4]] ,name = "b")
# <tf.Tensor 'b_1:0' shape=(2, 2) dtype=int32>

张量类型type

每个张量会有一个唯一的类型。TF会对参与运算张量类型进行匹配,如果不一样,会有类型不匹配的错误

import tensorflow as tf
a = tf.constant([1,2,3], name ="a")
b = tf.constant([1.0,2.0,3.0], name ="a")
tf.add(a, b, name = "add")
# TypeError: Input 'y' of 'Add' Op has type float32 that does not match type int32 of argument 'x'.

解决方案 a = tf.constant([1,2,3], name ="a",type=tf.float32)

常见type类型

实数:tf.float32 tf.float64
整数:tf.int8 tf.int32 tf.uint8
布尔型:tf.bool

张量常见的方法

**获取张量的维度 **

tf.shape(input)[0]
# 获取第一个维度的值

tensor和numpy对象的转换 tf.session()中运行

with tf.Session() as sess:
  res = a.eval()
  print type(res)
  #<type 'numpy.ndarray'>
with tf.Session() as sess:
  data = tf.convert_to_tensor(x)
  print data
  # Tensor("Const_1:0", shape=(2, 2), dtype=float64)

相关文章

网友评论

      本文标题:TF - 常量

      本文链接:https://www.haomeiwen.com/subject/cdrnrqtx.html