您當前的位置:首頁 > 攝影

即插即用的簡單知識點(持續更新)

作者:由 應鐘有微 發表于 攝影時間:2022-11-19

0。 np。row_stack和 np。column_stack:向矩陣中新增行或列

a = np。array([[1,2,3],

[4,5,6]])

b = [7,8,9]

print (np。row_stack((a,b)))

輸出:

[[1 2 3]

[4 5 6]

[7 8 9]]

a = np。array([[1,2,3],

[4,5,6]])

b = [7,8]

print (np。column_stack((a,b)))

輸出:

[[1 2 3 7]

[4 5 6 8]]

1。tf。nn。dropout(x, keep_prob, noise_shape=None, seed=None, name=None)

x:訓練、測試資料

keep_prob:保留比例

注:輸出的非0元素是原來的 “1/keep_prob” 倍

example:

import tensorflow as tf

dropout = tf。placeholder(tf。float32)

x = tf。Variable(tf。ones([10, 10]))

y = tf。nn。dropout(x, dropout)

init = tf。initialize_all_variables()

sess = tf。Session()

sess。run(init)

print sess。run(y, feed_dict = {dropout: 0。4})

輸出結果:

[[ 0。 0。 2。5 2。5 0。 0。 2。5 2。5 2。5 2。5]

[ 0。 2。5 2。5 2。5 2。5 2。5 0。 2。5 0。 2。5]

[ 2。5 0。 0。 2。5 0。 0。 2。5 0。 2。5 0。 ]

[ 0。 2。5 2。5 2。5 2。5 0。 0。 2。5 0。 2。5]

[ 0。 0。 0。 0。 0。 0。 0。 0。 2。5 2。5]

[ 2。5 2。5 2。5 0。 2。5 0。 0。 2。5 2。5 2。5]

[ 0。 2。5 2。5 2。5 0。 2。5 2。5 0。 0。 0。 ]

[ 0。 2。5 0。 2。5 0。 0。 2。5 2。5 0。 0。 ]

[ 2。5 2。5 2。5 2。5 2。5 0。 0。 2。5 0。 0。 ]

[ 2。5 0。 0。 0。 0。 0。 2。5 2。5 0。 2。5]]

2。tf。gather:把矩陣中某些索引值提取出來,得到新的矩陣,用於要提取的索引為不連續的情況

import tensorflow as tf

a = tf。Variable([[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15]])

index_a = tf。Variable([0,2])

with tf。Session() as sess:

sess。run(tf。global_variables_initializer())

print(sess。run(tf。gather(a, index_a)))

輸出結果:

[[ 1 2 3 4 5]

[11 12 13 14 15]]

3。python map函式:根據提供的函式對指定序列做對映

print (list(map(lambda x: x % 2, range(7))))

輸出結果:

[0, 1, 0, 1, 0, 1, 0]

注意:

Python 2。x 返回列表。

Python 3。x 返回迭代器。

4。tf。equal:對比兩個矩陣或者向量元素,如果相等就返回True,否則返回False。

import tensorflow as tf

import numpy as np

A = [[1,3,4,5,6]]

B = [[1,3,4,3,2]]

with tf。Session() as sess:

print(sess。run(tf。equal(A, B)))

輸出:

[[ True True True False False]]

5。

tf。argmax(input, axis=None, name=None, dimension=None)

:對矩陣按行或列取最大值索引

import tensorflow as tf

a=tf。get_variable(name=‘a’,

shape=[3,4],

dtype=tf。float32,

initializer=tf。random_uniform_initializer(minval=-1,maxval=1))

b=tf。argmax(input=a,axis=0)

c=tf。argmax(input=a,dimension=1) #此處用dimesion或用axis是一樣的

sess = tf。InteractiveSession()

sess。run(tf。initialize_all_variables())

print(sess。run(a))

#[[ 0。04261756 -0。34297419 -0。87816691 -0。15430689]

# [ 0。18663144 0。86972666 -0。06103253 0。38307118]

# [ 0。84588599 -0。45432305 -0。39736366 0。38526249]]

print(sess。run(b))

print(sess。run(c))

輸出:

[2 1 1 2]

[0 1 0]

6。tf。cast:用於改變某個張量的資料型別

import tensorflow as tf;

import numpy as np;

A = tf。convert_to_tensor(np。array([[1,1,2,4], [3,4,8,5]]))

with tf。Session() as sess:

print A。dtype

b = tf。cast(A, tf。float32)

print b。dtype

輸出結果:

