TensorFlow01:张量

匿名 (未验证) 提交于 2019-12-03 00:05:01

张量的形状:

标量---1个数字---0阶张量 向量---1维数组---1阶张量 矩阵---2维数组---2阶张量 张量---n维数组---n阶张量

张量操作:

tf.zeros(shape,dype=tf.float,name=None)    #全零张量  tf.ones()是全1张量 tf.zeros_like(tensor,dtype=None,name=None) #创建相同类型,相同形状的张量 tf.fill(shape,value,name=None)    #填充指定标量的张量 tf.constant(value,dtype=None,shape=None,name=None)   #创建一个常数张量 tf.truncated_normal(shape,mean=0.0,stddev=1.0,dtype=tf.float32,seed=None,name=None)#所有数字不超过两个标准差 tf.random_normal(shape,mean=0.0,stddv=1.0,dtype=tf.float32,seed,name=None)#随机正态分布的数字组成的矩阵 tf.cast(tensor,dtype)   #不会改变原始的tensor,返回新的改变类型后的tensor tensor.get_shape()    # 获取tensor形状 tensor.set_shape(shape) #改变静态形状(形状没有固定下来?号的形状),不能跨阶 tf.reshape(tensor,shape)#改变动态形状(张量的元素个数必须匹配),返回新的tensor tf.transpose(depth_major,[1,2,0]).eval()    # [c,h,w]  转换 [h,w,c]

代码实现1:创建张量

import tensorflow as tf zeros = tf.zeros([2, 3], name="zeros") ones = tf.ones_like(zeros,name ="ones") fill = tf.fill([2,3],5,name="fill") truncated = tf.truncated_normal([2,3],mean=1) random = tf.random_normal([2,3],name="random") with tf.Session() as sess:     zeros_,ones_,fill_,truncated_,random_ = sess.run([zeros,ones,fill,truncated,random])     print("zeros_:", zeros_)     print("ones_:", ones_)     print("fill_:", fill_)     print("truncated_:", truncated_)     print("random_:", random_)

运行结果:

zeros_: [[0. 0. 0.]  [0. 0. 0.]] ones_: [[1. 1. 1.]  [1. 1. 1.]] fill_: [[5 5 5]  [5 5 5]] truncated_: [[1.5404339  0.6582792  0.87537754]  [0.9082955  1.3467028  0.6821146 ]] random_: [[-0.02499405  0.27754402 -0.47137412]  [ 0.7734614  -1.1405578  -0.14125896]]

代码实现2:形状操作

import tensorflow as tf a = tf.placeholder(dtype=tf.float32,shape=[None, None]) b = tf.placeholder(dtype=tf.float32,shape=[None, 10]) c = tf.placeholder(dtype=tf.float16, shape=[3, 2]) print(a.get_shape()) print(b.get_shape()) print(c.get_shape()) a.set_shape([2, 3]) print("set_shape:", a.get_shape()) b.set_shape([2, 10]) print("set_shape:", b.get_shape()) c = tf.transpose(c, [1, 0]) print("transpose:", c.get_shape()) c = tf.reshape(c, [1, 6]) print("reshape:", c.get_shape())

运行结果:

(?, ?) (?, 10) (3, 2) set_shape: (2, 3) set_shape: (2, 10) transpose: (2, 3) reshape: (1, 6)

tf.zeros(shape,dype=tf.float,name=None)#全零张量 tf.ones()是全1张量

tf.zeros_like(tensor,dtype=None,name=None) #创建相同类型,相同形状的张量

tf.fill(shape,value,name=None)#填充指定标量的张量

tf.constant(value,dtype=None,shape=None,name=None)#创建一个常数张量

tf.truncated_normal(shape,mean=0.0,stddev=1.0,dtype=tf.float32,seed=None,name=None)#所有数字不超过两个标准差

tf.random_normal(shape,mean=0.0,stddv=1.0,dtype=tf.float32,seed,name=None)#随机正态分布的数字组成的矩阵

tf.cast(tensor,dtype)#不会改变原始的tensor,返回新的改变类型后的tensor

tensor.get_shape()# 获取tensor形状

tensor.set_shape(shape) #改变静态形状(形状没有固定下来?号的形状),不能跨阶

tf.reshape(tensor,shape)#改变动态形状(张量的元素个数必须匹配),返回新的tensor

tf.transpose(depth_major,[1,2,0]).eval()# [c,h,w]转换 [h,w,c]

代码实现1:创建张量

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!