python


1、

<p>[TOC]</p> <h1>python中@classmethod @staticmethod区别</h1> <p><a href="https://www.cnblogs.com/elie/p/5876210.html">https://www.cnblogs.com/elie/p/5876210.html</a></p> <p>1.定义方式</p> <p>普通的类方法foo()需要通过self参数隐式的传递当前类对象的实例。 @classmethod修饰的方法class_foo()需要通过cls参数传递当前类对象。@staticmethod修饰的方法定义与普通函数是一样的。</p> <p>self和cls的区别不是强制的,只是PEP8中一种编程风格,slef通常用作实例方法的第一参数,cls通常用作类方法的第一参数。即通常用self来传递当前类对象的实例,cls传递当前类对象。</p> <h3>2.绑定对象</h3> <pre><code>foo方法绑定对象A的实例,class_foo方法绑定对象A,static_foo没有参数绑定。 &gt;&gt;&gt; print(a.foo) &lt;bound method A.foo of &lt;__main__.A object at 0x0278B170&gt;&gt; &gt;&gt;&gt; print(a.class_foo) &lt;bound method A.class_foo of &lt;class '__main__.A'&gt;&gt; &gt;&gt;&gt; print(a.static_foo) &lt;function A.static_foo at 0x02780390&gt;</code></pre> <h3>3.调用方式</h3> <p>foo可通过实例a调用,类对像A直接调用会参数错误。</p> <pre><code>&gt;&gt;&gt; a.foo(1) executing foo(&lt;__main__.A object at 0x0278B170&gt;,1) self: &lt;__main__.A object at 0x0278B170&gt; &gt;&gt;&gt; A.foo(1) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: foo() missing 1 required positional argument: 'x'</code></pre> <p>但foo如下方式可以使用正常,显式的传递实例参数a。</p> <pre><code>&gt;&gt;&gt; A.foo(a, 1) executing foo(&lt;__main__.A object at 0x0278B170&gt;,1) self: &lt;__main__.A object at 0x0278B170&gt;</code></pre> <p>class_foo通过类对象或对象实例调用。</p> <pre><code>&gt;&gt;&gt; A.class_foo(1) executing class_foo(&lt;class '__main__.A'&gt;,1) cls: &lt;class '__main__.A'&gt; &gt;&gt;&gt; a.class_foo(1) executing class_foo(&lt;class '__main__.A'&gt;,1) cls: &lt;class '__main__.A'&gt;</code></pre> <p>static_foo通过类对象或对象实例调用。</p> <pre><code>&gt;&gt;&gt; A.static_foo(1) executing static_foo(1) &gt;&gt;&gt; a.static_foo(1) executing static_foo(1)</code></pre> <h3>4.继承与覆盖普通类函数是一样的。</h3> <pre><code>class B(A): pass b = B() b.foo(1) b.class_foo(1) b.static_foo(1) # executing foo(&lt;__main__.B object at 0x007027D0&gt;,1) # self: &lt;__main__.B object at 0x007027D0&gt; # executing class_foo(&lt;class '__main__.B'&gt;,1) # cls: &lt;class '__main__.B'&gt; # executing static_foo(1)</code></pre> <p>问题:@staticmethod修饰的方法函数与普通的类外函数,为什么不直接使用普通函数? @staticmethod是把函数嵌入到类中的一种方式,函数就属于类,同时表明函数不需要访问这个类。通过子类的继承覆盖,能更好的组织代码。</p> <p>参考:<a href="http://stackoverflow.com/questions/136097/what-is-the-difference-between-staticmethod-and-classmethod-in-python">What is the difference between @staticmethod and @classmethod in Python?</a></p> <h1>tf.nn.embedding_lookup函数的用法</h1> <p><a href="https://www.jianshu.com/p/abea0d9d2436">https://www.jianshu.com/p/abea0d9d2436</a></p> <p><strong>关于np.random.RandomState、np.random.rand、np.random.random、np.random_sample参考https://blog.csdn.net/lanchunhui/article/details/50405670</strong></p> <p>tf.nn.embedding_lookup函数的用法主要是选取一个张量里面索引对应的元素。tf.nn.embedding_lookup(params, ids):params可以是张量也可以是数组等,id就是对应的索引,其他的参数不介绍。</p> <p>例如:</p> <p><strong>ids只有一行:</strong></p> <pre><code>#c = np.random.random([10, 1]) # 随机生成一个10*1的数组 #b = tf.nn.embedding_lookup(c, [1, 3])#查找数组中的序号为1和3的 p=tf.Variable(tf.random_normal([10,1]))#生成10*1的张量 b = tf.nn.embedding_lookup(p, [1, 3])#查找张量中的序号为1和3的 with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print(sess.run(b)) #print(c) print(sess.run(p)) print(p) print(type(p))</code></pre> <p>  </p> <p>输出:</p> <pre><code>[[0.15791859] [0.6468804 ]] [[-0.2737084 ] [ 0.15791859] [-0.01315552] [ 0.6468804 ] [-1.4090979 ] [ 2.1583703 ] [ 1.4137447 ] [ 0.20688428] [-0.32815856] [-1.0601649 ]] &lt;tf.Variable 'Variable:0' shape=(10, 1) dtype=float32_ref&gt; &lt;class 'tensorflow.python.ops.variables.Variable'&gt;</code></pre> <p> 分析:输出为张量的第一和第三个元素。</p> <p><strong>如果ids是多行:</strong></p> <pre><code>import tensorflow as tf import numpy as np a = [[0.1, 0.2, 0.3], [1.1, 1.2, 1.3], [2.1, 2.2, 2.3], [3.1, 3.2, 3.3], [4.1, 4.2, 4.3]] a = np.asarray(a) idx1 = tf.Variable([0, 2, 3, 1], tf.int32) idx2 = tf.Variable([[0, 2, 3, 1], [4, 0, 2, 2]], tf.int32) out1 = tf.nn.embedding_lookup(a, idx1) out2 = tf.nn.embedding_lookup(a, idx2) init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) print sess.run(out1) print out1 print '==================' print sess.run(out2) print out2</code></pre> <p>输出</p> <pre><code>[[ 0.1 0.2 0.3] [ 2.1 2.2 2.3] [ 3.1 3.2 3.3] [ 1.1 1.2 1.3]] Tensor("embedding_lookup:0", shape=(4, 3), dtype=float64) ================== [[[ 0.1 0.2 0.3] [ 2.1 2.2 2.3] [ 3.1 3.2 3.3] [ 1.1 1.2 1.3]] [[ 4.1 4.2 4.3] [ 0.1 0.2 0.3] [ 2.1 2.2 2.3] [ 2.1 2.2 2.3]]] Tensor("embedding_lookup_1:0", shape=(2, 4, 3), dtype=float64) </code></pre> <pre><code>若 a 50000*300 idx1为 5*3 b = tf.nn.embedding_lookup(a, idx1) 则 b 的shape= 5*3*300 </code></pre> <h1>python pandas stack和unstack函数</h1> <p>在用pandas进行数据重排时,经常用到stack和unstack两个函数。stack的意思是堆叠,堆积,unstack即“不要堆叠”,我对两个函数是这样理解和区分的。</p> <p>  常见的数据的层次化结构有两种,一种是表格,一种是“花括号”,即下面这样的l两种形式:</p> <table> <thead> <tr> <th></th> <th>store1</th> <th>store2</th> <th>store3</th> </tr> </thead> <tbody> <tr> <td>street1</td> <td>1</td> <td>2</td> <td>3</td> </tr> <tr> <td>street2</td> <td>4</td> <td>5</td> <td>6</td> </tr> </tbody> </table> <p>​ <img src="https://images2017.cnblogs.com/blog/1153897/201710/1153897-20171013213916309-1610254152.png" alt="img" /></p> <p>  表格在行列方向上均有索引(类似于DataFrame),花括号结构只有“列方向”上的索引(类似于层次化的Series),结构更加偏向于堆叠(Series-stack,方便记忆)。stack函数会将数据从”表格结构“变成”花括号结构“,即将其行索引变成列索引,反之,unstack函数将数据从”花括号结构“变成”表格结构“,即要将其中一层的列索引变成行索引。例:</p> <pre><code>import numpy as np import pandas as pd from pandas import Series,DataFrame data=DataFrame(np.arange(6).reshape((2,3)),index=pd.Index(['street1','street2']),columns=pd.Index(['one','two','three'])) print(data) print('-----------------------------------------\n') data2=data.stack() data3=data2.unstack() print(data2) print('-----------------------------------------\n') print(data3)</code></pre> <p>·打印结果如下:使用stack函数,将data的行索引['one','two','three’]转变成列索引(第二层),便得到了一个层次化的Series(data2),使用unstack函数,将data2的第二层列索引转变成行索引(默认的,可以改变),便又得到了DataFrame(data3)。</p> <p><img src="https://images2017.cnblogs.com/blog/1153897/201710/1153897-20171012213543402-1226924570.png" alt="img" /></p> <hr /> <hr /> <h1>tensorflow bias_add应用</h1> <h1><a href="https://www.cnblogs.com/lovephysics/p/7222022.html">tensorflow bias_add应用</a></h1> <p><img src="https://images2015.cnblogs.com/blog/1204043/201707/1204043-20170722172730121-1672823306.png" alt="img" /></p> <pre><code>import tensorflow as tf a=tf.constant([[1,1],[2,2],[3,3]],dtype=tf.float32) b=tf.constant([1,-1],dtype=tf.float32) c=tf.constant([1],dtype=tf.float32) with tf.Session() as sess: print('bias_add:') print(sess.run(tf.nn.bias_add(a, b))) #执行下面语句错误 #print(sess.run(tf.nn.bias_add(a, c))) print('add:') print(sess.run(tf.add(a, c)))</code></pre> <p>输出结果:</p> <p>bias_add: [[ 2. 0.] [ 3. 1.] [ 4. 2.]] add: [[ 2. 2.] [ 3. 3.] [ 4. 4.]]</p> <p><img src="https://images2015.cnblogs.com/blog/1204043/201707/1204043-20170722172927434-441164955.png" alt="img" /></p> <h1>Tensorflow tf.multiply函数与tf.matmul函数用法和区别</h1> <p>在tensorflow中高频率的用到这两个函数,整理一下各自的用法和区别:</p> <pre><code>tensorflow.multiply(x, y, name=None) </code></pre> <p>参数: x: 类型为:half, float32, float64, uint8, int8, uint16, int16, int32, int64, complex64, complex128的张量。 y: 类型跟张量x相同的张量。 name: 操作的名字(可选参数) 返回值(元素级别的相乘): x * y element-wise 注意: (1)multiply这个函数实现的是元素级别的相乘,也就是两个相乘的数元素各自相乘,而不是矩阵乘法,注意和tf.matmul区别。 (2)两个相乘的数必须有相同的数据类型,否则就会报错</p> <pre><code>tf.matmul(a, b, transpose_a=False, transpose_b=Falsint_a=False, adjoint_b=False, a_is_sparse=False, b_is_sparse=False, name=None) ) </code></pre> <p>参数: a: 类型为 float16, float32, float64, int32, complex64, complex128 且张量秩 &gt; 1 的张量。 b: 类型跟张量a相同的张量。 <strong>transpose_a: 如果为真, a则在进行乘法计算前进行转置。 transpose_b: 如果为真, b则在进行乘法计算前进行转置。 adjoint_a: 如果为真, a则在进行乘法计算前进行共轭和转置。 adjoint_b: 如果为真, b则在进行乘法计算前进行共轭和转置。 a_is_sparse: 如果为真, a会被处理为稀疏矩阵。 b_is_sparse: 如果为真, b会被处理为稀疏矩阵。 </strong> name: 操作的名字(可选参数) 返回值: 一个跟张量a和张量b类型一样的张量,且最内部矩阵是a和b中的相应矩阵的乘积。 注意: (1)输入必须是矩阵(或者是张量秩 &gt;2的张量,表示成批的矩阵),并且其在转置之后有相匹配的矩阵尺寸。 (2)两个矩阵必须都是同样的类型,支持的类型如下:float16, float32, float64, int32, complex64, complex128。 引发错误: ValueError: 如果transpose_a 和 adjoint_a, 或 transpose_b 和 adjoint_b 都被设置为真</p> <p>作者:skyHdd 来源:CSDN 原文:<a href="https://blog.csdn.net/u010591976/article/details/82252522">https://blog.csdn.net/u010591976/article/details/82252522</a> 版权声明:本文为博主原创文章,转载请附上博文链接!</p> <h1>TensorFlow函数:tf.truncated_normal_initializer</h1> <h2>tf.truncated_normal_initializer函数</h2> <h3>truncated_normal_initializer类</h3> <p>别名:</p> <ul> <li>tf.initializers.truncated_normal类 </li> <li>tf.keras.initializers.TruncatedNormal类</li> <li>tf.truncated_normal_initializer类</li> </ul> <p>定义在:<a href="https://www.w3cschool.cn/tensorflow_python/tensorflow_python-tezr2d4u.html">tensorflow/python/ops/init_ops.py</a>.</p> <p>请参阅指南:<a href="https://www.w3cschool.cn/tensorflow_python/tensorflow_python-rv8u2c6g.html">变量&gt;共享变量</a></p> <p>生成截断正态分布的初始化程序.</p> <p>这些值与来自 random_normal_initializer 的值类似,不同之处在于值超过两个标准偏差值的值被丢弃并重新绘制.这是推荐的用于神经网络权值和过滤器的初始化器.</p> <p>函数参数:</p> <ul> <li>mean:一个 python 标量或一个标量张量,要生成的随机值的均值.</li> <li>stddev:一个 python 标量或一个标量张量,要生成的随机值的标准偏差.</li> <li>seed:一个 Python 整数,用于创建随机种子.查看<a href="https://www.w3cschool.cn/tensorflow_python/tensorflow_python-fqc42jvo.html">tf.set_random_seed</a>行为.</li> <li>dtype:数据类型,仅支持浮点类型.</li> </ul> <h3>tf.truncated_normal_initializer方法</h3> <h4><strong>init</strong></h4> <pre><code>__init__( mean=0.0, stddev=1.0, seed=None, dtype=tf.float32 )</code></pre> <h4><strong>call</strong></h4> <pre><code>__call__( shape, dtype=None, partition_info=None )</code></pre> <h4>from_config</h4> <pre><code>from_config( cls, config )</code></pre> <p>从配置字典中实例化初始化程序. </p> <p>示例:</p> <pre><code>initializer = RandomUniform(-1, 1) config = initializer.get_config() initializer = RandomUniform.from_config(config)</code></pre> <p>参数:</p> <ul> <li>config:一个 Python 字典,它通常是 get_config的输出. </li> </ul> <p>返回:</p> <p>一个初始化实例.</p> <h4>get_config</h4> <pre><code>get_config()</code></pre> <h1>tf.Variable和tf.get_variable的区别</h1> <h1>Variable</h1> <p>tensorflow中有两个关于variable的op,<code>tf.Variable()</code>与<code>tf.get_variable()</code>下面介绍这两个的区别</p> <h2>tf.Variable与tf.get_variable()</h2> <pre><code class="language-python">tf.Variable(initial_value=None, trainable=True, collections=None, validate_shape=True, caching_device=None, name=None, variable_def=None, dtype=None, expected_shape=None, import_scope=None)11 tf.get_variable(name, shape=None, dtype=None, initializer=None, regularizer=None, trainable=True, collections=None, caching_device=None, partitioner=None, validate_shape=True, custom_getter=None)11</code></pre> <h2>区别</h2> <ol> <li>使用<code>tf.Variable</code>时,如果检测到命名冲突,系统会自己处理。使用<code>tf.get_variable()</code>时,系统不会处理冲突,而会报错</li> </ol> <pre><code class="language-python">import tensorflow as tf w_1 = tf.Variable(3,name="w_1") w_2 = tf.Variable(1,name="w_1") print w_1.name print w_2.name #输出 #w_1:0 #w_1_1:01234567812345678 import tensorflow as tf w_1 = tf.get_variable(name="w_1",initializer=1) w_2 = tf.get_variable(name="w_1",initializer=2) #错误信息 #ValueError: Variable w_1 already exists, disallowed. Did #you mean to set reuse=True in VarScope?12345671234567</code></pre> <ol> <li>基于这两个函数的特性,当我们需要共享变量的时候,需要使用<code>tf.get_variable()</code>。在其他情况下,这两个的用法是一样的</li> </ol> <h2>get_variable()与Variable的实质区别</h2> <p>来看下面一段代码:</p> <pre><code class="language-python">import tensorflow as tf with tf.variable_scope("scope1"): w1 = tf.get_variable("w1", shape=[]) w2 = tf.Variable(0.0, name="w2") with tf.variable_scope("scope1", reuse=True): w1_p = tf.get_variable("w1", shape=[]) w2_p = tf.Variable(1.0, name="w2") print(w1 is w1_p, w2 is w2_p) #输出 #True False123456789101112123456789101112</code></pre> <p>看到这,就可以明白官网上说的参数复用的真面目了。由于<code>tf.Variable()</code> 每次都在创建新对象,所有<code>reuse=True</code> 和它并没有什么关系。对于<code>get_variable()</code>,来说,如果已经创建的变量对象,就把那个对象返回,如果没有创建变量对象的话,就创建一个新的。</p> <h2>random Tensor</h2> <p>可用于赋值给<code>tf.Variable()</code>的第一个参数</p> <pre><code class="language-python">tf.random_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None) tf.truncated_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None) tf.random_uniform(shape, minval=0, maxval=None, dtype=tf.float32, seed=None, name=None) tf.random_shuffle(value, seed=None, name=None) tf.random_crop(value, size, seed=None, name=None) tf.multinomial(logits, num_samples, seed=None, name=None) tf.random_gamma(shape, alpha, beta=None, dtype=tf.float32, seed=None, name=None) tf.set_random_seed(seed)123456789101112131415123456789101112131415</code></pre> <h2>constant value tensor</h2> <pre><code class="language-python">tf.zeros(shape, dtype=tf.float32, name=None) tf.zeros_like(tensor, dtype=None, name=None) tf.ones(shape, dtype=tf.float32, name=None) tf.ones_like(tensor, dtype=None, name=None) tf.fill(dims, value, name=None) tf.constant(value, dtype=None, shape=None, name='Const')12345678910111234567891011</code></pre> <h2>initializer</h2> <pre><code class="language-python">tf.constant_initializer(value=0, dtype=tf.float32) tf.random_normal_initializer(mean=0.0, stddev=1.0, seed=None, dtype=tf.float32) tf.truncated_normal_initializer(mean=0.0, stddev=1.0, seed=None, dtype=tf.float32) tf.random_uniform_initializer(minval=0, maxval=None, seed=None, dtype=tf.float32) tf.uniform_unit_scaling_initializer(factor=1.0, seed=None, dtype=tf.float32) tf.zeros_initializer(shape, dtype=tf.float32, partition_info=None) tf.ones_initializer(dtype=tf.float32, partition_info=None) tf.orthogonal_initializer(gain=1.0, dtype=tf.float32, seed=None)1234567812345678</code></pre> <p><strong>参考资料</strong> <a href="https://www.tensorflow.org/api_docs/python/state_ops/variables#Variable">https://www.tensorflow.org/api_docs/python/state_ops/variables#Variable</a> <a href="https://www.tensorflow.org/api_docs/python/state_ops/sharing_variables#get_variable">https://www.tensorflow.org/api_docs/python/state_ops/sharing_variables#get_variable</a> <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/constant_op/">https://www.tensorflow.org/versions/r0.10/api_docs/python/constant_op/</a> <a href="https://www.tensorflow.org/api_docs/python/state_ops/">https://www.tensorflow.org/api_docs/python/state_ops/</a></p>

页面列表

ITEM_HTML