博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
AI - TensorFlow - 张量(Tensor)
阅读量:6885 次
发布时间:2019-06-27

本文共 7635 字,大约阅读时间需要 25 分钟。

张量(Tensor)

在Tensorflow中,变量统一称作张量(Tensor)。

张量(Tensor)是任意维度的数组。

  • 0阶张量:纯量或标量 (scalar), 也就是一个数值,例如,\'Howdy\' 或 5
  • 1阶张量:向量 (vector)或矢量,也就是一维数组(一组有序排列的数),例如,[2, 3, 5, 7, 11] 或 [5]
  • 2阶张量:矩阵 (matrix),也就是二维数组(有序排列的向量),例如,[[3.1, 8.2, 5.9][4.3, -2.7, 6.5]]
  • 3阶张量:三维的矩阵,也就是把矩阵有序地叠加起来,成为一个“立方体”
  • 以此类推,等等。

在大多数情况下,只会使用一个或多个低维张量(2阶及以下)。

典型 TensorFlow 程序中的大多数代码行都是指令,张量也是计算图中的一种指令。

张量可以作为常量或变量存储在图中。

  • 常量是始终会返回同一张量值的指令,存储的是值不会发生更改的张量。
  • 变量是会返回分配给它的任何张量的指令,存储的是值会发生更改的张量。 

TensorFlow指南:

  • 张量:
  • 变量:

 

张量的定义

1 # coding=utf-8 2 import tensorflow as tf 3 import os 4 5 os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' 6 7 x = tf.constant([5.6], name="x_const") # tf.constant定义标量整数常量并传入值 8 y = tf.Variable([0], name="y_Variable") # tf.Variable定义变量并传入默认值 9 y = y.assign([3]) # 分配一个值 10 11 with tf.Session() as sess: # 图必须在会话中运行,会话存储了它所运行的图的状态 12 initialization = tf.global_variables_initializer() # 使用tf.Variable时,必须在会话开始时明确初始化变量 13 print("x: {}".format(sess.run(x))) 14 print("y: {}".format(sess.run(y)))

运行结果:

x: [5.6]y: [3]

 

常量相加

1 # coding=utf-8 2 import tensorflow as tf 3 import os 4 5 os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' 6 7 g = tf.Graph() # 创建图,虽然TensorFlow提供一个默认图,仍建议创建自己的Graph,以便跟踪状态 8 9 with g.as_default(): # 将定义的图作为默认 10 x = tf.constant(8, name="x_const") # tf.constant定义标量整数常量并传入值 11 y = tf.constant(5, name="y_const") 12 z = tf.constant(4, name="z_const") 13 sum1 = tf.add(x, y, name="x_y_sum") # tf.add相加 14 sum2 = tf.add(z, sum1, name="x_y_z_sum") 15 with tf.Session() as sess: # 图必须在会话中运行 16 print("sum1: {}".format(sum1.eval())) 17 print("sum2: {}".format(sum2.eval()))

 运行结果:

sum1: 13sum2: 17

 

矢量相加、张量形状与广播

