Python3

pythonの最初の環境構築メモ

conda init zsh sh -c "$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" # conda create (GUIで操作しても良い) conda create --name [環境名] python=3.7 --prefix=[prefix] -y conda activate [環境名] jupyter kernelspe…

git の subdirectoryをlocalにinstallする方法

stackoverflow.com pytorch の referenceをinstallする方法を探してたら、これが便利そう $ svn ls https://github.com/pytorch/vision.git/trunk/references/detection README.md coco_eval.py coco_utils.py engine.py group_by_aspect_ratio.py train.py …

google colab で動画が再生できなかった。

import base64 import io def play(file_path): video = io.open(file_path, 'r+b').read() encoded = base64.b64encode(video) return(HTML(data='''<video width="320" height="240" controls><source src="data:video/mp4;base64,{0}" type="video/mp4" /></video>'''.format(encoded.decode('ascii')))) walkingmask.ha…

Pytorch で RGB2GBR を実施

transpose は numpy の func なので、permute を使用する。 qiita.com

Transformer の pytorch での実装してるサイトのメモ

nlp.seas.harvard.edu Label scaling と temperature scaling があり、予測結果のoverconfidence を抑制する。 codecrafthouse.jp .unsqueeze(1) は縦長。scatter_で one-hot的に、置換している。 # true_dist.shape == (n, d) # target.shape == (n, ) true…

多重代入法

多重代入法のPDF https://www.ism.ac.jp/~noma/Noma2017JJAS.pdf statsmodels で実装できるっぽい。

rle_encode の +2については、 pixel は 1 から、採番していくため、+1 0番目と1番目の差異を index=0とするため、実際のmask は +1 def rle_encode(mask): """ Ref. https://www.kaggle.com/paulorzp/run-length-encode-and-decode """ pixels = mask.flatt…

plt.hist と sns.distplot の normed パラメータについて

plt.hist の normed=True は 出現確率を表現するものではなく、面積的ななにかをnormize する方法っぽい。 sns.distplot も同様。 jb102.blogspot.com

matplot の色をラベルで固定する方法

色の確認 import matplotlib as mpl import matplotlib.pyplot as plt def plot_colorMaps(cmap): fig, ax = plt.subplots(figsize=(4,0.4)) col_map = plt.get_cmap(cmap) mpl.colorbar.ColorbarBase(ax, cmap=col_map, orientation = 'horizontal') plt.sh…

Plotly のセットアップで詰まった所

seaborn の stack の barplot が難しいので、Plotly で実施するように変更した。settings に手こずったので tips のURL を掲載。 stackoverflow.com stackoverflow.com

seaborn : barplot の xticks の調整が難しかった

seaborn の barplot を使っている時、1990~2020 年までのデータに不足があったので、間がとびとびのbarplotになっていた。 xticks(np.arange(1990, 2020)) とかで調整しようとすると、barが消えたりする。 不足分を補うことで、対応した。やむなし。idnex は…

2つ以上の histgram の bins の幅がいい感じにならなかったので

これでいい感じに揃えられた。 sns.set(font='IPAPGothic') plt.figure(figsize=(12, 4)) try: bins=np.histogram(np.hstack((tmp_0[col],tmp_1[col])), bins=50)[1] #get the bin edges except Exception as e: print(e) continue sns.distplot( tmp_0[col]…

Notebook を HTML形式で出力する方法

ワイルドカードでの指定でも可能 stackoverflow.com

seaborn の distplot logscale

dispplot の y軸 log scale sns.distplot(..., hist_kws={'log':True}) github.com

ZIPファイルから、skimage と PIL で 画像を読み込む

zip を解凍せずに処理していきたい(Diskを圧迫するため)。 import pandas as pd import numpy as np import skimage.io from PIL import Image, ImageFile import io def get_pil_inzip(_zip_path, image_idx): image_id = files_in_zip_dic[image_idx][0]…

pandas groupby した後のカラム

grouypby agg した後の、columns を 階層1に統合。 tmp_kigo2.columns = ['_'.join(col) if col[1]!='' else col[0] for col in tmp_kigo2.columns]

seaborn の figsize

seaborn で figsize 変更するには以下のメソッドが使いやすい。 g = sns.catplot( x='year', y='金額', hue='フラグ', data=df, kind='bar' ) g.fig.set_size_inches(15, 4) plt.show() www.drawingfromdata.com

jupyter notebook の src から画像を復元する方法

最初の data:image/png;base64 の文言は BOMみたいなもんなので、抜いてください。 import base64 from PIL import Image from io import BytesIO text = "" def base642image(data): try: ddata = base64.b64decode(data) img = Image.open(BytesIO(ddata))…

時系列の python 実装例

www.dataquest.io www.machinelearningplus.com

時系列の特徴量に三角関数が有効

sin などを使うことで、周期性を特徴量に入れれるらしい。 tbnsilveira.info isadoranun.github.io pandas.pydata.org

分類機を loss=BCE で予測するとき

0, 1 の分類器について、BCE で loss を計算すると、未来の確率の最尤は予測値となる。 def likelifood(x, n, n_1): return (x**(n_1)) * ((1- x) ** (n - n_1)) N = 100 N_1 = 80 x_list = [] for i in np.arange(0, 1.01, 0.01): xx = likelifood(i, N, N_…

model の param がちゃんと更新されなかった時

a = list(self.parameters())[0].clone() loss.backward() self.optimizer.step() b = list(self.parameters())[0].clone() torch.equal(a.data, b.data) discuss.pytorch.org

attention 記事まとめ

github.com github.com deeplearning.hatenablog.com self attention によるLSTMの精度向上 ai-scholar.tech github.com Pytorch の transformer 実装 towardsdatascience.com nlp.seas.harvard.edu

flip の引数について

peaceandhilightandpython.hatenablog.com

Mask-rcnn のベンチマーク

この人いい感じにまとめてくれている。faster-rcnn と mask-rcnn いい感じに整理したい。 github.com

OpenCV 小ネタ集4

Object detections matchTemplate import cv2 import numpy as np import matplotlib.pyplot as plt def cv2_imshow(title, image): plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) plt.title(title) # as opencv loads in BGR format by default, we …

interpret が便利そう

explainable AI で便利そうなOSS。以下で、どれだけ項目が効いているか確認。 from interpret.glassbox import ExplainableBoostingClassifier ebm = ExplainableBoostingClassifier() ebm.fit(x_train, y_train) ebm_local = ebm.explain_local(x_test, y_t…

Python の method の params を知る方法

from inspect import signature from sklearn.ensemble import IsolationForest signature(IsolationForest) <Signature (n_estimators=100, max_samples='auto', contamination=0.1, max_features=1.0, bootstrap=False, n_jobs=1, random_state=None, verbose=0)></signature>

異常検知の実装 tips

以下を見て、方法をまとめたい。明日移行。 scikit-learn.org https://fisproject.jp/2019/03/deep-learning-for-anomaly-detection-1/ deeplearning4j.org contamination: ノイズの割合を指定できるので、訓練データにノイズが有る場合は指定する。OneClass…

OpenCV 小ネタ集3

Approximating Contour + Convex Hull Approximating Contour import numpy as np import cv2 import matplotlib.pyplot as plt def cv2_imshow(title, image): plt.figure(figsize=(8, 8)) plt.imshow(cv2.cvtColor(image.astype(np.uint8), cv2.COLOR_BGR2…