Python Practice Series

Python standard library

Numpy tutorial

Tensorflow API

 

Catalog

1, yield:

2, tf.constant:

3, tf.stack and tf.unstack:

4, tf.tensordot:

5, For multiple class arrays of the same dimension, the order is scrambled at the same time, but the one-to-one correspondence between them is maintained:

6, Get the path os.path.dirname(os.path.realpath(sys.argv[0]) of the currently opened file:

7, A simple example of modifying the names of all files in a folder os.rename:

8, When python executes a certain program, it is stuck all the time for unknown reasons and does not report an error to exit. You can set the timeout to skip the execution of this part. func_timeout.func_set_timeout(1, False)

9, To view the version of a library in code writing:

10, signal.argrelextrema looks for local maximum and minimum values:

1, yield:

In a function, when the result of a loop passes through yield, the function is no longer a normal function, it becomes a generator function, and the result returned is a generator. Then, you can get the value of each iteration through the s. \\\\\\\\\\\. The advantage of doing so is to save memory. For example, for the following code, every time you call "next" (), the code before yield will be executed, until yield, it will be suspended, and the next time you call "next" (), it will continue to execute at the last place until yield.

def f():
    for i in range(3):
        yield i
s = f()
print(s.__next__())   #Or next(s)
print(s.__next__())   #Or next(s)
print(s.__next__())   #Or next(s)

2, tf.constant:

Create a constant sensor.

import tensorflow as tf;
import numpy as np;
t1 = tf.constant(value=[1, 2.2, 3, 5e-3], 
                 dtype=None, 
                 shape=None, 
                 name="Const", 
                 verify_shape=False)
with tf.Session() as sess:
    print(sess.run(t1))  #output: [1.    2.2   3.    0.005]

3, tf.stack and tf.unstack:

tf.stack([x, y, z]) is equivalent to np.stack([x, y, z]), which is used to stack multiple sensors of the same shape together according to the specified dimension. In contrast, tf.unstack, assuming t.shape = (A,B,C), then tf.unstack(t,axis=0) is equivalent to decomposing t into A (B,C) combined list.

#coding=utf-8
import tensorflow as tf;
import numpy as np;
x = tf.constant([1, 4])
y = tf.constant([2, 5])
z = tf.constant([3, 6])

s1 = tf.stack(values=[x, y, z],
         axis=0,
         name="stack")  # [[1, 4], [2, 5], [3, 6]]
s2 = tf.stack([x, y, z], axis=1)  # [[1, 2, 3], [4, 5, 6]]

s3 = tf.unstack(value=s1,    
                num=None, 
                axis=0, 
                name="unstack")
with tf.Session() as sess:
    print(sess.run(s1))  #output: [[1 4] [2 5] [3 6]]
    print(sess.run(s2))  #output: [[1 2 3] [4 5 6]]
    print(sess.run(s3))  #output: [array([1, 4]), array([2, 5]), array([3, 6])]

4, tf.tensordot:

At present, we know that the value in the first tensor is multiplied by the value in the second tensor. For example, when axes is 0, the first tensor is [1,2], and the second is [4,5,6]. Their result is a new tensor which is a combination of the results of multiplying 1 by [4,5,6] and multiplying 2 by [4,5,6] respectively.

#coding=utf-8
import tensorflow as tf;
import numpy as np;
from openpyxl.styles.builtins import output
t = tf.constant([1,2])
t1 = tf.constant([4,5,6])
t2 = tf.tensordot(t, t1, axes=0)
with tf.Session() as sess:
    print(sess.run(t2))
'''    
output: 
    [[ 4  5  6]
     [ 8 10 12]]
'''

5, For multiple class arrays of the same dimension, the order is scrambled at the same time, but the one-to-one correspondence between them is maintained:

#coding=utf-8
'''Disorder the order of multiple class arrays of the same dimension at the same time, but keep the one-to-one correspondence between them'''
import numpy as np
a = np.array([1,2,3,4])
b = np.array([5,6,7,8])
size = a.shape[0]
size = np.arange(size)
print(size)  #[0 1 2 3]
np.random.shuffle(size)
print(size)  #[2 3 0 1]
print(a[size])  #[3 4 1 2]
print(b[size])  #[7 8 5 6]

6, Get the path os.path.dirname(os.path.realpath(sys.argv[0]) of the currently opened file:

#coding=utf-8
import os
import sys
s = os.path.dirname(os.path.realpath(sys.argv[0]))
print(s)  #Output the absolute path of your current file

7, A simple example of modifying the names of all files in a folder os.rename:

#coding=utf-8
import os
fileDir = r'E:\test'  #Original folder
fileList = os.listdir(fileDir)  #Save the file name under the folder into the list
for i, f in enumerate(fileList):  #Traverse every file
    srcName = os.path.join(fileDir, f)  #Original filename (absolute path)
    newFileName = str(i) + "_" + f.split("_")[0] + ".jpg"  #New file name. The new file name depends on the situation. The example here is convenient for me to use
    dstName = os.path.join(fileDir, newFileName)  #New filename (absolute path)
    os.rename(src=srcName, dst=dstName)  #Rename (old name, new name)

8, When python executes a certain program, it is stuck all the time for unknown reasons and does not report an error to exit. You can set the timeout to skip the execution of this part. func_timeout.func_set_timeout(1, False)

Reprinted from: Python function timeout, use decorator to solve func "timeout

#coding=utf-8
from func_timeout import func_set_timeout, FunctionTimedOut
import time
@func_set_timeout(timeout=0.1, allowOverride=False)  #If the setting time exceeds 0.1s, it will time out
def task():
    while True:
        print("Hello world")
        time.sleep(1)
if __name__ == '__main__':
    try:
        task()
    except FunctionTimedOut: #If the running time of some part of the program exceeds the set time, a FunctionTimedOut exception will be thrown
        print("Overtime")       #After the write timeout, the code to be executed next

9, To view the version of a library in code writing:

import numpy
print(numpy.__version__)

10, signal.argrelextrema looks for local maximum and minimum values:

from scipy import signal

#Calculating the index of the local maximum of one-dimensional array
y = np.array([3,5,8,3,6,1])
local_max_index = signal.argrelextrema(y, np.greater) 
print(local_max_index)  #output:(array([2, 4], dtype=int64),)
local_max_index = signal.argrelextrema(y, np.greater)[0] #Add [0] to return only the numerical part
print(local_max_index) #output:[2 4]

#Calculating the index of the local minimum of one-dimensional array
x = np.array([6,2,8,7,3,9])
local_min_index = signal.argrelextrema(x, np.less)
print(local_min_index)  #output:(array([1, 4], dtype=int64),)
local_min_index = signal.argrelextrema(x, np.less)[0] #Add [0] to return only the numerical part
print(local_min_index) #output:[1 4]

#Calculate the index of the local maximum of the two-dimensional array; axis=0, indicating the comparison between rows
y = np.array([[1, 2, 1, 2], [6, 6, 4, 0], [3, 6, 3, 4]])
local_max_index = signal.argrelextrema(y, np.greater, axis=0) #Default axis=0, which means the comparison between rows
print(local_max_index)  
#output:(array([1, 1], dtype=int64), array([0, 2], dtype=int64)), the first term refers to the index of the local maximum in a column, and the second term refers to the column of the local maximum
local_max_index = signal.argrelextrema(y, np.greater, axis=0)[0] #Add [0] to return the index of the local maximum in a column, and add [1] to return the column of the local maximum
print(local_max_index) #output:[1 1]

#Calculate the index of the local maximum of the two-dimensional array; axis=1, indicating the comparison between columns
y = np.array([[1, 2, 1, 2], [6, 6, 4, 0], [3, 6, 3, 4]])
local_max_index = signal.argrelextrema(y, np.greater, axis=1) 
print(local_max_index)  
#output:(array([0, 2], dtype=int64), array([1, 1], dtype=int64)), the first term refers to the index of the local maximum in a row, and the second term refers to the row of the local maximum
local_max_index = signal.argrelextrema(y, np.greater, axis=1)[0] #Add [0] to return only the numerical part
print(local_max_index) #output:[0 2]

#The calculation of the index of the local minimum of the two-dimensional array is the same as above, only changing np.greater to np.less.

 

 

                                                            . . .          . . .

Published 14 original articles, won praise 19, visited 10000+
Private letter follow

Tags: Python Session less

Posted on Mon, 13 Jan 2020 19:38:43 -0800 by arion279