Pythonいぬ

pythonを使った画像処理に関する記事を書いていきます

pythonのlistから特定文字列を含む要素を抽出

pythonのlistで指定した文字列を含む要素だけを抽出したい。linuxでいうgrep的なことをlistやりたい。

listから特定の文字列を含む要素を抽出

以下のようにすると指定した要素を取り出せる。keyに探したい言葉を入れる。mylistは検索対象のリスト。outが出力

import numpy as np

key = 'rand'
mylist = dir(np.random)
out =  [ s for s in mylist if key in s ]

np.random以下にある関数のリストから文字列'rand'を含むものだけを出力する。結果のoutの中身は以下のようになる

['mtrand',
 'rand',
 'randint',
 'randn',
 'random',
 'random_integers',
 'random_sample']

テキストマイニングとかするときに大量の文章から特定の単語を抽出してくるとかに使えるかなと。

条件の変更

ifの部分は別の条件も入れられるため、例えば次のように長さが5の文字列のみを抽出するとかもできる。

import numpy as np

mylist = dir(np.random)
out =  [ s for s in mylist if len(s)==5 ]

出力outには以下の値が入る。

['bytes', 'gamma', 'power', 'randn']

文字数が5文字の関数だけ抽出できる。

pytorchの関数リスト

せっかくなので、pytorchのnn以下の関数について、特定条件のリストを出してみる。これをやると知らない関数がちらほら出てくるので、勉強になったりする。

まずは2dをkeyにしてnn以下の関数を出力する。

from torch import nn

key = '2d'
out =  [ s for s in mylist if key in s ]
['AdaptiveAvgPool2d',
 'AdaptiveMaxPool2d',
 'AvgPool2d',
 'BatchNorm2d',
 'ConstantPad2d',
 'Conv2d',
 'ConvTranspose2d',
 'CrossMapLRN2d',
 'Dropout2d',
 'FractionalMaxPool2d',
 'InstanceNorm2d',
 'LPPool2d',
 'MaxPool2d',
 'MaxUnpool2d',
 'NLLLoss2d',
 'ReflectionPad2d',
 'ReplicationPad2d',
 'Softmax2d',
 'UpsamplingBilinear2d',
 'UpsamplingNearest2d',
 'ZeroPad2d']

聞いたことがない関数がちらほら。

次は'Loss'をkeyにしてみる。

from torch import nn

key = 'Loss'
out =  [ s for s in mylist if key in s ]
['AdaptiveLogSoftmaxWithLoss',
 'BCELoss',
 'BCEWithLogitsLoss',
 'CTCLoss',
 'CosineEmbeddingLoss',
 'CrossEntropyLoss',
 'HingeEmbeddingLoss',
 'KLDivLoss',
 'L1Loss',
 'MSELoss',
 'MarginRankingLoss',
 'MultiLabelMarginLoss',
 'MultiLabelSoftMarginLoss',
 'MultiMarginLoss',
 'NLLLoss',
 'NLLLoss2d',
 'PoissonNLLLoss',
 'SmoothL1Loss',
 'SoftMarginLoss',
 'TripletMarginLoss']

普段はBCE, L1, MSEくらいしか使わないんだけど、こちらも結構たくさんあることがわかった。diffとかも取れるようにすればバージョンアップしたときに差分が取れて便利かもしれない。