7。numpy。random。shuffle(x):將序列的所有元素隨機排序,直接在原來的陣列上進行操作,改變原來陣列的順序,無返回值

np。random。permutation(x):將序列的所有元素隨機排序,permutation不直接在原來的陣列上進行操作,而是返回一個新的打亂順序的陣列,並不改變原來的陣列。

a = np。arange(12)

print a

np。random。shuffle(a)

print a

a = np。arange(12)

print a

b = np。random。permutation(a)

print b

print a

輸出:

[ 0 1 2 3 4 5 6 7 8 9 10 11]

[11 6 4 10 3 0 7 1 9 2 5 8]

[ 0 1 2 3 4 5 6 7 8 9 10 11]

[10 4 8 11 1 7 6 2 0 9 5 3]

[ 0 1 2 3 4 5 6 7 8 9 10 11]

8。python zip:將可迭代的物件作為引數,將物件中對應的元素打包成一個個元組,然後返回由這些元組組成的物件,我們可以使用 list() 轉換來輸出列表

python zip(*):將tuple組成的list(dict等)拆分成多個tuple

a = [1,2]

b = [3,4]

c = list(zip(a,b))

d, e = zip(*c)

print (c)

print (d)

print (e)

輸出:

[(1, 3), (2, 4)]

(1, 2)

(3, 4)

9。tf。reduce_max(input_tensor, reduction_indices=None, keep_dims=False, name=None):在指定維度上(reduction_indices)取最大值,keep_dims引數表示是否保持原來的維度。

import numpy as np

d_scores[0] = [[[1,2],[3,4],[5,6]],[[7,8],[9,10],[11,12]]]

scores = tf。reduce_max(d_scores[0],axis=2)

scores1 = tf。reduce_max(d_scores[0],axis=2,keep_dims=True)

with tf。Session() as sess:

print(scores。eval())

print(scores1。eval())

輸出:

[[ 2 4 6]

[ 8 10 12]]

[[[ 2]

[ 4]

[ 6]]

[[ 8]

[10]

[12]]]

10。tf。sequence_mask

sq_mask = tf。sequence_mask([1, 3, 2], 5)

with tf。Session() as sess:

print (sess。run(sq_mask))

輸出:

[[ True False False False False]

[ True True True False False]

[ True True False False False]]

11。str。join(sequence):將序列中的元素以指定的字元連線生成一個新的字串

s1 = “-”

s2 = “”

seq = (“r”, “u”, “n”, “o”, “o”, “b”) # 字串序列

print (s1。join( seq ))

print (s2。join( seq ))

輸出:

r-u-n-o-o-b

runoob

12。tf。expand_dims():在第axis位置增加一個維度

# ‘t’ is a tensor of shape [2]

shape(expand_dims(t, 0)) ==> [1, 2]

shape(expand_dims(t, 1)) ==> [2, 1]

shape(expand_dims(t, -1)) ==> [2, 1]

# ‘t2’ is a tensor of shape [2, 3, 5]

shape(expand_dims(t2, 0)) ==> [1, 2, 3, 5]

shape(expand_dims(t2, 2)) ==> [2, 3, 1, 5]

shape(expand_dims(t2, 3)) ==> [2, 3, 5, 1]

13。Python strip():移除字串頭尾指定的字元(預設為空格或換行符)或字元序列

str = “00000003210Runoob01230000000”;

print str。strip( ‘0’ ); # 去除首尾字元 0

str2 = “ Runoob ”; # 去除首尾空格

print str2。strip();

輸出:

3210Runoob0123

Runoob

14。tf。assign(A, new_number): 把A的值變為new_number

import

tensorflow

as

tf

A

=

tf

Variable

tf

constant

0。0

),

dtype

=

tf

float32

with

tf

Session

()

as

sess

sess

run

tf

initialize_all_variables

())

print

sess

run

A

sess

run

tf

assign

A

10

))

print

sess

run

A

輸出

0。0

10。0

15。os。listdir(path):返回指定的資料夾包含的檔案或資料夾的名字的列表。這個列表以字母順序。 它不包括 ‘。’ 和‘。。’ ,即使它在資料夾中。

import os

path = “。/sxl” #sxl檔案中有三個文字檔案:1。txt,2。txt,3。txt

dirs = os。listdir( path )

for file in dirs:

print file

輸出:

1。txt

2。txt

3。txt

16。nltk。sent_tokenize(text) :按句子分割

nltk。word_tokenize(sentence) :分詞

import nltk

text = “This is a cat。 And it is beautiful。”

sen = nltk。sent_tokenize(text)

