记录本人在使用 tensorflow 过程中遇到过的函数,长期更新。
1. def reshape(tensor, shape, name=None)
第1个参数为被调整维度的张量。
第2个参数为要调整为的形状。
返回一个shape形状的新tensor
注意shape里最多有一个维度的值可以填写为-1,表示自动计算此维度。shape是一个列表形式
好了我想说的重点还有一个就是根据shape如何变换矩阵。其实简单的想就是,
reshape(t, shape) => reshape(t, [-1]) => reshape(t, shape)
首先将矩阵t变为一维矩阵,然后再对矩阵的形式更改就可以了。
关于shape
# tensor 't' is [1, 2, 3, 4, 5, 6, 7, 8, 9]
# tensor 't' has shape [9]
# tensor 't' is [[[1, 1], [2, 2]],
# [[3, 3], [4, 4]]]
# tensor 't' has shape [2, 2, 2]
# tensor 't' is [[[1, 1, 1],
# [2, 2, 2]],
# [[3, 3, 3],
# [4, 4, 4]],
# [[5, 5, 5],
# [6, 6, 6]]]
# tensor 't' has shape [3, 2, 3]
2. tf.concat(concat_dim, values, name='concat')
concat_dim:必须是一个数,表明在哪一维上连接
如果concat_dim是0 可以理解为使行变大
t1 = [[1, 2, 3], [4, 5, 6]]
t2 = [[7, 8, 9], [10, 11, 12]]
tf.concat(0, [t1, t2]) == > [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
如果concat_dim是1 可以理解为使列变大
t1 = [[1, 2, 3], [4, 5, 6]]
t2 = [[7, 8, 9], [10, 11, 12]]
tf.concat(1, [t1, t2]) ==> [[1, 2, 3, 7, 8, 9], [4, 5, 6, 10, 11, 12
如果有更高维:
# tensor t3 with shape [2, 3]
# tensor t4 with shape [2, 3]
tf.shape(tf.concat(0, [t3, t4])) ==> [4, 3]
tf.shape(tf.concat(1, [t3, t4])) ==> [2, 6]
3. tf.add_to_collection(self, name, value)
将value以name的名称存储在收集器(self._collections)中.
import tensorflow as tf
v1 = tf.get_variable('v1', shape=[1], initializer=tf.ones_initializer())
v2 = tf.get_variable('v2', shape=[1], initializer=tf.zeros_initializer())
tf.add_to_collection('vc', v1)
tf.add_to_collection('vc', v2)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
vc = tf.get_collection('vc')
print(vc)
for i in vc:
print(i)
print(sess.run(i))
输出
[<tf.Variable 'v1:0' shape=(1,) dtype=float32_ref>, <tf.Variable 'v2:0' shape=(1,) dtype=float32_ref>]
<tf.Variable 'v1:0' shape=(1,) dtype=float32_ref>
[ 1.]
<tf.Variable 'v2:0' shape=(1,) dtype=float32_ref>
[ 0.]
4. tf.ones_like(tensor,dype=None,name=None)
新建一个与给定的tensor类型大小一致的tensor,其所有元素为1。