张量(Tensor)
1、张量在计算机中如何存储?
标量 一个数字 ---- 0阶张量
向量 一维数组[2,3,4] ----一阶张量
矩阵 二维数组[[2,3,4],
[5,6,7]] ----2阶张量
张量 n维数组 ----n阶张量 TensorFlow的张量就是一个n维数组。
2)两个重要的属性 :type ---数据类型 shape ---形状(阶)
张量的类型
张量的阶
def tensor_demo():
"""
张量的演示
:return:
"""
tensor1 = tf.constant(4.0)
tensor2 = tf.constant([1,2,3,4])
linear_squares = tf.constant([[4],[9],[16],[25]],dtype=tf.int32)
print("tensor1:\n",tensor1)
print("tensor2:\n", tensor2)
print("liner_squares:\n", linear_squares)
return None
tensor_demo()
创建张量的时候,如果不指定类型 默认 tf.float32 整形tf.int32 浮点型tf.float32
2、创建张量的指令 具体操作查看API
1)固定值张量
tf.zeros(shape, dtype-=t.float32, name: =None) ---创建所有元素设置为0
tf.ones(shape, dtype=tf1loat32, name=None) ---创建所有元素为1
tf.constant(value, dtype=None, shape=None, name='Const') ---创建一个常数张量
2)随机张量
tf.truncated_ normal(shape, mean=0.0, stddev= 1.0, dtype-tf.float32, seed=None, name=None) ----创建符合正态分布
特殊张量 tf.Variable tf.placeholder
3、张量的变换
1)类型改变
最后一个可以修改任何 tf.cast(tensor,dtype)
不会改变原始的tensor 返回新改变类型后的tensor
2)形状改变
静态形状 ---初始创建张量时的形状
(tensor.set_shape(shape))只有在形状没有完全固定下来的情况 并且不能跨阶修改
动态形状
(tf.reshape(tensor,shape))创建新张量时,张量元素个数必须匹配
4、张量的数学运算 使用时查API
算数运算符
基本数学函数
矩阵运算
reduce操作
序列索引操作
变量OP
TensorFlow变量是表示程序处理的共享持久状态的最佳方法。变量通过tf.VariableOP类进行操作。变量的特点:
存储持久化
可修改值
可指定被训练
1、创建变量
tf.Variable(initial_ value=None,trainable=True,collections=None,name=None)
initial_ value:初始化的值
trainable:是否被训练
collections:新变量将添加到列出的图的集合collection
注意: 变量需要显示初始化,才能运行值
修改变量的命名空间
好处:代码模块化,清晰,可视化也更加清晰