word = [nltk。word_tokenize(sent) for sent in sen]

print (sen)

print (word)

輸出:

[‘This is a cat。’, ‘And it is beautiful。’]

[[‘This’, ‘is’, ‘a’, ‘cat’, ‘。’], [‘And’, ‘it’, ‘is’, ‘beautiful’, ‘。’]]

17。np。identity(n, dtype=None):只能獲取方陣

np。eye(N, M=None, k=0, dtype=< class‘float’>, order=’C’):N代表行數,M代表列數,k 可選,代表對角線索引,預設值0是指主對角線,正值是指上對角線,而負值是指向下對角線,order 可選{‘C’, ‘F’},代表記憶體中以行儲存還是以列儲存。

import numpy as np

print (np。identity(3))

print (np。eye(3, k=1))

結果:

[[ 1。 0。 0。]

[ 0。 1。 0。]

[ 0。 0。 1。]]

[[ 0。 1。 0。]

[ 0。 0。 1。]

[ 0。 0。 0。]]

18。itertools。chain():給它一個列表如 lists/tuples/iterables,連結在一起;返回iterables物件。

letters = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]

booleans = [1, 0, 1, 0, 0, 1]

print(list(itertools。chain(letters,booleans)))

輸出:

[‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, 1, 0, 1, 0, 0, 1]

19。Counter():計數功能

most_common(n):返回一個TopN列表。如果n沒有被指定,則返回所有元素。當多個元素計數值相同時,排列是無確定順序的。

from collections import Counter

c = Counter(‘abcasd’)

print(c)

輸出:

Counter({‘a’: 2, ‘c’: 1, ‘b’: 1, ‘s’: 1, ‘d’: 1})

c。most_commom(3)

print (c)

輸出:

[(‘a’, 2), (‘c’, 1), (‘b’, 1)]

20。tf。transpose():將矩陣對應維度進行轉置

看懂該例子即可

import tensorflow as tf

x = [[[1,2,3,4],[5,6,7,8],[9,10,11,12]],[[21,22,23,24],[25,26,27,28],[29,30,31,32]]]

b=tf。transpose(x, [0, 2, 1])

c=tf。transpose(x, [1, 0, 2])

d=tf。transpose(x, [1, 2, 0])

e=tf。transpose(x, [2, 1, 0])

f=tf。transpose(x, [2, 0, 1])

with tf。Session() as sess:

print (sess。run(b))

print (sess。run(c))

print (sess。run(d))

print (sess。run(e))

print (sess。run(f))

輸出:

[[[ 1 5 9]

[ 2 6 10]

[ 3 7 11]

[ 4 8 12]]

[[21 25 29]

[22 26 30]

[23 27 31]

[24 28 32]]]

[[[ 1 2 3 4]

[21 22 23 24]]

[[ 5 6 7 8]

[25 26 27 28]]

[[ 9 10 11 12]

[29 30 31 32]]]

[[[ 1 21]

[ 2 22]

[ 3 23]

[ 4 24]]

[[ 5 25]

[ 6 26]

[ 7 27]

[ 8 28]]

[[ 9 29]

[10 30]

[11 31]

[12 32]]]

[[[ 1 21]

[ 5 25]

[ 9 29]]

[[ 2 22]

[ 6 26]

[10 30]]

[[ 3 23]

[ 7 27]

[11 31]]

[[ 4 24]

[ 8 28]

[12 32]]]

[[[ 1 5 9]

[21 25 29]]

[[ 2 6 10]

[22 26 30]]

[[ 3 7 11]

[23 27 31]]

[[ 4 8 12]

[24 28 32]]]

21。tf。nn。top_k(input, k, name=None):返回 input 中每行最大的 k 個數,並且返回它們所在位置的索引

import tensorflow as tf

import numpy as np

input = tf。constant(np。random。rand(3,4))

k = 2

output = tf。nn。top_k(input, k)

with tf。Session() as sess:

print(sess。run(input))

print(sess。run(output))

輸出:

[[ 0。41838255 0。285235 0。15189788 0。16350887]

[ 0。51574552 0。23891329 0。51110759 0。52498746]

[ 0。94055086 0。40593525 0。55112816 0。10201801]]

TopKV2(values=array([[ 0。41838255, 0。285235 ],

[ 0。52498746, 0。51574552],

[ 0。94055086, 0。55112816]]), indices=array([[0, 1],

[3, 0],

[0, 2]]))

22。tf。pad(tensor,paddings,mode=‘CONSTANT’,name=None):填充。

