张量

1.数据类型

 

数据类型 Python 类型 描述

DT_FLOAT tf.float32 32 位浮点数.

DT_DOUBLE tf.float64 64 位浮点数.
DT_INT64 tf.int64 64 位有符号整型.
DT_INT32 tf.int32 32 位有符号整型.
DT_INT16 tf.int16 16 位有符号整型.
DT_INT8 tf.int8 8 位有符号整型.
DT_UINT8 tf.uint8 8 位无符号整型.

2. 维数

1 con1 = tf.constant(11.0,name="con1")
2 con2 = tf.constant([1,2,3,4],name="con2")
3 con3 = tf.constant([[1],[3],[2]],name="con3")
4 
5 
6 print(con1.shape)
7 print(con2.shape)
8 print(con3.shape)

运行结果

()  --0维
(4,) --1维
(3, 1)  --2维

3.创建张量的指令

    固定值张量

tf.zeros(shape,dtype=tf.float32,name=None)  所有元素为0的张量,float32为默认的,可以改变
tf.ones(shape,dtype=tf.float32,name=None) 所有元素为1的张量,float32为默认的,可以改变
tf.constant(shape,dtype=tf.float32,name=None) 常数张量,float32为默认的,可以改变

1 a = tf.zeros([2])
2 b = tf.zeros([2, 3], dtype=tf.int32)

     运行结果:

1 [0. 0.]
2 
3 [[0 0 0]
4  [0 0 0]]

 

    随机值张量

        random_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None)  从正态分布中输出随机值

       其它特殊的创建张量的op

                变量OP

4.张量的变换

      类型改变

  • tf.string_to_number(string_tensor, out_type=None, name=None)  
    • 将输入Tensor中的每个字符串转换为指定的数字类型。注意,int32溢出导致错误,而浮点溢出导致舍入值
    • 1 n1 = tf.constant(["1234","6789"])
      2 n2 = tf.string_to_number(n1,out_type=tf.float32)
      3 
      4 with   tf.compat.v1.Session() as  sess:
      5 
      6     print(sess.run(n2))#通过使用sess.run()来运行operation

                运行结果

[1234. 6789.]

  • tf.cast(x, dtype, name=None)
    • x:需要转换数据类型的对象   dtype:转换至此数据类型 
  • 1 import tensorflow as tf
    2 
    3 a=[[9.5,2.7],[1,2]]
    4 b=tf.cast(a,tf.int32)
    5 
    6 with tf.Session() as sess:
    7     print(sess.run(b))

    运行结果

[[9 2] 
[1 2]]

 5.形状

  • 动态形状 tf.reshape(tensor, shape, name=None)
    • tf.reshape()动态创建新张量时,张量的元素个数必须匹配
  • 静态形状tf.set_shape(input, name=None)
    • 转换静态形状的时候,1-D到1-D,2-D到2-D,不能跨阶数改变形状
    • 对于已经固定的张量的静态形状的张量,不能再次设置静态形状

 

5.tf.compat.v1.global_variables_initializer()

           默认添加所有节点用于初始化全局变量(GraphKeys.GLOBAL_VARIABLES)。返回一个初始化所有全局变量的操作(Op)。在你构建完整个模型并在会话中加载模型后,运行这个节点。能够将所有的变量一步到位的初始化,非常的方便。通过feed_dict, 你也可以将指定的列表传递给它,只初始化列表中的变量。

 

 

posted on 2020-07-11 00:26  眼睛是心灵的窗户吗  阅读(122)  评论(0)    收藏  举报