1 # coding=utf-8 2 import tensorflow as tf 3 import os 4  5 os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' 6  7 try: 8     tf.contrib.eager.enable_eager_execution() 9     print("# TF imported with eager execution!")10 except ValueError:11     print("# TF already imported with eager execution!")12 13 # ### 矢量(一维张量)加法14 primes = tf.constant([2, 3, 5, 7, 11, 13], dtype=tf.int32)  # 包含质数的primes矢量15 ones = tf.ones([6], dtype=tf.int32)  # 值全为1的ones矢量16 just_beyond_primes = tf.add(primes, ones)  # 通过对前两个矢量执行元素级加法而创建的矢量17 twos = tf.constant([2, 2, 2, 2, 2, 2], dtype=tf.int32)18 primes_doubled = primes * twos  # 通过将primes矢量中的元素翻倍而创建的矢量19 print("primes: ", primes)20 print("ones: ", ones)21 print("just_beyond_primes: ", just_beyond_primes)22 print("primes_doubled: ", primes_doubled)23 24 some_matrix = tf.constant([[1, 2, 3], [4, 5, 6]], dtype=tf.int32)25 print("some_matrix: ", some_matrix)  # 输出张量将返回其值、形状以及存储在张量中的值的类型26 print("value of some_matrix is:\n", some_matrix.numpy())  # 调用张量的numpy方法会返回该张量的值(以NumPy数组形式)27 28 # ### 张量形状29 scalar = tf.zeros([])  # 标量30 vector = tf.zeros([3])  # 值全为0的矢量31 matrix = tf.zeros([2, 3])  # 值全为0的2行3列矩阵32 print('scalar has shape:', scalar.get_shape(), 'and value:\n', scalar.numpy())33 print('vector has shape:', vector.get_shape(), 'and value:\n', vector.numpy())34 print('matrix has shape:', matrix.get_shape(), 'and value:\n', matrix.numpy())35 36 # ### 广播37 primes2 = tf.constant([2, 3, 5, 7, 11, 13], dtype=tf.int32)38 ones2 = tf.ones(1, dtype=tf.int32)  # 使用的是标量值(不是全包含1矢量)和广播39 just_beyond_primes2 = tf.add(primes2, ones2)40 twos2 = tf.constant(2, dtype=tf.int32)  # 使用的是标量值(不是全包含 2 的矢量)和广播41 primes_doubled2 = primes2 * twos242 print("primes2: ", primes2)43 print("ones2: ", ones2)44 print("just_beyond_primes2: ", just_beyond_primes2)45 print("primes_doubled2: ", primes_doubled2)46 47 # ### 矢量加法48 # 可以对张量执行很多典型数学运算:https://www.tensorflow.org/api_docs/python/tf/math;49 # 输出张量将返回其值、形状以及存储在张量中的值的类型;50 # 调用张量的numpy方法会返回该张量的值(以NumPy数组形式);51 #52 # ### 张量形状(shape)53 # 形状(shape)用于描述张量维度的大小和数量;54 # 张量的形状表示为list,其中第i个元素表示维度i的大小;55 # 列表的长度表示张量的阶(即维数);56 #57 # ### 广播58 # TensorFlow支持广播(一种借鉴自NumPy的概念);59 # 利用广播,元素级运算中的较小数组会增大到与较大数组具有相同的形状;

运行结果:

# TF imported with eager execution!primes:  tf.Tensor([ 2  3  5  7 11 13], shape=(6,), dtype=int32)ones:  tf.Tensor([1 1 1 1 1 1], shape=(6,), dtype=int32)just_beyond_primes:  tf.Tensor([ 3  4  6  8 12 14], shape=(6,), dtype=int32)primes_doubled:  tf.Tensor([ 4  6 10 14 22 26], shape=(6,), dtype=int32)some_matrix:  tf.Tensor([[1 2 3] [4 5 6]], shape=(2, 3), dtype=int32)value of some_matrix is: [[1 2 3] [4 5 6]]scalar has shape: () and value: 0.0vector has shape: (3,) and value: [0. 0. 0.]matrix has shape: (2, 3) and value: [[0. 0. 0.] [0. 0. 0.]]primes2:  tf.Tensor([ 2  3  5  7 11 13], shape=(6,), dtype=int32)ones2:  tf.Tensor([1], shape=(1,), dtype=int32)just_beyond_primes2:  tf.Tensor([ 3  4  6  8 12 14], shape=(6,), dtype=int32)primes_doubled2:  tf.Tensor([ 4  6 10 14 22 26], shape=(6,), dtype=int32)

 

矩阵相乘、张量变形

1 # coding=utf-8 2 import tensorflow as tf 3 import os 4  5 os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' 6  7 try: 8     tf.contrib.eager.enable_eager_execution() 9     print("# TF imported with eager execution!")10 except ValueError:11     print("# TF already imported with eager execution!")12 13 # ### 矩阵相乘14 x = tf.constant([[5, 2, 4, 3], [5, 1, 6, -2], [-1, 3, -1, -2]], dtype=tf.int32)  # 3行4列矩阵15 y = tf.constant([[2, 2], [3, 5], [4, 5], [1, 6]], dtype=tf.int32)  # 4行2列矩阵16 matrix_multiply_result = tf.matmul(x, y)  # 矩阵相乘的结果是3行2列矩阵17 print("matrix_multiply_result: ", matrix_multiply_result)18 19 # ### 张量变形20 matrix = tf.constant([[1, 2], [3, 4], [5, 6], [7, 8]], dtype=tf.int32)  # 4行2列的矩阵21 reshaped_2x4_matrix = tf.reshape(matrix, [2, 4])  # 将4x2张量变形为2x4张量22 reshaped_1x8_matrix = tf.reshape(matrix, [1, 8])23 reshaped_2x2x2_tensor = tf.reshape(matrix, [2, 2, 2])  # 将4x2张量变形为三维2x2x2张量24 one_dimensional_vector = tf.reshape(matrix, [8])  # 将4x2张量变形为一维8元素张量25 print("Original matrix (4x2):\n", matrix.numpy())26 print("Reshaped matrix (2x4):\n", reshaped_2x4_matrix.numpy())27 print("Reshaped matrix (1x8):\n", reshaped_1x8_matrix.numpy())28 print("reshaped_2x2x2_tensor:\n", reshaped_2x2x2_tensor.numpy())29 print("one_dimensional_vector:\n", one_dimensional_vector.numpy())30 31 # ### 矩阵相乘32 # 在线性代数中,当两个矩阵相乘时,第一个矩阵的列数必须等于第二个矩阵的行数,否则是无效的;33 #34 # ### 张量变形35 # 可以使用tf.reshape方法改变张量的形状和维数(“阶”);36 # 例如,可以将4x2张量变形为2x4张量;37 # 例如,可以将4x2张量变形为三维2x2x2张量或一维8元素张量;