tensor:要填充的張量;paddings: 也是一個張量,代表每一維填充多少行/列,但是有一個要求,它的秩一定要和tensor的秩是一樣的;mode 可以取三個值,分別是“CONSTANT” ,“REFLECT”,“SYMMETRIC”

import tensorflow as tf

t1 = tf。constant([[1, 2, 3], [4, 5, 6]])

paddings1 = tf。constant([[1, 1], [2, 2]])

t2 = tf。constant([[[1,2,3], [4,5,6], [7,8,9]]])

paddings2 = tf。constant([[1, 0], [2, 1], [1, 2]])

with tf。Session() as sess:

# 例子1 二維

op = tf。pad(t1, paddings1, “CONSTANT”)

print(sess。run(op))

# 例子2 三維

op = tf。pad(t2, paddings2, “CONSTANT”)

print(sess。run(op))

輸出:

[[0 0 0 0 0 0 0]

[0 0 1 2 3 0 0]

[0 0 4 5 6 0 0]

[0 0 0 0 0 0 0]]

[[[0 0 0 0 0 0]

[0 0 0 0 0 0]

[0 0 0 0 0 0]

[0 0 0 0 0 0]

[0 0 0 0 0 0]

[0 0 0 0 0 0]]

[[0 0 0 0 0 0]

[0 0 0 0 0 0]

[0 1 2 3 0 0]

[0 4 5 6 0 0]

[0 7 8 9 0 0]

[0 0 0 0 0 0]]]

23。os。path。exists(path) :path可以為檔案,也可以為目錄;如果存在,返回True;如果不 存在,返回False

os。path。isfile(path):如果path是一個存在的

檔案

,返回True;否則返回False

os。path。isdir(path):如果path是一個存在的

目錄

,則返回True。否則返回False

假設我在桌面新建一個資料夾 a ,在 a 裡新建一個文字檔案 a。txt ,文字檔案路徑為‘C:/Users/sxl/Desktop/a/a。txt’

print (os。path。exists(‘C:/Users/sxl/Desktop/a/a。txt’))

print (os。path。exists(‘C:/Users/sxl/Desktop/a’))

print (os。path。isfile(‘C:/Users/sxl/Desktop/a/a。txt’))

print (os。path。isfile(‘C:/Users/sxl/Desktop/a’))

print (os。path。isdir(‘C:/Users/sxl/Desktop/a/a。txt’))

print (os。path。isdir(‘C:/Users/sxl/Desktop/a’))

輸出:

True #是檔案

True #也是目錄

True #是檔案

False #不是檔案

False #不是目錄

True #是目錄

24。os。path。join():將多個路徑組合後返回

print (os。path。join(‘d:\\library’,‘book’))

輸出:

d:\library\book

25。exec():動態執行python程式碼

這裡僅僅記錄論文復現過程中用到的功能:在一個py檔案中透過exec()函式實現另一個py檔案中的程式碼功能

假設“sxl。py”檔案中的內容是“print (“I ate three eggs morning。”)”

在另一個py檔案中可以透過以下方式實現“sxl。py”檔案中的程式碼功能:

