tensorflow学习日记 01

命令行参数

全局环境下编写代码

import tensorflow as tf
flags = tf.flags # flags 是一个文件:flags.py,用于处理命令行参数的解析g工作
logging = tf.logging

# 调用flags内部的DEFINE_string行数来制定解析规则
flags.DEFINE_string("para_name_1", "default_val", "description")
flags.DEFINE_bool("para_name_2", "default_val", "description")

# FLAGS是一个对象,保存了解析后的命令参数
FLAGS= flags.FLAGS

def main(_):
    FLAGS.para_neme # 调用命令行输入的参数

if __name__ == "__main__": # 使用这种方式保证了,如果此文件被其他文件import时,不会执行main中的代码
    tf.app.run() #解析命令行参数,调用main函数 main(sys.argv)

调用方法:

~/ python script.py --para_name_1=name --para_name_2=name2
# 不传的话,会使用默认值

打印输出tensor的值

使用tensorflow计算时,print只能打印出shape的信息,而要打印输出tensor的值,需要借助 tf.Session, 因为我们在建立graph的时候,只建立tensor的结构形状信息,并没有执行数据的操作。

a = tf.constant(5.0)
b = tf.constant(6.0)
c = a * b
sess = tf.Session() # 方式一
print(sess.run(c))
with tf.Session():
    print(c.eval()) # 方式二

tensor变换

矩阵操作

# 对于2-D
# 所有的reduce_...,如果不佳axis的话都是对整个矩阵进行运算
tf.reduce_sum(a, 1)# 对axis1
tf.redcue_mean(a, 0)# 每列均值

第二个参数是axis,如果为0的话, r e s [ i ] = j a [ j , i ] = a [ : , i ] ,如果是1的话, r e s [ i ] = j a [ i , j ] = a [ i , : ]

tf.concat(data, concat_dim) # 关于concat,可以用来降维
tf.concat([t1, t2],0) ==> [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
tf.concat([t1, t2],1) ==> [[1, 2, 3, 7, 8, 9], [4, 5, 6, 10, 11, 12]]

concat是将list中的向量给连接起来,axis表示将那维的数据连接起来,而其他维的结构保持不变

# squeeze 降维 维度为1的降掉
tf.squeeze(arr, [])
arr = tf.Variable(tf.truncated_normal([3,4,1,6,1], stddev=0.1))
arr2 = tf.squeeze(arr, [2,4])
arr3 = tf.squeeze(arr) 

# split
tf.split(value, num_or_size_splits, axis=0, name='split')
split0, split1, split2  = tf.split(1, 3, value)
tf.shape(split0) ⇒ [5, 10]

# embedding
mat = np.array([1,2,3,4,5,6,7,8,9]).reshape((3, -1))
ids = [[1,2], [0,1]]
res = tf.nn.embedding_lookup(mat, ids)
res ==> [[[4 5 6], [7 8 9]],
           [[1 2 3], [4 5 6]]]

# 扩展维度,如果想用广播特性的话,经常会用到这个函数

# 't' is a tensor of shape [2]
tf.expand_dims(t, 0).shape ==> [1, 2]
tf.expand_dims(t, 1).shape ==> [2, 1]
tf.expand_dims(t, -1).shape ==> [2, 1]

# 't2' is a tensor of shape [2, 3, 5]
tf.expand_dims(t2, 0).shape ==> [1, 2, 3, 5]
tf.expand_dims(t2, 2).shape ==> [2, 3, 1, 5]
tf.expand_dims(t2, 3).shape ==> [2, 3, 5, 1]

猜你喜欢

转载自blog.csdn.net/wyisfish/article/details/80562999