TensorFlow 入门(四)

形状改变和类型改变

1.形状改变

形状改变分为,静态改变和动态改变

1.1 静态改变形状

静态形状改变就是:在形状还没有完全确定下来的时候,对形状进行改变。

tensor.set_shape(shape=[])

tensor:要修改的tensor
shape:要修改的形状大小

import tensorflow as tf
a = tf.placeholder(shape=[None,None,None],dtype=tf.int32)
b = tf.placeholder(shape=[None,None,3], dtype=tf.int32)
c  = tf.placeholder(shape=[None,3,3], dtype=tf.int32)
print('a:',a)
print('b:',b)
print('c:',c)
print('_'*50)
#更新形状
a.set_shape(shape=[3,4,5])
b.set_shape(shape=[4,5,3])
c.set_shape(shape=[5,3,3])

print('a:',a)
print('b:',b)
print('c:',c)

打印结果

a: Tensor(“Placeholder:0”, shape=(?, ?, ?), dtype=int32)
b: Tensor(“Placeholder_1:0”, shape=(?, ?, 3), dtype=int32)
c: Tensor(“Placeholder_2:0”, shape=(?, 3, 3), dtype=int32)


a: Tensor(“Placeholder:0”, shape=(3, 4, 5), dtype=int32)
b: Tensor(“Placeholder_1:0”, shape=(4, 5, 3), dtype=int32)
c: Tensor(“Placeholder_2:0”, shape=(5, 3, 3), dtype=int32)

说明:
刚开始a shape=(?, ?, ?)。是三个问号码。就是说是一个三阶张量。但是每一阶的大小没有确定。我们改变的是时候,只能对没有确定大小的进行改变。对于a我们只能该变每阶的大小。不能改成其他阶。

如果写成
对于a
a.set_shape(shape=[3,4,5,1])
就会报错。原来是三阶张量,我们却改成了四阶张量。所以会报错。

对于b
b.set_shape(shape=[4,5,5])
也会报错。b 的形状是shape=(?, ?, 3)。虽然我们没有修改他的阶数,但是最后阶大小是3,已经确定。如果我们把它修改成了其他的大小,就会报错。

注意
静态改变,并不会生成新的变量。

如上面的例子。a,b,c 修改后返回的仍然是a,b,c

1.2 动态改变

动态改变就是: 在形状确定下来了,进行改变。

tf.reshape(a,shape=[])

a:传入的tensor
shape:要修改的形状大小

import tensorflow as tf

a = tf.placeholder(shape=[4,4,4], dtype=tf.int32)
b = tf.placeholder(shape=[4,4,None], dtype=tf.int32)

print('a:',a)
print('b:',b)
print('_'*50)
#更新形状
a_1 = tf.reshape(a,shape=[2,4,8])
b_1 = tf.reshape(b,shape=[2,2,4])

print('a_1:',a_1)
print('b_1:',b_1)

打印结果

a: Tensor(“Placeholder:0”, shape=(4, 4, 4), dtype=int32)
b: Tensor(“Placeholder_1:0”, shape=(4, 4, ?), dtype=int32)


a_1: Tensor(“Reshape:0”, shape=(2, 4, 8), dtype=int32)
b_1: Tensor(“Reshape_1:0”, shape=(2, 2, 4), dtype=int32)

说明

刚开始a的形状是==shape=(4, 4, 4),==已经完全确定下来了。

动态修改就是:确定形状了的也能修改成其他的大小,但是他,会返回一个新的值。并不是对原来的直接修改

注意

修改前和修改后的元素总是应保持一直。

在上面例子中。a的元素总数是4x4x4=64

修改后的元素也是2x4x8=64.

如果将:
a_1 = tf.reshape(a,shape=[2,4,8])
改成
a_1 = tf.reshape(a,shape=[2,4,9])

就会报错。因为前面是64个元素,修改后为72个。修改前后的元素总个数不相同。

还有就是b的形状是:shape=(4, 4, ?) 有一阶没有确定。

对于这种有没有确定的形状。我们要进行修改的时候,要注意。
因为形状没有完全确定,但是我们可以确定的是,他的元素综合一定是4x4xNone=16xNone

也是就是说原来的总数是16的倍数,我们修改后的总数也应该是16的倍数。

如果修改后不是16的倍数就会报错。
原来例子中
b_1 = tf.reshape(b,shape=[2,2,4])
**2x2x4=16 **就不会报错

如果修改成:
b_1 = tf.reshape(b,shape=[2,2,5])

2x2x5=20就会报错。因为不是16的整倍数了。

2 类型改变

类型修改有很多种方法。对不同的类型有不同的方法。
一般我们都是有通用的方法。

tf.cast(a,dtype=tf.float32)

a:传入的tensor
dtype:要修改的类型

import tensorflow as tf

a = tf.placeholder(shape=[4,4,4], dtype=tf.int32)

print('a:',a)
print('_'*50)
#更新类型
a_1 = tf.cast(a,dtype=tf.float32)
print('a_1:',a_1)

显示结果*

a: Tensor(“Placeholder:0”, shape=(4, 4, 4), dtype=int32)


a_1: Tensor(“Cast:0”, shape=(4, 4, 4), dtype=float32)

注意tf.cast会返回一个新的对象。
在上面的例子中本来是dtype=int32
修改之后是dtype=float32
并且返回了一个新的值


更多精彩内容