运行结果:

# TF imported with eager execution!matrix_multiply_result:  tf.Tensor([[35 58] [35 33] [ 1 -4]], shape=(3, 2), dtype=int32)Original matrix (4x2): [[1 2] [3 4] [5 6] [7 8]]Reshaped matrix (2x4): [[1 2 3 4] [5 6 7 8]]Reshaped matrix (1x8): [[1 2 3 4 5 6 7 8]]reshaped_2x2x2_tensor: [[[1 2]  [3 4]] [[5 6]  [7 8]]]one_dimensional_vector: [1 2 3 4 5 6 7 8]

 

变量、初始化和赋值

1 # coding=utf-8 2 import tensorflow as tf 3 import os 4  5 os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' 6  7 try: 8     tf.contrib.eager.enable_eager_execution() 9     print("# TF imported with eager execution!")10 except ValueError:11     print("# TF already imported with eager execution!")12 13 v1 = tf.contrib.eager.Variable([3])  # 创建一个初始值为3的标量变量14 v2 = tf.contrib.eager.Variable(15     tf.random_normal(shape=[1, 4],  # 形状为1行4列,必选项16                      mean=1.0,  # 正态分布的均值,默认为017                      stddev=0.35,  # 正态分布的标准差,默认为1.018                      dtype=tf.float64,  # 输出的类型,默认为tf.float3219                      seed=1,  # 每次产生的随机数结果是否相同,如果固定seed值为一个整数则相同,默认为None(不相同)20                      name="test")  # 操作的名称21 )  # 创建一个初始值为正态分布的1*4矢量变量22 tf.assign(v1, [7])  # 使用assign更改变量的值23 24 print("v1:", v1.numpy())25 print("v2:", v2.numpy())26 27 # ### 变量、初始化和赋值28 # 在TensorFlow中可以定义Variable对象(变量),其值可以更改;29 # 创建变量时,可以明确设置一个初始值,也可以使用初始化程序(例如分布);30 # 使用assign更改变量的值,向变量赋予新值时,其形状必须和之前的形状一致;31 #32 # ### tf.random_normal()函数33 # 用于从服从指定正太分布的数值中取出指定个数的值;

运行结果:

# TF imported with eager execution!v1: [7]v2: [[1.08498964 0.87645062 0.70722227 0.91475084]]

 

转载于:https://www.cnblogs.com/anliven/p/5985262.html

你可能感兴趣的文章
课后作业-----输入法评价
查看>>
使用qemu
查看>>
静态页之间传值
查看>>
01.Hibernate快速入门
查看>>
ThinkPHP3.2判断是否为手机端访问并跳转到另一个模块的方法
查看>>
人事管理系统——11个基础信息管理界面
查看>>
关于联想超极本出现蓝屏Default Boot Device Missing or Boot Failed的解决办法
查看>>
solr索引报错(java.lang.OutOfMemoryError:GC overhead limit exceeded)
查看>>
python基础2--小结篇
查看>>
Ajax传统操作
查看>>
webpack01
查看>>
NoSQL 简介
查看>>
功能测试思考点
查看>>
PHP代码审计
查看>>
杭电4786--Fibonacci Tree(生成树)
查看>>
git 基础
查看>>
搜索高亮
查看>>
图片上没有line-height垂直居中
查看>>
图片标记 : 行内元素 单边标记
查看>>
canvas基础—图形变换
查看>>