tf.add_to_collection() tf.get_collection() tf.add_n()
tf.add_to_collection:把变量放入一个集合,把很多变量变成一个列表 tf.get_collection:从一个结合中取出全部变量,是一个列表 tf.add_n:把一个列表的东西都依次加起来 例如: import tensorflow as tf; import numpy as np; import matplotlib.pyplot as plt; v1 = tf.get_variable(name='v1', shape=[1], initializer=tf.constant_initializer(0)) tf.add_to_collection('loss', v1) v2 = tf.get_variable(name='v2', shape=[1], initializer=tf.constant_initializer(2)) tf.add_to_collection('loss', v2) with tf.Session() as sess: sess.run(tf.initialize_all_variables()) print tf.get_collection('loss') print sess.run(tf.add_n(tf.get_collection('loss'))) 输出: [<tensorflow.python.ops.variables.Variable object at 0x7f6b5d700c50>, <tensorflow.python.ops.variables.Variable object at 0x7f6b5d700c90>] [ 2.]
张量 数组相互转换
# 主要是两个方法: # 1.数组转tensor:数组a, tensor_a=tf.convert_to_tensor(a) # 2.tensor转数组:tensor b, array_b=b.eval() # # 下面看一个例子 import tensorflow as tf import numpy as np a=np.array([[1,2,3],[4,5,6],[7,8,9]]) print (a) b=tf.constant(a) with tf.Session() as sess: print (b) for x in b.eval(): #b.eval()就得到tensor的数组形式 print (x) print ('a是数组',a) tensor_a=tf.convert_to_tensor(a) print ('现在转换为tensor了...',tensor_a)