TensorFlow--张量

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012911202/article/details/85258897

参考https://www.jianshu.com/p/a8f57bd5e5b6

单词tensor翻译成中文,就是张量。可以类比C/C++中的数组。

例子:

import tensorflow as tf

# tf.constant是一个计算,这个计算的结果为一个张量,保存在变量a,b中
#下面的a,b...就是张量
a = tf.constant(100, name="a")
b = tf.constant([1.0,2.0], name="b")
c = tf.constant([2.0,3.0], name="c")
d = tf.constant([[2.0,3.0]], name="d")
e = tf.constant([[2.0,3.0],[4.0,5.0]], name="e")
f = tf.constant([[[2.0,3.0],[4.0,5.0]]], name="f")

print(a)
print(b)
print(c)
print(d)
print(e)
print(f)

输出结果:

Tensor("a_16:0", shape=(), dtype=int32)
Tensor("b_16:0", shape=(2,), dtype=float32)
Tensor("c_5:0", shape=(2,), dtype=float32)
Tensor("d_5:0", shape=(1, 2), dtype=float32)
Tensor("e_5:0", shape=(2, 2), dtype=float32)
Tensor("f_4:0", shape=(1, 2, 2), dtype=float32)

张量介绍

从结果可以看出,一个张量主要包括三个属性:名字(name)、维度(shape)和类型(type)

name

张量的命名形式:node:src_output
其中node为节点的名称,src_output表示当前张量来自节点的第几个输出。

shape

该属性描述了一个张量的维度信息,比如上面样例中shape=(2,)说明张量result是一个长度为2的一维数组。

type

每一个张量会有一个唯一的类型,运行时Tensorflow会对参与运算的所有张量进行类型的检查,当发现类型不匹配时会报错,比如下面这段程序:

import tensorflow as tf
a = tf.constant([1, 2], name="a")
b = tf.constant([2.0, 3.0], name="b")
result = tf.add(a, b, name="add")

报错:

ValueError: Tensor conversion requested dtype int32 for Tensor with dtype float32: 'Tensor("b:0", shape=(2,), dtype=float32)'

如果将一个加数指定成实数类型就不会出错了

a = tf.constant([1, 2], name="a", dtype=tf.float32)
b = tf.constant([2.0, 3.0], name="b")
result = tf.add(a, b, name="add")

为了避免导致类型不匹配的问题,建议通过dtype来明确指定变量或常量的类型

张量维度

张量维度,感性地理解,可以简单地从中括号的层数判定。当然这个方法仅限张量每个维度数值较小,可罗列。用上面的例子说明。

张量a,没有中括号,是标量。通过print(a),从输出结果看,shape(),表示标量

Tensor("a_16:0", shape=(), dtype=int32)

张量b,有一层中括号,是一维向量。通过print(b),从shape(2,)表示一维向量

张量c和d区别,d多一层中括号,所以c是一维向量,而d是二维向量。从输出结果shape(2,) 和shape(1,2)也能看出。d有两维,每个维度数值分别是1,2

其他类似。

猜你喜欢

转载自blog.csdn.net/u012911202/article/details/85258897