tensorflow基础【1】-Tensor

tensor 即张量,是 tf 的核心数据结构,它可以是一个标量、向量、矩阵、多维数组

基本属性

Tensor 有 3 个基本属性

d2 = tf.constant([1., 2.])
print(d2)           # Tensor("Const:0", shape=(2,), dtype=float32)

解释如下

节点名:输出:Tensor 是节点的输入和输出,节点就是操作 op,上图中 add 就是一个 op,代表这个 Tensor 是 add 操作的输出

这点很重要,用来判断是不是 操作op   

数据格式:tf.string、tf.float32、tf.int16、tf.int32、tf.complex64(复数)、tf.bool 等 

基本属性可直接获取,无需 Session

d1 = tf.ones((2, 3))
## 直接获取属性,无需 session
print(d1)           # Tensor("ones:0", shape=(2, 3), dtype=float32)
print(d1.shape)     # (2, 3)
print(d1.dtype)     # <dtype: 'float32'>

shape

值得注意的是第二个属性 shape,它和 numpy 中的 shape 是一样的

先看个例子:

d2 = tf.constant([1., 2.])
print(d2)           # Tensor("Const:0", shape=(2,), dtype=float32)      ### 我们发现 shape 并不是 (1, 2)
#### vs numpy
d3 = np.array([1, 2])
print(d3.shape)     # (2,)      ### numpy 的 shape 与 Tensor 的 shape 一致

跟我们理解的 shape 略有不同,其实 shape 是这样的,

shape 中 元素的个数 代表 Tensor 的维度,或者说阶数,每个元素的值 代表 这个维度上的 长度;

# shape=(100,784) 代表该张量有两个维度,第一个维度长度为100,第二个维度长度为784,二维数组100行784列;
# shape=(2,) 代表该张量有一个维度,第一个维度长度为2,一维数组1行2列

再看个例子:

d4 = tf.constant([[[1, 1, 1, 1], [2, 2, 2, 3]], [[3, 3, 3, 3], [4, 4, 4, 4]]])
print(d4)           # Tensor("Const_1:0", shape=(2, 2, 4), dtype=int32)
#### vs numpy
d5 = np.array([[[1, 1, 1, 1], [2, 2, 2, 3]], [[3, 3, 3, 3], [4, 4, 4, 4]]])
print(d4.shape)     # (2, 2, 4)     ### numpy 的 shape 与 Tensor 的 shape 一致

其实对于高维数组来说,shape 就是矩阵的形状,如

[[[1,2,3],[4,5,6]]]
# 第一个维度中只有一个元素[[1,2,3][4,5,6]],所以第一个维度长度为1
# 第二个维度中有两个元素[1,2,3][4,5,6],所以第二个维度长度为2
# 第三个维度中有三个元素“1,2,3”或“4,5,6”,所以第三个维度长度为3
# 那么它的shape参数就是[1,2,3]

注意:形状不一定在编译时确定,可以在运行是通过推断得出

阶数:Tensor 的维度

阶数的获取需要 session

示例

d1 = tf.ones([3, 2])
n1 = tf.rank(d1)
print(n1)               # Tensor("Rank:0", shape=(), dtype=int32)  阶数 不可直接获取,需要 session
d2 = tf.constant([[[1, 1, 1, 1], [2, 2, 2, 3]], [[3, 3, 3, 3], [4, 4, 4, 4]]])
n2 = tf.rank(d2)
with tf.Session() as sess:
    print(sess.run(n1))     # 2 阶张量
    print(sess.run(n2))     # 3 阶张量

tf 中有几种比较特别的张量

tf.constant  常量

tf.Variable   变量

tf.placeholder  占位符

他们都具有 Tensor 的属性 

常量

注意几点:

1. 不同类型的常量不能运算

2. 常量可像 python 变量一样直接赋值

def constant(value, dtype=None, shape=None, name="Const")

示例

### 单个元素
d1 = tf.constant(1)
d2 = tf.constant(2, dtype=tf.int32, name='int')
d3 = tf.constant(3., dtype=tf.float32, name='float')
d4 = tf.add(d1, d2)
# d5 = d1 + d3                ### 不同类型的数据不能运算
d6 = d1 + d2

sess1 = tf.Session()
print(sess1.run(d4))        # 3
# print(sess1.run(d5))        ### 报错 type float32 does not match type int32
print(sess1.run(d6))        # 3
print(type(d6))             # <class 'tensorflow.python.framework.ops.Tensor'>


### 矩阵
d1 = tf.constant([[1., 2.]])
d2 = tf.constant([[2.], [3.]])
d3 = tf.matmul(d1, d2)

## 常数赋值
d2 = d1

sess2 = tf.Session()
print(sess2.run(d3))        # [[8.]]
print(sess2.run(d2))        # [[1. 2.]]

参考资料:

原文地址:https://www.cnblogs.com/yanshw/p/12341203.html