tensorflow【1】-Tensor

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

属性

数据格式

tf.string、tf.float32、tf.int16、tf.int32、tf.complex64(复数)、tf.bool 等

数据形状

1. 形状 shape 是 Tensor 的属性,可直接获取,无需 session

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

阶数:Tensor 的维度

阶数的获取需要 session

示例

d1 = tf.ones([3, 2])
print(d1.shape)         # (3, 2)  shape 可直接获取,无需 session
n1 = tf.rank(d1)
print(n1)               # Tensor("Rank:0", shape=(), dtype=int32)  阶数 不可直接获取,需要 session

d2 = tf.constant([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]])
print(d2)           # Tensor("Const:0", shape=(2, 2, 3), dtype=int32)
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  占位符

常量

注意几点:

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.]]

参考资料:

猜你喜欢

转载自www.cnblogs.com/yanshw/p/12341203.html