with open(‘E://sxl。py’, ‘r’) as f:

s = f。read()

exec(s)

結果:

I ate three eggs morning。

26。np。save(),np。load():用numpy專用的二進位制格式儲存資料,它們會自動處理元素型別和形狀等資訊。

import numpy as np

a = np。array([[1,2,3],

[4,5,6]])

np。save(“a。npy”, a)

b = np。load(“a。npy”)

print (b)

輸出:

[[1 2 3]

[4 5 6]]

27。

pickle。dump(obj, file[, protocol])

pickle。load(file)

:python中可以使用 pickle 模組將物件轉化為檔案儲存在磁碟上,在需要的時候再讀取並還原。

from six。moves import cPickle

x = {“a”: 1, “b”: 2, “c”: 3}

# 將 x 持久化儲存到檔案 tmp。txt 中

cPickle。dump(x, open(“tmp。txt”, “wb”))

# 從 tmp。txt 中讀取並恢復 x 物件

b = cPickle。load(open(“tmp。txt”, “rb”))

print (b)

輸出:

{‘a’: 1, ‘c’: 3, ‘b’: 2}

28。defaultdict():defaultdict接受一個工廠函式作為引數,工廠函式可以是list、set、str等等,作用是當key不存在時,返回的是工廠函式的預設值,比如list對應[ ],str對應的是空字串,set對應set( ),int對應0。

res = defaultdict(int)

a = [1,2,3,4,2]

for num in a:

res[num] += 1

print (res)

輸出:

defaultdict(, {1: 1, 2: 2, 3: 1, 4: 1})

29。tf。sign():返回符號 y = sign(x) -1 if x < 0; 0 if x == 0; 1 if x > 0。

import tensorflow as tf

a = [-2, 3, 0 ,1]

b = tf。sign(a)

with tf。Session() as sess:

print (sess。run(b))

輸出:

[-1 1 0 1]

30。np。pad(array, pad_width, mode, **kwargs):常用於深度學習中的資料預處理,可以將numpy陣列按指定的方法填充成指定的形狀。引數含義:array代表需要填充的陣列;pad_width代表每個軸邊緣需要填充的數值數目;mode代表填充方式。

這裡只是舉了一個簡單例子,該函式的詳細使用方法還要參考別處。

import numpy as np

a = [[1, 2, 3],

[4, 5, 6]]

b = np。pad(a, ((1, 2),(2, 3)), ‘constant’, constant_values = (-1,-2))

print (b)

輸出:

[[-1 -1 -1 -1 -1 -2 -2 -2]

[-1 -1 1 2 3 -2 -2 -2]

[-1 -1 4 5 6 -2 -2 -2]

[-1 -1 -2 -2 -2 -2 -2 -2]

[-1 -1 -2 -2 -2 -2 -2 -2]]

31。 random。setstate和getstate:python的random模組生成的隨機數並不是真正的隨機數, 其內部狀態決定了生成的隨機數的值。內部狀態可以透過random。getstate()來獲取。 每次生成一個隨機數之後,內部狀態就會改變random。setstate()可以恢復內部狀態, 如果內部狀態相同,那麼生成的隨機數也相同。

import random

a = random。getstate()

b = random。random()

print (b)

c = random。setstate(a)

d = random。random()

print (d)

輸出:

0。40726850933040404

0。40726850933040404

32。it = np。nditer(x, flags=[‘multi_index’], op_flags=[‘readwrite’])用法:

python自帶的迭代器,

flags=[‘multi_index’]

表示對a進行多重索引,具體解釋看下面的程式碼。

op_flags=[‘readwrite’]

表示不僅可以對a進行read(讀取),還可以write(寫入),即相當於在建立這個迭代器的時候,我們就規定好了有哪些許可權。

import numpy as np

a = np。array([[1,2,3],

[4,5,6]])

it = np。nditer(a, flags=[‘multi_index’], op_flags=[‘readwrite’])

while not it。finished:

ix = it。multi_index # (tuple)

print (ix)

it。iternext()

輸出:

(0, 0)

(0, 1)

(0, 2)

(1, 0)

(1, 1)

(1, 2)

print it。multi_index

表示輸出元素的索引,可以看到輸出的結果都是index。

it。iternext()

表示進入下一次迭代,如果不加這一句的話,輸出的結果就一直都是

(0, 0)

33。 np。outer函式:計算向量外積。

a = np。array([1,2,3])

b = np。array([1,2])

c = np。outer(b, a)

print (c)

輸出:

[[1 2 3]

[2 4 6]]

34。tf。variable_scope和tf。name_scope的用法

https://

blog。csdn。net/UESTC_C2_

403/article/details/72328815

35。tensorflow學習筆記——embedding_lookup()用法

https://

blog。csdn。net/u01304139

8/article/details/60955847

35。tf。cond()的用法

https://

blog。csdn。net/m0_370413

25/article/details/76908660

36。tensorflow中使用tf。ConfigProto()配置Session執行引數&&GPU裝置指定

https://

blog。csdn。net/dcrmg/art

icle/details/79091941

37。如何遮蔽Tensorflow中的Warning

https://

zhuanlan。zhihu。com/p/11

6733375

38。 填充使用tf。sequence_mask()函式詳細說明和應用場景

https://

blog。csdn。net/xinjieyua

n/article/details/95760679

39。tf。Graph()。as_default() 詳解

https://

blog。csdn。net/nanhuaibe

ian/article/details/101862790

40。 tf。strided_slice/張量切片

https://

blog。csdn。net/akadiao/a

rticle/details/79602128

41。 tf。slice()介紹

https://

blog。csdn。net/nini_code

d/article/details/79852031?utm_medium=distribute。pc_relevant。none-task-blog-BlogCommendFromMachineLearnPai2-1。nonecase&depth_1-utm_source=distribute。pc_relevant。none-task-blog-BlogCommendFromMachineLearnPai2-1。nonecase

標簽: tf  print  sess  np  run