Tensorflow与Python之细枝末节

来源:互联网 发布:阿里云工商数据查询 编辑:程序博客网 时间:2024/06/07 07:11

本文将对Tensorflow中的一些细枝末节进行总结。

  • Variables与constant的区别

    Constant一般是常量,可以被赋值给Variables,constant保存在graph中,如果graph重复载入那么constant也会重复载入,其非常浪费资源,如非必要尽量不使用其保存大量数据。而Variables在每个session中都是单独保存的,甚至可以单独存在一个参数服务器上。可以通过代码观察到constant实际是保存在graph中,具体如下。

  import tensorflow as tf  a = tf.constant(2, name = "constant")  print(tf.get_default_graph().as_graph_def())

这里写图片描述

  • placeholder占位符

    placeholder,中文意思是占位符,当然placeholder也是一个tensor,可以接受任何维度的tensor数据,比如向量,矩阵,图像等

x = tf.placeholder(tf.float32, [2, 3], name='x-input')

其中,第一个参数是你要保存的数据的数据类型,第二个参数就是要保存数据的结构,第三个参数则是该变量的名称,它在使用的时候和前面的variable不同的是在session运行阶段,需要给placeholder提供数据,利用feed_dict的字典结构给placeholdr变量赋值,具体如下:

import tensorflow as tfa = tf.placeholder(tf.float32)b = tf.placeholder(tf.float32)c = tf.add(a, b)with tf.Session() as sess:    print(sess.run(c, feed_dict={a:10, b:30})) #把10赋给a,30赋给b
  • With…as语句(python)

    有这么一行语句:

with open('filename', 'wt') as f:      f.write('hello, world!')  

这条处理语句是处理异常的语句,是下面这行语句的改进版:

f= open('filename', 'wt')try:    data = f.write('hello, world!')finally:    file.close()

通过下面的代码,我们来了解with…as语句的执行顺序

class Sample:    def __enter__(self):        print("_enter")        return "Foo"    def __exit__(self, exc_type, exc_val, exc_tb):        print("_exit")def get_sample():    return Sample()with get_sample() as sample:        print("sample", sample)

基本思想是with所求值的对象必须有一个enter()方法,一个exit()方法。紧跟with后面的语句被求值后,返回对象的enter()方法被调用,这个方法的返回值将被赋值给as后面的变量。当with后面的代码块全部被执行完之后,将调用前面返回对象的exit()方法。

  • 正则(regularizer)

    tf.contrib.layers.l1_regularizer(scale, scope=None)

    返回一个用来执行L1正则化的函数,函数的签名是func(weights).
    参数:

    scale: 正则项的系数.

    scope: 可选的scope name

    tf.contrib.layers.l2_regularizer(scale, scope=None)

    返回一个执行L2正则化的函数.

    tf.contrib.layers.sum_regularizer(regularizer_list, scope=None)

    返回一个可以执行多种(个)正则化的函数.意思是,创建一个正则化方法,这个方法是多个正则化方法的混合体