金子邦彦研究室インストールまとめ人工知能応用,データ応用,3次元のまとめ

人工知能応用,データ応用,3次元のまとめ

このページは,学術の進展には,用語の定義,実験等での実証が重要であり,そのための基本となる情報をまとめたいという理念による. 第三者のソフトウェア,データセット,製品等を説明しているものがあるが, それらの利用条件は利用者で確認すること.個々のソフトウェア,データセット,製品等の評価,評論は行わない.

データ処理,データベース,ディープラーニング分野のための基礎用語. 項目を 0-9,a-z, あーん,漢字順に並べている.

目次

  1. 0-9 (数字)
  2. a-z (アルファベット)
  3. あ〜ん (ひらがな,カタカナ)
  4. あ〜ん (漢字)

サイト内のまとめページへのリンク

Google Colaboratory の使い方

Google Colaboratory は,オンラインの Python の開発環境.使い方などは, 別ページ »で説明

サイト内の主な Windows 関連ページ

サイト内の主な Ubuntu 関連ページ

関連する外部ページ

0-9 (数字)

2to3

2to3 は,Python バージョン 2 用のソースコードを Python バージョン 3 用に変換するプログラム.

詳しくは: 別ページ »で説明している.

300W (300 Faces-In-The_Wild) データセット

顔のデータベース,顔の 68 ランドマークが付いている.

文献

C. Sagonas, G. Tzimiropoulos, S. Zafeiriou and M. Pantic, "300 Faces in-the-Wild Challenge: The First Facial Landmark Localization Challenge," 2013 IEEE International Conference on Computer Vision Workshops, 2013, pp. 397-403, doi: 10.1109/ICCVW.2013.59.

https://ibug.doc.ic.ac.uk/media/uploads/documents/sagonas_2016_imavis.pd

関連する外部ページ

関連項目HELEN データセット, iBUG 300-W データセット, face alignment, 顔ランドマーク (facial landmark)の検出, 3次元の顔の再構成 (3D face reconstruction), OpenMMLab, 顔の 68 ランドマーク, 顔のデータベース

3DF Zephyr Free

3DF Zephyr Free は,フォトグラメトリのソフトウェア 3dF Zephyr の無料版

関連項目】 フォトグラメトリ, Meshroom

3DDFA_V2

3DDFA_V2 は, 3次元の顔の再構成 (3D face reconstruction) のうち dense vertices regression を行う一手法.論文は,2020年発表.

文献

Jianzhu Guo, Xiangyu Zhu, Yang Yang, Fan Yang, Zhen Lei, Stan Z. Li, Towards Fast, Accurate and Stable 3D Dense Face Alignment, ECCV 2020.

https://arxiv.org/pdf/2009.09960v2.pdf

関連する外部ページ

Google Colaboratory での 3DDFA_V2 のインストールとオンライン実行

次のページは,Google Colaboratory のページである.ページを開き実行できる.

URL: https://colab.research.google.com/drive/1OKciI0ETCpWdRjP-VOGpBulDJojYfgWv [Google Colaboratory]

実行により,3次元のポリゴンが得られていることを確認できる.

結果は /content/3DDFA_V2/examples/results/ にできる. ここには,顔の3次元データであるポリゴンメッシュ(.obj ファイル)もある.

.obj ファイルをダウンロードし Blender で表示してみると次のようになる.

関連項目3次元の顔の再構成, 顔に関する処理

3次元姿勢推定 (3D pose estimation)

画像から,物体検出を行うとともに,その3次元の向きの推定も行う.

関連項目Objectron

3次元ゲームエンジン (3-D game engine)

3次元ゲームエンジン (3-D game engine) の機能を持つソフトウェアとしては, GoDot, Open 3D Engine, Unreal Engine, Panda3D などがある.

3次元の顔の再構成 (3D face reconstruction)

3次元の顔の再構成 (3D face reconstruction) は, 顔の写った画像から,元の顔の3次元の形を構成すること.

3次元の顔の再構成は,次の2つの種類がある.

  1. 3次元の変形可能な顔のモデル (3D Morphable Model) について,そのパラメータを,画像を使って推定すること. FaceRig などが有名である.
  2. dense vertices regression: dense は「密な」,vertices は「頂点」,regression は「回帰」.画像から,顔の3次元データであるポリゴンメッシュを推定する

関連項目3DDFA_V2 , 顔に関する処理

3次元再構成 (3D reconstruction)

3次元再構成 (3D reconstruction) の機能をもつソフトウェアとしては, colmapMeshroom がある.

関連項目colmap, Meshroom, Multi View Stereo, OpenMVG, OpenMVS, Structure from Motion

3次元点群データ (3-D point cloud data)

3次元点群データ (3-D point cloud data) を扱うには,MeshLab や CloudCompare が便利である.

7-Zip のインストール

7-Zipはファイルやフォルダの圧縮・解凍作業を行うためのツールである.Windows の標準機能では簡単に扱えない各種形式のアーカイブファイルを扱うことが可能である.

7-Zip の公式ページ: https://sevenzip.osdn.jp/ からダウンロードしてインストールする.

7-Zip のインストールの詳細: 別ページ »で説明

  1.  7-Zip の公式ページを開く
    https://sevenzip.osdn.jp/
  2.  ダウンロードしたいので,「7-Zip ... for Windows」の下の,「64 ビット x64」の「ダウンロード」をクリック

    [image]
  3. ダウンロードした .exe ファイルを実行
  4. Windowsシステム環境変数 Pathに,C:\Program Files\7-Zip追加することにより,パスを通す

    Windows で,コマンドプロンプト管理者として実行

    コマンドプロンプトを管理者として実行: 別ページ »で説明

    次のコマンドを実行

    powershell -command "$oldpath = [System.Environment]::GetEnvironmentVariable(\"Path\", \"Machine\"); $oldpath += \";C:\Program Files\7-Zip\"; [System.Environment]::SetEnvironmentVariable(\"Path\", $oldpath, \"Machine\")"
    

a-z (アルファベット)

Aachen Day-Night データセット

URL: https://www.visuallocalization.net/datasets/

Access

Access はリレーショナルデータベース管理の機能を持ったソフトウエア.

サイト内の関連ページ

AdaDelta 法

M.Zeiler の AdaDelta 法は,学習率をダイナミックに変化させる技術. 学習率をダイナミックに変化させる技術は,その他 Adam 法なども知られる.

確率的勾配降下法 (SGD 法) をベースとしているが, 確率的勾配降下法が良いのか,Adadelta 法が良いのかは,一概には言えない.

Keras のプログラム】

from tensorflow.keras.optimizers import Adadelta
optimizer = Adadelta(rh=0.95)

M. Zeiler, Adadelta An adaptive learning rate method, 2012.  

Adam 法

Adam 法は,学習率をダイナミックに変化させる技術. 学習率をダイナミックに変化させる技術は,その他 AdaDelta 法なども知られる. Adam 法を使うプログラム例は次の通り.

Keras のプログラム】

m.compile(
    optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
    loss='sparse_categorical_crossentropy',
    metrics=['sparse_categorical_crossentropy', 'accuracy']
)

Diederik Kingma and Jimmy Ba, Adam: A Method for Stochastic Optimization, 2014, CoRR, abs/1412.6980

ADE20K データセット

ADE20K データセット は, セマンティック・セグメンテーションシーン解析(scene parsing)インスタンス・セグメンテーション (instance segmentation)についてのアノテーション済みの画像データセットである.

次の特色がある

画像数,オブジェクト数などは次の通り.

利用には,次の URL で登録が必要.

ADE20K データセットの URL: http://groups.csail.mit.edu/vision/datasets/ADE20K/

文献

関連する外部ページ

関連項目セマンティック・セグメンテーション (semantic segmentation), シーン解析(scene parsing), インスタンス・セグメンテーション (instance segmentation), Detectron2 CASILVision, MIT Scene Parsing Benchmark, 物体検出

AFLW (Annotated Facial Landmarks in the Wild) データセット

AFLW (Annotated Facial Landmarks in the Wild) データセットは, Flickr から収集された24,386枚の顔画像である. さまざまな表情,民族,年齢,性別,撮影条件,環境条件の顔が収集されている. それぞれの顔には,最大21個の顔ランドマークが付けられている.

次の URL で公開されているデータセット(オープンデータ)である.

URL: https://www.tugraz.at/institute/icg/research/team-bischof/lrs-group/downloads

文献

M. Köstinger, P. Wohlhart, P. M. Roth and H. Bischof, "Annotated Facial Landmarks in the Wild: A large-scale, real-world database for facial landmark localization," 2011 IEEE International Conference on Computer Vision Workshops (ICCV Workshops), 2011, pp. 2144-2151, doi: 10.1109/ICCVW.2011.6130513.

関連する外部ページ

関連項目顔のデータベース, 顔ランドマーク

Anaconda3 のインストール

Anaconda3は,Python 処理系, conda その他の詰め合わせ. パッケージ管理は anaconda, conda コマンドで行う. pip や python setpy.py でのインストール予定がない場合には候補の1つになりえる.

Windows での Anaconda3 のインストールには,複数の方法がある.次のいずれかによりインストールできる.

関連項目】 Python のインストール: 別項目で説明している.

AgeDB データセット

手作業で収集された,「in-the-wild」の顔と年齢のデータベース. 年号まで正確に記録された顔画像が含まれている.

次の URL で公開されているデータセット(オープンデータ)である.

https://ibug.doc.ic.ac.uk/resources/agedb/

文献

S. Moschoglou, A. Papaioannou, C. Sagonas, J. Deng, I. Kotsia and S. Zafeiriou, "AgeDB: The First Manually Collected, In-the-Wild Age Database," 2017 IEEE Conference on Computer Vision and Pattern Recognition Workshops (CVPRW), 2017, pp. 1997-2005, doi: 10.1109/CVPRW.2017.250.

https://ibug.doc.ic.ac.uk/media/uploads/documents/agedb.pdf

関連する外部ページ

関連項目顔認識 (face recognition), 顔のデータベース

AIM-500 (Automatic Image Matting-500) データセット

イメージ・マッティング (image matting) のデータセット. 3種類の前景(Salient Opaque, Salient Transparent/Meticulous, Non-Salient)を含む 500枚の画像について,元画像と alpha matte と Trimap のデータセットである.

次の URL で公開されているデータセット(オープンデータ)である.

URL: https://drive.google.com/drive/folders/1IyPiYJUp-KtOoa-Hsm922VU3aCcidjjz

文献

Jizhizi Li, Jing Zhang, DaCheng Tao, Deep Automatic Natural Image Matting, CoRR, abs/2107.07235v1, 2021.

https://arxiv.org/pdf/2107.07235v1.pdf

関連する外部ページ

【関連用語】 イメージ・マッティング (image matting), オープンデータ (open data)

AlexeyAB darknet

AlexeyAB darknet は,YOLOv2, YOLOv3, YOLOv4 の機能などを持つ.

文献

Chien-Yao Wang, Alexey Bochkovskiy, Hong-Yuan Mark Liao, Scaled-YOLOv4: Scaling Cross Stage Partial Network, Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR) 2021, pp. 13029-13038, also CoRR, Scaled-YOLOv4: Scaling Cross Stage Partial Network, 2021.

https://arxiv.org/pdf/2011.08036v2.pdf

サイト内の関連ページ

AlexryAB/darknet のインストールと動作確認(Scaled YOLO v4 による物体検出)(Windows 上)

関連する外部ページ

関連項目YOLOv3, YOLOv4, RetinaNet, 物体検出

Alexnet

AlexNet の場合

input 3@224x224
conv 11x11
  96@55x55
pooling
conv 5x5
  256@27x27
pooling
  16@5x5
conv 3x3
  384@13x13
conv 3x3
  384@13xx13
conv 3x3 
  256@13x13
affine
  4096
affine
  4096
  1000

参考文献: ch08/deep=cnvnet.py

AltCLIP

AltCLIP の特徴は, CLIP のテキストエンコーダ (text encoder) を 学習済みの多言語のテキストエンコーダ XLM-R で置き換えたこと.

文献

Zhongzhi Chen, Guang Liu, Bo-Wen Zhang, Fulong Ye, Qinghong Yang, Ledell Wu, AltCLIP: Altering the Language Encoder in CLIP for Extended Language Capabilities, arXiv:2211.06679, 2022.

関連項目CLIP

AP

機械学習による物体検出では, 「AP」は,「average precision」の意味である.

Apache Hadoop

Apache Hadoop は,並列処理のための MapReduce という機構を持つ.これは,Hadoop の分散ファイルシステム (Hadoop Distributed File System; HDFS) 上で動く.MapReduce とは,アプリケーションが,多数の小さな処理単位 (block) に分割するための機構である.分散ファイルシステムは, データブロック (data block) 単位での複製を作り,クラスタを構成するノード上に配置する.

Ubuntu での Apache Hadoop のインストール: 別ページ »で説明している.

Applications of Deep Neural Networks

「Applications of Deep Neural Networks」は,ディープラーニングに関するテキスト. ニューラルネットワークCNN (convolutional neural network), LSTM (Long Short-Term Memory), GRU (Gated Recurrent Neural Networks), GAN (Generative Adversarial Network), 強化学習とその応用について学ぶことができる. Python, TensorFlow, Keras を使用している.

関連する外部ページ

関連項目CNN (convolutional neural network), GAN (Generative Adversarial Network), GRU (Gated Recurrent Neural Networks), Keras, LSTM (Long Short-Term Memory), TensorFlow, ディープラーニング ニューラルネットワーク, 強化学習

ArcFace 法

距離学習の1手法である. 分類モデルが特徴ベクトルを生成するための複数の層と,最終層の softmax から構成されているとき, その分類モデルでの,特徴ベクトルを生成するための複数の層の出力に対して, L2 正規化の処理と,Angular Magin Penalty 層による処理を追加し,softmax 層につなげる.

deepface, InsightFace などで実装されている.

文献

Jiankang Deng, Jia Guo, Niannan Xue, Stefanos Zafeiriou, ArcFace: Additive Angular Margin Loss for Deep Face Recognition, CVPR 2019, also CoRR, abs/1801.07698v3, 2019.

https://arxiv.org/pdf/1801.07698v3.pdf

関連する外部ページ

関連項目deepface, InsightFace, 顔検証 (face verification), 顔識別 (face identification), 顔認識 (face recognition), 顔に関する処理

asteroid

asteroid は,音源分離(audio source separation)のツールキット.

文献

Ryosuke Sawata, Stefan Uhlich, Shusuke Takahashi, Yuki Mitsufuji, All for One and One for All: Improving Music Separation by Bridging Networks, CoRR, abs/2010.04228v4, 2021.

PDF: https://arxiv.org/pdf/2010.04228v4.pdf

関連する外部ページ

【関連用語】 audio source seperation, music source separation, speech enhancement

Windows での asteroid のインストールと動作確認(音源分離)

asteroid のインストールと動作確認(音源分離)(Python,PyTorch を使用)(Windows 上): 別ページ »で説明している.

[image]
Google Colaboratory での asteroid のインストール

公式の手順 https://github.com/asteroid-team/asteroid による.

次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する).

%cd /content
!rm -rf asteroid
!git clone https://github.com/asteroid-team/asteroid
%cd asteroid
!python3 setup.py develop
!pip3 install -r requirements.txt

[image]

AVA

Spatio-Temporal Action Recognition の一手法.2016年発表

関連項目MMAction2, Spatio-Temporal Action Recognition, 動作認識 (action recognition)

Bark

Bark は Transformer ベースの音声合成の技術.多言語に対応.

サイト内の関連ページ

関連する外部ページ

関連項目VALL-E X

BASNet (Boundary-Aware Salient object detection)

BASNet は, ディープラーニングにより,Salient Object Detection (顕著オブジェクトの検出)を行う一手法.2019年発表.

BASNet は次の2つのモジュールから構成される.

Salient Object Detection は, 視覚特性の異なるオブジェクトを,画素単位で切り出す. 前景と背景の分離に役立つ場合がある.人間がマスクの指定や塗り分け(Trimap など)を行うことなく実行される.

文献

Qin, Xuebin and Zhang, Zichen and Huang, Chenyang and Gao, Chao and Dehghan, Masood and Jagersand, Martin, BASNet: Boundary-Aware Salient Object Detection, The IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2019

https://openaccess.thecvf.com/content_CVPR_2019/papers/Qin_BASNet_Boundary-Aware_Salient_Object_Detection_CVPR_2019_paper.pdf

関連する外部ページ

【関連用語】 U-Net, U2-Net, salient object detection, セマンティック・セグメンテーション (semantic segmentation)

Windows での BASNet のインストールとテスト実行(顕著オブジェクトの検出)

BASNet のインストールとテスト実行(顕著オブジェクトの検出)(Python,PyTorch を使用)(Windows 上): 別ページ »で説明している.

[image]

[image]

[image]

[image]

[image]

[image]
Google Colaboratory での BASNet のインストールとオンライン実行

次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する).

BASNet のテストプログラムのオンライン実行を行うまでの手順を示す.

  1. BASNet プログラムなどのダウンロード**
    !git clone https://github.com/NathanUA/BASNet.git
    

    [image]
  2. 学習済みモデルのダウンロード

    公式ページ https://github.com/xuebinqin/BASNet の指示による. 学習済みモデル(ファイル名 basenet.pth)は,次で公開されている. ダウンロードし,saved_models/basnet_bsi の下に置く

    https://drive.google.com/open?id=1s52ek_4YTDRt_EOkx1FS53u-vJa0c4nu

    [image]
  3. テスト用の画像のダウンロードと確認表示
    %cd BASNet
    !curl -L https://github.com/opencv/opencv/blob/master/samples/data/fruits.jpg?raw=true -o fruits.jpg
    !curl -L https://github.com/opencv/opencv/blob/master/samples/data/home.jpg?raw=true -o home.jpg
    !curl -L https://github.com/opencv/opencv/blob/master/samples/data/squirrel_cls.jpg?raw=true -o squirrel_cls.jpg
    from PIL import Image
    Image.open('fruits.jpg').show()
    Image.open('home.jpg').show()
    Image.open('squirrel_cls.jpg').show()
    

    [image]
    [image]
  4. BASNet の実行
    %cd BASNet
    !python basnet_test.py
    

    [image]
  5. 結 果の表示

    [image]
    [image]

BDD100K

物体検出, instance segmentaion, multi object tracking, segmentation trackling, セマンティック・セグメンテーション (semantic segmentation), lane marking,l pose estimation 等の用途を想定したデータセット

関連項目物体検出, instance segmentaion, multi object tracking, segmentation trackling, セマンティック・セグメンテーション (semantic segmentation), lane marking, pose estimation

Windows での BDD100K Images, Detection 2020 Labels, Pose Estimation Labels の展開

Windows での BDD100K Images, Detection 2020 Labels, Pose Estimation Labels の展開手順は次の通り.

BDD100K を image tagging, 物体検出 (object detection), pose estimation に用いることを想定.

BDD100K のデータセットの準備の説明ページ(公式): https://github.com/SysCV/bdd100k-models/blob/main/doc/PREPARE_DATASET.md

  1. BDD100K のダウンロードの公式ページから, BDD100K Images, Detection 2020 Labels, Pose Estimation Labels をダウンロード

  2. BDD100K のダウンロードの公式ページ: https://bdd-data.berkeley.edu/
  3. bdd100k_images_100k.zip がダウンロードされる
  4. 展開のため,次のコマンドを実行
    copy bdd100k_images_100k.zip %LOCALAPPDATA%
    copy bdd100k_labels_release.zip %LOCALAPPDATA%
    copy bdd100k_pose_labels_trainval.zip %LOCALAPPDATA%
    cd %LOCALAPPDATA%
    powershell -command "Expand-Archive -DestinationPath . -Path bdd100k_images_100k.zip"
    powershell -command "Expand-Archive -DestinationPath . -Path bdd100k_labels_release.zip"
    powershell -command "Expand-Archive -DestinationPath . -Path bdd100k_pose_labels_trainval.zip"
    
  5. ファイルの配置は次のようになる.
     └─bdd100k
         |
         └── images
             ├── test
             ├── train
             └── val
         |
         └─labels
             ├──bdd_labels_images_train.json
             ├──bdd_labels_images_val.json
             └─ pose21
    
Ubuntu での BDD100K Images, Detection 2020 Labels, Pose Estimation Labels の展開

Windows での BDD100K Images, Detection 2020 Labels, Pose Estimation Labels の展開手順は次の通り.

BDD100K を image tagging, 物体検出 (object detection), pose estimation に用いることを想定.

BDD100K のデータセットの準備の説明ページ(公式): https://github.com/SysCV/bdd100k-models/blob/main/doc/PREPARE_DATASET.md

  1. BDD100K のダウンロードの公式ページから, BDD100K Images, Detection 2020 Labels, Pose Estimation Labels をダウンロード

  2. BDD100K のダウンロードの公式ページ: https://bdd-data.berkeley.edu/
  3. bdd100k_images_100k.zip がダウンロードされる
  4. 展開のため,次のコマンドを実行
    sudo cp bdd100k_images_100k.zip /usr/local
    sudo cp bdd100k_labels_release.zip /usr/local
    sudo cp bdd100k_pose_labels_trainval.zip /usr/local
    cd /usr/local
    sudo 7z x bdd100k_images_100k.zip
    sudo 7z x bdd100k_labels_release.zip
    sudo 7z x bdd100k_pose_labels_trainval.zip
    sudo chown -R $USER bdd100k
    
  5. アノテーションファイルを,COCO 形式に変換する.
    cd /usr/local
    sudo rm -rf bdd100k-models
    sudo git clone https://github.com/SysCV/bdd100k-models
    sudo chown -R $USER bdd100k-models
    cd bdd100k-models
    sed -i -e 's/git+git/git+https/g' requirements.txt
    sudo pip3 install -U -r requirements.txt
    sudo python3 det/setup.py install
    sudo python3 drivable/setup.py install
    sudo python3 ins_seg/setup.py install
    sudo python3 pose/setup.py install
    sudo python3 sem_seg/setup.py install
    sudo python3 tagging/setup.py install
    cd /usr/local
    mkdir bdd100k\jsons
    python3 -m bdd100k.label.to_coco -m pose \
        -i bdd100k/labels/pose_21/pose_train.json \
        -o bdd100k/jsons/pose_train_cocofmt.json
    python3 -m bdd100k.label.to_coco -m pose \
        -i bdd100k/labels/pose_21/pose_val.json \
        -o bdd100k/jsons/pose_val_cocofmt.json
    
  6. ファイルの配置は次のようになる.
     └─bdd100k
         |
         └── images
             ├── test
             ├── train
             └── val
         |
         └─labels
             ├──bdd_labels_images_train.json
             ├──bdd_labels_images_val.json
             └─ pose21
    

Big Tranfer ResNetV2

関連項目Residual Networks (ResNets)

BioID 顔データベース (BioID Face Database)

BioID 顔データベースは,23名, 1521枚のモノクロの画像.解像度は 384x286 である.目の位置に関するデータを含む.

BioID 顔データベースは次の URL で公開されているデータセット(オープンデータ)である.

https://www.bioid.com/facedb/

BLAS

BLAS の主な機能(ごく一部を紹介)

関連項目BLAS, clapack, LAPACK

Blender

Blenderは,3次元コンピュータグラフィックス・アニメーションソフトウェアである. 3次元モデルの編集,レンダリング,光源やカメラ等を設定しての3次元コンピュータグラフィックス・アニメーション作成機能がある.

関連項目bpy (blenderpy), yuki-koyama の blender-cli-rendering

Windows での Blender のインストール

Windows での Blender のインストールは,複数の方法がある.

Ubuntu での Blender のインストール

Ubuntu での Blenderインストールは,別ページ »で説明している.

Blender のモーショントラッキング機能

次の動画は,Blender のモーショントラッキング機能を用いた映像作成について説明している.

https://www.youtube.com/watch?v=lY8Ol2n4o4A

次の動画は,作成された映像,グリーンバックの映像である.

https://www.youtube.com/watch?v=FFJ_THGj72U

BM3D image denosing

BM3D image denosing の公式ソースコード(GitHub のページ): https://github.com/gfacciol/bm3d

関連項目】 image denosing

Boost

Boost は, C++ のライブラリ.

Boost の URL: https://www.boost.org/

Windows での Boost のインストールとテスト実行

Windows での Boost 1_83 のインストールとテスト実行(ソースコードを使用): 別ページ »で説明している.

Ubuntu での Boost のインストール

Ubuntu でインストールを行うには,次のコマンドを実行.

sudo apt -y update
sudo apt -y install libboost-all-dev

Boston housing price 回帰データセット

Boston housing price 回帰データセットは,次のプログラムでロードできる.

Keras のプログラム】

from tensorflow.keras.datasets import boston_housing
(x_train, y_train), (x_test, y_test) = boston_housing.load_data()

関連項目Keras に付属のデータセット

Box Annotation

ディープラーニングによる物体検出のための学習と検証では, アノテーションとして,物体のバウンディングボックスが広く用いられている.

ディープラーニングによるインスタンス・セグメンテーション (instance segmentation)でも, Tian らの BoxInst (2021年発表) のように,画素単位でのアノテーションでなく, バウンディングボックスを用いる手法が登場している.

関連項目インスタンス・セグメンテーション (instance segmentation), バウンディングボックス, 物体検出,

bpy (blenderpy)

bpy (blenderpy) では,Blender がPython モジュールになっている.

関連項目Blender yuki-koyama の blender-cli-rendering

Windows での bpy (blenderpy) のインストール(PyPI を使用)

PyPI を用いてのインストールでは,2021年12月時点では,使用する Python はバージョン 3.7,Blender は 2.8. 新しい Blender の Python モジュールを必要する場合には,下の項目を見ること.

https://pypi.org/project/bpy/ の記載により,PyPI の bpy (blenderpy) のインストールを行う.

  1. 次のページで,必要な Python のバージョンを確認する.

    https://pypi.org/project/bpy/

  2. いま確認したバージョンの Python がインストールされていないときは, Python のインストール: 別項目で説明している.を行う.
  3. コマンドプロンプトを管理者として開き次のコマンドを実行する.

    -3.7」のところには, いま確認した Python のバージョンを指定する.

    py -3.7 -m pip install numpy
    py -3.7 -m pip install bpy
    bpy_post_install
    
  4. インストールできたことの確認

    -3.7」のところには, いま確認した Python のバージョンを指定する.

    エラーメッセージが出ていなければ OK.

    py -3.7 -c "import bpy"
    
Windows での bpy (blenderpy) のインストール(ソースコード を使用)

詳しくは,別ページ »で説明

ソースコードからビルドする

  1. Windows では,前準備として次を行う.
  2. タグの確認

    インストールしたい Blender のバージョンにあう Blender のタグを,次のページで探す.

    https://github.com/blender/blender/tags

  3. Visual Studio の x64 Native Tools コマンドプロンプトを開く.
  4. Blender のソースコードをダウンロード

    v3.0.1」のところには,使用したいバージョンの Blender のタグを指定すること.

    cd %LOCALAPPDATA%
    rmdir /s /q blender
    git clone -b v3.0.1 https://github.com/blender/blender
    
  5. Blender のコンパイル済みのライブラリのダウンロード,Blender のビルド

    Visual Studio Community 2022 を使うときは「make update 2022」,「make release 2022」 を実行.

    終了まで時間がかかるので,しばらく待つ

    cd %LOCALAPPDATA%
    cd blender
    make update 2022b
    make release 2022b 
    
  6. Blender の Python モジュールのビルド
    cd %LOCALAPPDATA%
    cd blender
    rmdir /s /q build
    mkdir build
    cd build
    del CMakeCache.txt
    cmake -G "Visual Studio 17 2022" -A x64 -T host=x64 -DWITH_PYTHON_INSTALL=OFF -DWITH_PYTHON_MODULE=ON ..
    cmake --build . --config RELEASE --target INSTALL -- /m:4
    
  7. Python のバージョン, Python のインストールディレクトリを確認
  8. インストール

    c:\Program Files\Python39」のところは, Python のインストールディレクトリを指定すること.

    python -m pip install numpy
    cd %LOCALAPPDATA%\blender\build\release
    copy bin\bpy.pyd c:\Program Files\Python39\Lib\site-packages\
    copy bin\*.dll c:\Program Files\Python39\Lib\site-packages\
    del c:\Program Files\Python39\Lib\site-packages\python36.dll
    xcopy /E bin\3.0 c:\Program Files\Python39\
    
  9. インストールできたかの確認

    コマンドプロンプトで次のコマンドを実行する.

    エラーメッセージが出なければ OK.

    python -c "import bpy; scene = bpy.data.scenes['Scene']; print(scene)"
    

    [image]

Build Tools for Visual Studio 2019

Build Tools for Visual Studio 2019(ビルドツール for Visual Studio 2019)は,Windows で動くMicrosoft の C++ コンパイラーである.

サイト内の関連ページ

関連する外部ページ

Build Tools for Visual Studio 2022

Build Tools for Visual Studio 2022(ビルドツール for Visual Studio 2022)は,Windows で動くMicrosoft の C++ コンパイラーである.

サイト内の関連ページ

Windows での Build Tools for Visual Studio 2022(ビルドツール for Visual Studio 2022)のインストール: 別ページ »で説明している.

関連する外部ページ

Build Tools for Visual Studio 2022 (ビルドツール for Visual Studio 2022)の公式ダウンロードページ: https://visualstudio.microsoft.com/ja/visual-cpp-build-tools/

cabani の MaskedFace-Net データセット

正しくマスクが装着された状態の顔の写真 (CMFD) と, 正しくマスクが装着されていない状態の顔の写真 (IMFD) のデータセット.

文献

Adnane Cabani and Karim Hammoudi and Halim Benhabiles and Mahmoud Melkemi, MaskedFace-Net -- A Dataset of Correctly/Incorrectly Masked Face Images in the Context of COVID-19, Smart Health, 2020.

Science Direct: https://www.sciencedirect.com/science/article/pii/S2352648320300362?via%3Dihub

サイト内の関連ページ

chandrikadeb7 / Face-Mask-Detection のインストールと動作確認(マスク有り顔,マスクなし顔の検出)(Python,TensorFlow を使用)(Windows 上): 別ページ »で説明している.

関連する外部ページ

公式 URL: https://github.com/cabani/MaskedFace-Net

関連項目顔のデータベース, 顔検出 (face detection)

Caffe

Caffe2

Caffe 2 のインストール

関連する外部ページ

Caltech Pedestrian データセット (Caltech Pedestrian Dataset)

Caltech Pedestrian データセット は,都市部を走行中の車両から撮影したデータ. 機械学習による物体検出 の学習や検証に利用できるデータセットである.

Caltech Pedestrian データセットは次の URL で公開されているデータセット(オープンデータ)である.

URL: http://www.vision.caltech.edu/datasets/

【関連情報】

Ceres ソルバ(Ceres Solver)

Ceres ソルバ(Ceres Solver)は,非線形の最適化の機能をもったソフトウェア.

公式ページ: http://ceres-solver.org/

文献

Agarwal, Sameer and Mierle, Keir and The Ceres Solver Team, Ceres Solver, https://github.com/ceres-solver/ceres-solver, 2022.

Windows での Ceres ソルバ(Ceres Solver) のインストール

Windows での Ceres ソルバ(Ceres Solver) のインストール: 別ページ »で説明している.

Ceres ソルバ(Ceres Solver) 2.1.0 の非公式ビルド: ceres-solver.zip

私がビルドしたもの,非公式,無保証, https://github.com/ceres-solver/ceres-solver で公開されているソースコードを改変せずにビルドした. Windows 10, Visual Build Tools for Visual Studio 2022 を用いてビルドした. 作者が定めるライセンス https://github.com/ceres-solver/ceres-solver/blob/master/LICENSE による.

zip ファイルは C:\ 直下で展開し,C:\ceres-solver での利用を想定.

CASILVision

関連項目画像分類, Class Activation Mapping (CAM), image tagging
Google Colaboratory で 画像分類,image tagging, class activation map のプログラム実行(CASILVision の Place365 を使用)

CASILVision の Place365 を使用. 公開されているプログラムは,次の手順で実行できる. 画像分類の結果は, 「0.511 -> food_court, 0.085 -> fastfood_restaurant, 0.083 -> cafeteria, 0.040 -> dining_hall, 0.021 -> flea_market/indoor」のように表示される.

image tagging では, 「no horizon, enclosed area, man-made, socializing, indoor lighting, cloth, congregating, eating, working」 のように,屋内であるか屋外であるかのタグなどが得られる.

!rm -rf places365
!git clone https://github.com/CSAILVision/places365
%cd places365
!python3 run_placesCNN_unified.py
from PIL import Image
Image.open('cam.jpg').show()

[image]

CelebA (Large-scale CelebFaces Attributes) データセットのダウンロード

Large-scale CelebFaces Attributes (CelebA) データセットは,顔画像とアノテーションのデータ. 機械学習による顔検出顔ランドマーク (facial landmark)顔認識,顔の生成などの学習や検証に利用できるデータセットである.

Large-scale CelebFaces Attributes (CelebA) データセットは次の URL で公開されているデータセット(オープンデータ)である.

URL: https://mmlab.ie.cuhk.edu.hk/projects/CelebA.html

【関連情報】

関連項目顔のデータベース, 顔ランドマーク (facial landmark)

Chain of Thought

マルチモーダル名前付きエンティティ認識(Multimodal Named Entity Recognition; MNER)およびマルチモーダル関係抽出(Multimodal Relation Extraction; MRE)の改善に注力し、これらの分野における精度向上を目指している。この目的のために、Chain of Thought(CoT)プロンプトを活用し、大規模言語モデル(LLM)から reasoning を抽出している。論文の手法は、名詞、文、マルチモーダルの観点からの多粒度の推論と、スタイル、エンティティ、画像を含むデータ拡張を網羅している。これにより、LLMからの reasoning をより効果的に抽出している。MNERの有効性を評価するために、Twitter2015、Twitter2017、SNAP、WikiDiverseという様々なデータセットを使用し、提案方法の効果を検証している。

文献

Feng Chen, Yujian Feng, Chain-of-Thought Prompt Distillation for Multimodal Named Entity Recognition and Multimodal Relation Extraction, arXiv:2306.14122v3, 2023.

https://arxiv.org/pdf/2306.14122v3.pdf

関連する外部ページ

CityGML

CityGML は,3次元の都市,3次元の景観を扱う機能を持つデータフォーマット. 次のようなモジュールがある.

Appearance, Bridge, Building, CityFurniture, LandUse, Relief, Transportation, Tunnel, Vegetation, Vegetation, WaterBody, TexturedSurface

[image]
12-019_OGC_City_Geography_Markup_Language_CityGML_Encoding_Standard.pdf のページ 34から転載

CityGML の公式情報は,Open Geospatial Consortium のページで公開されている.

Open Geospatial Consortium の CityGML ページ: https://www.ogc.org/standards/citygml

CityGML の仕様書も,このページで公開されている.

CityGML のビューワには FZKViewer がある. Windows での FZKViewer のインストールは 別ページ »で説明している.

関連項目FZKViewer

CSAILVision

CSAILVision の公式デモ(GitHub のページ): https://colab.research.google.com/github/CSAILVision/semantic-segmentation-pytorch/blob/master/notebooks/DemoSegmenter.ip

関連項目セマンティック・セグメンテーション (semantic segmentation)

CGAL

Windows での CGAL のインストール

Windows での cgal のインストール(Windows 上): 別ページ »で説明している.

Ubuntu での CGAL のインストール

Ubuntu でインストールを行うには,次のコマンドを実行.

sudo apt -y update
sudo apt -y install libcgal-dev libcgal-qt5-dev

Chandrika Deb の顔マスク検出 (Chandrika Deb's Face Mask Detection) および顔のデータセット

写真やビデオから,マスクありの顔と,マスク無しの顔を検出する技術およびソフトウェア. 顔検出,マスク有りの顔とマスク無しの顔の分類を同時に行っている. MobileNetV2 (ディープニューラルネットワーク)を使用.

ソースコードは公開されており,画像を追加して学習をやり直すことも可能

Bing Search API, Kaggle dataset, RMDF dataset から収集された顔のデータセット(マスクあり: 2165 枚,マスクなし 1930 枚)が同封.

関連する外部ページ

関連項目cabani の MaskedFace-Net データセット, Face Mask Detection, マスク付き顔の処理 顔検出 (face detection)

Google Colaboratory で,Chandrika Deb による顔マスク検出の実行

次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する).

  1. インストール
    !rm -rf Face-Mask-Detection
    !git clone https://github.com/chandrikadeb7/Face-Mask-Detection
    %cd Face-Mask-Detection
    !pip3 install -U -r requirements.txt
    

    [image]
  2. 学習

    Chandrika Deb の顔マスク検出に同封のデータセット(Deb Bing Search API, Kaggle dataset, RMDF dataset から収集された顔のデータセット(マスクあり: 2165 枚,マスクなし 1930 枚)により学習を行う.

    !python3 train_mask_detector.py --dataset dataset
    

    [image]
  3. 顔マスク検出の実行
    !sed -i -e 's/cv2.imshow("Output", image)/cv2.imwrite("result.png", image)/g' detect_mask_image.py
    !sed -i -e 's/cv2.waitKey(0)//g' detect_mask_image.py
    !python3 detect_mask_image.py --image images/pic1.jpeg
    from PIL import Image
    Image.open('result.png').show()
    

    [image]
  4. 手持ちの画像で顔マスク検出の実行

    curl は URL を指定して画像ファイルをダウンロードしている.

    !curl -O https://www.kkaneko.jp/sample/face/3284.png
    !python3 detect_mask_image.py --image 3284.png
    from PIL import Image
    Image.open('result.png').show()
    

    [image]
    !curl -O https://www.kkaneko.jp/sample/face/3288.png
    !python3 detect_mask_image.py --image 3288.png
    from PIL import Image
    Image.open('result.png').show()
    

    [image]
Windows での Chandrika Deb の顔マスク検出のインストールと学習と顔マスク検出

chandrikadeb7 / Face-Mask-Detection のインストールと動作確認(マスク有り顔,マスクなし顔の検出)(Python,TensorFlow を使用)(Windows 上): 別ページで説明

Ubuntu での Chandrika Deb の顔マスク検出のインストールと学習と顔マスク検出

前準備:事前に Python のインストール: 別項目で説明している., NVIDIA CUDA ツールキットNVIDIA cuDNN のインストール: 別項目で説明している.を行うこと.

  1. Ubuntu でインストールを行うには,次のコマンドを実行.
    sudo apt -y update
    sudo apt -y install git
    
    cd /usr/local
    sudo rm -rf Face-Mask-Detection
    sudo git clone https://github.com/chandrikadeb7/Face-Mask-Detection
    sudo chown -R $USER Face-Mask-Detection
    
    # システム Python の環境とは別の Python の仮想環境システム Python を使用)を作成
    sudo apt -y update
    sudo apt -y install python3-venv
    python3 -m venv ~/a
    source ~/a/bin/activate
    
    cd /usr/local/Face-Mask-Detection
    pip install -U -r requirements.txt
    pip list
    
  2. 学習

    Chandrika Deb の顔マスク検出に同封のデータセット(Deb Bing Search API, Kaggle dataset, RMDF dataset から収集された顔のデータセット(マスクあり: 2165 枚,マスクなし 1930 枚)により学習を行う. その後,顔マスク検出を行う.

    source ~/a/bin/activate
    cd /usr/local/Face-Mask-Detection
    python train_mask_detector.py --dataset dataset
    
  3. 顔マスク検出の実行

    「python detect_mask_video.py 」はカメラの顔マスク検出を行う.

    python detect_mask_image.py --image images/pic1.jpeg
    python detect_mask_video.py 
    

    [image]

Chaudhury らの画像補正 (image rectification)

画像補正は,画像を射影変換することにより,斜め方向からの撮影画像を正面画像に変換する. 意図しないカメラ回転(ロール、ピッチ、ヨー)を含む画像を正面画像に補正できる.

また,AIの事前学習は,通常,正面画像で行われることが多く,画像補正を使うことで,AIの推論をより精度よく行うことができると期待できる.

[image] [image]

文献

Chaudhury, Krishnendu, Stephen DiVerdi, and Sergey Ioffe. "Auto-rectification of user photos." 2014 IEEE International Conference on Image Processing (ICIP). IEEE, 2014.

資料

PDFファイル, パワーポイントファイル

サイト内の関連ページ

関連する外部ページ

GitHub のページ: https://github.com/chsasank/Image-Rectification

CIFAR-10 データセット

CIFAR-10 データセット(Canadian Institute for Advanced Research, 10 classes)は,公開されているデータセット(オープンデータ)である.

CIFAR-10 データセット(Canadian Institute for Advanced Research, 10 classes) は,クラス数 10 の カラー画像と,各画像に付いたのラベルから構成されるデータセットである. 機械学習での画像分類の学習や検証に利用できる.

文献

Alex Krizhevsky, Vinod Nair, and Geoffrey Hinton. 'Learning multiple layers of features from tiny images', Alex Krizhevsky, 2009.

サイト内の関連ページ

関連する外部ページ

関連項目CIFAR-100 データセット(Canadian Institute for Advanced Research, 100 classes), Keras に付属のデータセット, TensorFlow データセット, オープンデータ, 画像分類

Python での CIFAR-10 データセットのロード(TensorFlow データセットを使用)

次の Python プログラムは,TensorFlow データセットから,CIFAR-10 データセットのロードを行う. x_train, y_train が学習用のデータ.x_test, y_test が検証用のデータになる.

次のプログラムでは、x_train と y_train を 25枚分表示することにより,x_train と y_train が,画像であることが確認できる.

tensorflow_datasets の loadで, 「batch_size = -1」を指定して,一括読み込みを行っている.

from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
import numpy as np
import tensorflow_datasets as tfds

%matplotlib inline
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')   # Suppress Matplotlib warnings

# CIFAR-10 データセットのロード
cifar10, cifar10_metadata = tfds.load('cifar10', with_info = True, shuffle_files=True, as_supervised=True, batch_size = -1)
x_train, y_train, x_test, y_test = cifar10['train'][0], cifar10['train'][1], cifar10['test'][0], cifar10['test'][1]

plt.style.use('default')
plt.figure(figsize=(10,10))
for i in range(25):
    plt.subplot(5,5,i+1)
    plt.xticks([])
    plt.yticks([])
    plt.grid(False)
# squeeze は,サイズ1の次元を削除.numpy は tf.Tensor を numpy に変換
    plt.imshow(np.squeeze(x_train[i]), cmap=plt.cm.binary)
    plt.xlabel(y_train[i].numpy())

# 確認表示
plt.show()

[image]
Python での CIFAR-10 データセットのロード(Keras を使用)

次の Python プログラムは,Keras に付属のデータセットの中にある CIFAR-10 データセットのロードを行う. x_train, y_train が学習用のデータ.x_test, y_test が検証用のデータになる.

次のプログラムでは,x_train と y_train を 25枚分表示することにより,x_train と y_train が,カラー画像であることが確認できる.

import tensorflow.keras
from tensorflow.keras.datasets import cifar10
%matplotlib inline
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')   # Suppress Matplotlib warnings

# CIFAR-10 データセットのロード
(x_train, y_train), (x_test, y_test) = cifar10.load_data()

plt.style.use('default')
plt.figure(figsize=(10,10))
for i in range(25):
    plt.subplot(5,5,i+1)
    plt.xticks([])
    plt.yticks([])
    plt.grid(False)
    plt.imshow(x_train[i], cmap=plt.cm.binary)
    plt.xlabel(y_train[i])

# 確認表示
plt.show()

[image]
CIFAR-10 データセットのロードと正規化

次の Python プログラムは,TensorFlow データセットから,CIFAR-10 データセットのロードを行う. x_train, y_train が学習用のデータ.x_test, y_test が検証用のデータになる.

次のプログラムでは、x_train と y_train を 25枚分表示することにより,x_train と y_train が,画像であることが確認できる.

tensorflow_datasets の loadで, 「batch_size = -1」を指定して,一括読み込みを行っている.

ロードの後,正規化を行う.type は型,shape はサイズ,np.max と np.mi は最大値と最小値.

from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
import numpy as np
import tensorflow_datasets as tfds

%matplotlib inline
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')   # Suppress Matplotlib warnings

# CIFAR-10 データセットのロード
cifar10, cifar10_metadata = tfds.load('cifar10', with_info = True, shuffle_files=True, as_supervised=True, batch_size = -1)
x_train, y_train, x_test, y_test = cifar10['train'][0], cifar10['train'][1], cifar10['test'][0], cifar10['test'][1]

plt.style.use('default')
plt.figure(figsize=(10,10))
for i in range(25):
    plt.subplot(5,5,i+1)
    plt.xticks([])
    plt.yticks([])
    plt.grid(False)
# squeeze は,サイズ1の次元を削除.numpy は tf.Tensor を numpy に変換
    plt.imshow(np.squeeze(x_train[i]), cmap=plt.cm.binary)
    plt.xlabel(y_train[i].numpy())

# 確認表示
plt.show()

# メタデータの表示
print(cifar10_metadata)

# 正規化
# 【x_train, x_test, y_train, y_test の numpy ndarray への変換と,値の範囲の調整(値の範囲が 0 〜 255 であるのを,0 〜 1 に調整)】
x_train = x_train.numpy().astype("float32") / 255.0
x_test = x_test.numpy().astype("float32") / 255.0
y_train = y_train.numpy()
y_test = y_test.numpy()
print(type(x_train), x_train.shape, np.max(x_train), np.min(x_train))
print(type(x_test), x_test.shape, np.max(x_test), np.min(x_test))
print(type(y_train), y_train.shape, np.max(y_train), np.min(y_train))
print(type(y_test), y_test.shape, np.max(y_test), np.min(y_test))

[image]

CIFAR-100 データセット

CIFAR-100 データセット(Canadian Institute for Advanced Research, 100 classes)は,公開されているデータセット(オープンデータ)である.

CIFAR-100 データセット(Canadian Institute for Advanced Research, 100 classes) は,機械学習での画像分類の学習や検証に利用できるデータセット.

文献

Alex Krizhevsky, Vinod Nair, and Geoffrey Hinton. Learning multiple layers of features from tiny images, Alex Krizhevsky, 2009.

サイト内の関連ページ

関連する外部ページ

関連項目CIFAR-10 データセット(Canadian Institute for Advanced Research, 10 classes), Keras に付属のデータセット, TensorFlow データセット, オープンデータ, 画像分類

Python での CIFAR-100 データセットのロード(TensorFlow データセットを使用)

次の Python プログラムは,TensorFlow データセットから,CIFAR-100 データセットのロードを行う. x_train, y_train が学習用のデータ.x_test, y_test が検証用のデータになる.

次のプログラムでは、x_train と y_train を 25枚分表示することにより,x_train と y_train が,画像であることが確認できる.

tensorflow_datasets の loadで, 「batch_size = -1」を指定して,一括読み込みを行っている.

from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
import numpy as np
import tensorflow_datasets as tfds

%matplotlib inline
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')   # Suppress Matplotlib warnings

# CIFAR-100 データセットのロード
cifar100, cifar100_metadata = tfds.load('cifar100', with_info = True, shuffle_files=True, as_supervised=True, batch_size = -1)
x_train, y_train, x_test, y_test = cifar100['train'][0], cifar100['train'][1], cifar100['test'][0], cifar100['test'][1]

plt.style.use('default')
plt.figure(figsize=(10,10))
for i in range(25):
    plt.subplot(5,5,i+1)
    plt.xticks([])
    plt.yticks([])
    plt.grid(False)
# squeeze は,サイズ1の次元を削除.numpy は tf.Tensor を numpy に変換
    plt.imshow(np.squeeze(x_train[i]), cmap=plt.cm.binary)
    plt.xlabel(y_train[i].numpy())

# 確認表示
plt.show()

[image]
CIFAR-100 データセットのロードと正規化

次の Python プログラムは,TensorFlow データセットから,CIFAR-100 データセットのロードを行う. x_train, y_train が学習用のデータ.x_test, y_test が検証用のデータになる.

次のプログラムでは、x_train と y_train を 25枚分表示することにより,x_train と y_train が,画像であることが確認できる.

tensorflow_datasets の loadで, 「batch_size = -1」を指定して,一括読み込みを行っている.

ロードの後,正規化を行う.type は型,shape はサイズ,np.max と np.mi は最大値と最小値.

from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
import numpy as np
import tensorflow_datasets as tfds

%matplotlib inline
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')   # Suppress Matplotlib warnings

# CIFAR-100 データセットのロード
cifar100, cifar100_metadata = tfds.load('cifar100', with_info = True, shuffle_files=True, as_supervised=True, batch_size = -1)
x_train, y_train, x_test, y_test = cifar100['train'][0], cifar100['train'][1], cifar100['test'][0], cifar100['test'][1]

plt.style.use('default')
plt.figure(figsize=(10,10))
for i in range(25):
    plt.subplot(5,5,i+1)
    plt.xticks([])
    plt.yticks([])
    plt.grid(False)
# squeeze は,サイズ1の次元を削除.numpy は tf.Tensor を numpy に変換
    plt.imshow(np.squeeze(x_train[i]), cmap=plt.cm.binary)
    plt.xlabel(y_train[i].numpy())

# 確認表示
plt.show()

# メタデータの表示
print(cifar100_metadata)

# 正規化
# 【x_train, x_test, y_train, y_test の numpy ndarray への変換と,値の範囲の調整(値の範囲が 0 〜 255 であるのを,0 〜 1 に調整)】
x_train = x_train.numpy().astype("float32") / 255.0
x_test = x_test.numpy().astype("float32") / 255.0
y_train = y_train.numpy()
y_test = y_test.numpy()
print(type(x_train), x_train.shape, np.max(x_train), np.min(x_train))
print(type(x_test), x_test.shape, np.max(x_test), np.min(x_test))
print(type(y_train), y_train.shape, np.max(y_train), np.min(y_train))
print(type(y_test), y_test.shape, np.max(y_test), np.min(y_test))

[image]

Cityscapes データセット

Cityscapes データセット は,車両と人が撮影されたアノテーション済の画像データ. 機械学習での セマンティック・セグメンテーション (semantic segmentation)インスタンス・セグメンテーション (instance segmentation) に利用できるデータセットである.

Cityscapes データセットは, 50都市の数ヶ月間(春,夏,秋)の日中,良好な/中程度の天候のもとで撮影,計測されたデータである.データの種類は次の通りである.

画像数は,合計で,24998 枚であり,その内訳は次のとおりである.

クラスは次の通りである.これらクラス以外に「unlabeled」がある.

road, sidewalk, parking, rail track, person, rider, car, truck, bus, on rails, motorcycle, bicycle, caravan, trailer, building, wall, fence, guard rail, bridge, tunnel, pole, pole group, traffic sign, traffic light, vegetation, terrain, sky, ground, dynamic, static

これらクラスは,次のようにグループ化されている. (flat などがグループ名である).

クラスの説明は次のページにある.

Cityscapes データセットは次の URL で公開されているデータセット(オープンデータ)である.利用には登録が必要である.

https://www.cityscapes-dataset.com/

【関連情報】

関連項目Detectron2, MMSegmentation, OpenMMLab, PANet

Cityscapes データセットの train and val と test のダウンロード

Cityscapes データセットの train and val と test は,合計で 5000枚の画像と関連データである.

train and val と test の Ground Truth と画像のダウンロードのため, gtFine,leftImg8bit のダウンロードを行うときは, Cityscapes データセットのダウンロードのページで,次を選ぶ. (必要最小限のダウンロードを行うこと).

Cityscape データセットのページ: https://www.cityscapes-dataset.com/

Clang

Clang は,LLVMのサブプロジェクトである. C言語ファミリ(C,C++,Objective C/C++,OpenCL,CUDA,RenderScript)の機能, GCC互換のコンパイラドライバ (clang) の機能, MSVC互換のコンパイラドライバ (clang-cl.exe) の機能を持つ.

【関連する外部ページ】

サイト内の関連ページ

関連項目LLVM

clapack

clapack は,元々 FORTRAN で書かれていた LAPACK の,C言語版 (C 言語に書き直されたもの)である. lapack は,行列に関する種々の問題(連立1次方程式,固有値問題,などなど多数)を解く機能を持つソフトウェア.BLAS の機能を使う.

関連項目lapack, OpenBLAS

Windows での clapack のインストール

Windows での clapack のインストール(Windows 上): 別ページ »で説明している.

Class Activation Mapping (CAM)

Class Activation Mapping (CAM) は, Bolei Zhou により,2016年に提案された.

関連項目CASILVision

CRAFT

CRAFT は,文字検出の一手法.

[image]

文献】 Youngmin Baek, Bado Lee, Dongyoon Han, Sangdoo Yun, and Hwalsuk Lee, Character Region Awareness for Text Detection, Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, pp. 9365--9374, 2019.

関連する外部ページ

GitHub のページ: https://github.com/clovaai/CRAFT-pytorch

関連項目EasyOCR

Windows で,CRAFT のインストールと動作確認(テキスト検出)

CRAFT のインストールと動作確認(テキスト検出)(Python,PyTorch を使用)(Windows 上): 別ページ »で説明している.

crowd counting (群衆の数のカウントと位置の把握)

crowd countingは, 画像内の人数を数えること. 監視等に役立つ. さまざま状況において, さまざまな大きさで画像内にある人物を数えることが課題であり, 画像からの物体検出とは研究課題が異なる.

【関連用語】 FIDTM, JHU-CROWD++ データセット, NWPU-Crowd データセット, ShanghaiTech データセット, UCF-QNRF データセット

CLIP

CLIP(Contrastive Language-Image Pre-Training)では, テキスト画像のペアを用いて学習が行われる. GPT-2,GPT-3 のゼロショット学習 (zero-shot learning) のゼロショットと同様に, 画像に対して,テキストが結果として求まる. CLIP は,ImageNet データセット のゼロショットに対して, ResNet50と同等の性能があるとされる.

CLIP の GitHub のページ: https://github.com/openai/CLIP

CLIP のサンプルプログラムの実行結果は次の通り.

[image]

関連項目AltCLIP

cmake

cmake は,ソフトウェアのソースコードからのビルドを簡単に行えるようにするためのソフトウェアである.

cmake のオプションは,Windows では cmake-gui コマンド,Ubuntu など linux 系では ccmake コマンドで確認できる.

cmake のジェネレータについて: 別ページ »で説明している.

cmake の使い方の例: 別ページ »で説明している.

CMake の公式ダウンロードページ: https://cmake.org/download/

Windows での cmake のインストール

Windows での cmake のインストールには,複数の方法がある.次のいずれかによりインストールできる.

Ubuntu での cmake のインストール

Ubuntu では,端末で,次のコマンドを実行して,cmake をインストールする.

sudo apt -y update
sudo apt -y install cmake cmake-curses-gui cmake-gui

ソースコードからビルドする場合には,次のように操作する.

sudo apt -y update
sudo apt -y install build-essential gcc g++ make
sudo apt -y install git cmake cmake-curses-gui cmake-gui
cd /tmp
curl -L -O https://github.com/Kitware/CMake/releases/download/v3.22.2/cmake-3.22.2.tar.gz
tar -xvzof cmake-3.22.2.tar.gz
cd cmake-3.22.2
./configure --prefix=/usr/local
make
sudo make install

C-MS-Celeb Cleaned データセット

C-MS-Celeb Cleaned データセット は, MS-Celeb-1M データセット を整えたもの.間違いの修正など.

人物数は 94,682 (94,682 identities), 画像数は 6,464,018 枚 (6,464,018 images)

次の URL で公開されているデータセット(オープンデータ)である.

https://github.com/EB-Dodo/C-MS-Celeb

関連項目顔のデータベース, MS-Celeb-1M データセット, 顔検出 (face detection)

CNN

CNN (convolutional neural network) は畳み込みニューラルネットワークのこと.

CNTK

COCO (Common Object in Context) データセット

COCO(Common Object in Context)データセットは,物体検出やセグメンテーション,キーポイント検出,姿勢推定,画像分類,キャプショニング等の多様なタスクに対応可能な画像データセットとして,2014年にMicrosoftにより公開された.これは,人間や自動車,家具,食品等,多岐にわたるカテゴリのオブジェクトを含む数十万枚以上の画像から構成され,それぞれの画像は,80種類のカテゴリに対応する形でアノテーションが施されている. COCO は次の URL で公開されているデータセット(オープンデータ)である.

URL: https://cocodataset.org/

COCO は,以下の特徴がある.

COCO の 80 のクラスのラベルは次の通りである.

['person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush']

文献

Tsung-Yi Lin, Michael Maire, Serge Belongie, Lubomir Bourdev, Ross Girshick, James Hays, Pietro Perona, Deva Ramanan, C. Lawrence Zitnick, Piotr Dollr, Microsoft COCO: Common Objects in Context, CoRR, abs/1405.0312, 2014.

https://arxiv.org/pdf/1405.0312v3.pdf

サイト内の関連ページ

COCO 2017 データセットのダウンロードとカテゴリ情報や画像情報の確認(Windows 上): 別ページ »で説明している.

関連する外部ページ

関連項目pycocotools, 物体検出, インスタンス・セグメンテーション (instance segmentation), keypoint detection, panoptic segmentation, セマンティック・セグメンテーション (semantic segmentation)

Windows での COCO 2014 データセットのダウンロードと展開

Windows での COCO 2014 のダウンロードと展開の手順は次の通り.

  1. COCO データセットの公式ページから, 2017 Train images, 2017 Val images, 2017 Train/Val annotations をダウンロード

    COCO データセットの公式ページ: https://cocodataset.org/#home

    コマンドプロンプトを管理者として開き ダウンロードのため,次のコマンドを実行

    cd %LOCALAPPDATA%
    curl -O http://images.cocodataset.org/zips/train2017.zip
    curl -O http://images.cocodataset.org/zips/val2014.zip
    curl -O http://images.cocodataset.org/zips/test2017.zip
    curl -O http://images.cocodataset.org/annotations/annotations_trainval2014.zip
    
  2. train2017.zip, val2014.zip, test2017.zip, annotations_trainval2014.zip がダウンロードされる
  3. 展開のため,次のコマンドを実行
    cd %LOCALAPPDATA%
    powershell -command "Expand-Archive -DestinationPath . -Path train2014.zip"
    powershell -command "Expand-Archive -DestinationPath . -Path val2014.zip"
    powershell -command "Expand-Archive -DestinationPath . -Path test2014.zip"
    powershell -command "Expand-Archive -DestinationPath . -Path annotations_trainval2014.zip"
    
  4. ファイルの配置は次のようになる.
     └── COCO_DATASET_ROOT
         |
         ├── annotations
            ├── stuff_train2014.json (the original json files)
            ├── stuff_test2014.json (the original json files)
            ├── stuff_val2014.json (the original json files)
    
         ├── train2014
         ├── test2014
         └── val2014
    
Ubuntu での COCO 2017 データセットのダウンロードと展開

Ubuntu の場合.次により,/usr/local/mscoco2014, /usr/local/mscoco2017 にダウンロードされる.

`sudo mkdir cd /usr/local/coco2017
sudo chown -R $USER /usr/local/coco2017
cd /usr/local/coco2017
# labels
curl -O -L https://github.com/ultralytics/yolov5/releases/download/v1.0/coco2017labels-segments.zip
unzip coco2017labels-segments.zip
cd /usr/local/coco2017
# 19G, 118k images
curl -O http://images.cocodataset.org/zips/train2017.zip
unzip -d /usr/local/coco2017/coco train2017.zip
# 1G, 5k images
curl -O http://images.cocodataset.org/zips/val2017.zip
unzip -d /usr/local/coco2017/coco val2017.zip
# 7G, 41k images (optional)
curl -O http://images.cocodataset.org/zips/test2017.zip
unzip -d /usr/local/coco2017/coco test2017.zip
#
curl -O http://images.cocodataset.org/annotations/annotations_trainval2017.zip
unzip -d annotations_trainval2017.zip
#
curl -O http://images.cocodataset.org/annotations/stuff_annotations_trainval2017.zip
unzip -d stuff_annotations_trainval2017.zip
#
curl -O http://images.cocodataset.org/annotations/panoptic_annotations_trainval2017.zip
unzip -d panoptic_annotations_trainval2017.zip

#
sudo mkdir cd /usr/local/coco2014
sudo chown -R $USER /usr/local/coco2014
cd /usr/local/coco2014
curl -O http://images.cocodataset.org/zips/train2014.zip
curl -O http://images.cocodataset.org/zips/val2014.zip
curl -O http://images.cocodataset.org/zips/test2014.zip
curl -O http://images.cocodataset.org/annotations/annotations_trainval2014.zip
unzip -d train2014.zip
unzip -d val2014.zip
unzip -d test2014.zip
unzip -d annotations_trainval2014.zip

ファイルの配置は次のようになる(現在確認中).

coco2014/
  annotations/
  images/
  objectInfo150.txt
  sceneCategories.txt

coco2017/
  coco/
    annotations/
    images/
      train2017/
      val2017/
      test2017/
    labels/
    objectInfo150.txt
    sceneCategories.txt
Windows で COCO の Python API のインストール

cocoapi のインストールを行う. cocoapi は, COCO (Common Object in Context) データセット の Python API である.

  1. Windows では,コマンドプロン プトを管理者として実行
  2. pycocotools のインストール
    python -m pip install -U cython
    python -m pip install "git+https://github.com/philferriere/cocoapi.git#egg=pycocotools&subdirectory=PythonAPI"
    

    [image]
  3. COCO 2018 Panoptic Segmentation Task API のインストール

    Windows では,コマンドプロン プトを管理者として実行し, 次のコマンドを実行する.

    python -m pip install git+https://github.com/cocodataset/panopticapi.git
    

COCO の Keypoints 2014/2017 アノテーション

URL: https://cocodataset.org/#keypoints-2017

COCO の Keypoints 2014/2017 アノテーションは,次からダウンロードできる.

COLMAP

COLMAP は 3次元再構成の機能を持ったソフトウェア.

文献

Johannes L. Schonberger, Jan-Michael Frahm, Structure-From-Motion Revisited, CVPR 2016, 2016

https://openaccess.thecvf.com/content_cvpr_2016/papers/Schonberger_Structure-From-Motion_Revisited_CVPR_2016_paper.pdf

サイト内の関連ページ

関連する外部ページ

Coqui TTS

Coqui TTS は,音声合成および音声変換(Voice Changer)の研究プロジェクトならびに成果物.

Coqui の GitHub のページ: https://github.com/coqui-ai/TTS

関連項目音声合成 (Text To Speech; TTS)

Google Colaboratory で,Coqui TTS の顔マスク検出の実行

公式の手順(https://github.com/coqui-ai/TTS/tree/dev#install-tts)に従う.

次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する).

次のコマンドを実行.することにより,Coqui TTS のインストール,日本語のモデル類のダウンロード, 音声合成の実行が行われる. 結果は,tts_output.wav にできる.

!pip3 install TTS[all]
!rm -rf TTS
!git clone https://github.com/coqui-ai/TTS
%cd TTS
!pip3 install -e .[all]
!make system-deps
!make install
!python3 setup.py install
!tts --list_models
!tts --text "日本国民は正当に選挙された国会における代表者を通じて行動し、われらとわれらの子孫のために、諸国民と協和による成果と、わが国全土にわたって自由のもたらす恵沢を確保し、政府の行為によって再び戦争の惨禍が起こることのないようにすることを決意し、ここに主権が国民に存することを宣言し、この憲法を確定する。そもそも国政は国民の厳粛な信託によるものであって、その権威は国民に由来し、その権力は国民の代表者がこれを行使し、その福利は国民がこれを享受する。これは人類普遍の原理であり、この憲法は、かかる原理に基づくものである。われらはこれに反する一切の憲法、法令及び詔勅を排除する。" --model_name "tts_models/ja/kokoro/tacotron2-DDC" --vocoder_name "vocoder_models/ja/kokoro/hifigan_v1"

[image]
Ubuntu での Coqui TTS のインストールとテスト実行

公式の手順(https://github.com/coqui-ai/TTS/tree/dev#install-tts)に従う.

次のコマンドを実行.することにより,Coqui TTS のインストール,日本語のモデル類のダウンロード, 音声合成の実行が行われる. 結果は,tts_output.wav にできる.

cd /usr/local
sudo pip3 install TTS[all]
sudo rm -rf TTS
sudo git clone https://github.com/coqui-ai/TTS
cd TTS
sudo pip3 install -e .[all]
sudo make system-deps
sudo make install
sudo python3 setup.py install
tts --list_models
tts --text "日本国民は正当に選挙された国会における代表者を通じて行動し、われらとわれらの子孫のために、諸国民と協和による成果と、わが国全土にわたって自由のもたらす恵沢を確保し、政府の行為によって再び戦争の惨禍が起こることのないようにすることを決意し、ここに主権が国民に存することを宣言し、この憲法を確定する。そもそも国政は国民の厳粛な信託によるものであって、その権威は国民に由来し、その権力は国民の代表者がこれを行使し、その福利は国民がこれを享受する。これは人類普遍の原理であり、この憲法は、かかる原理に基づくものである。われらはこれに反する一切の憲法、法令及び詔勅を排除する。" --model_name "tts_models/ja/kokoro/tacotron2-DDC" --vocoder_name "vocoder_models/ja/kokoro/hifigan_v1"

CoTracker

CoTracker は、動画のポイントトラッキングの一手法である。 この手法は、長期間の追跡やオクルージョン(遮蔽)の取り扱いの難しさに対処するために開発された。 CoTracker では、ポイントをグループとして追跡する方法、つまりグループベースのアプローチを採用しており、ポイント間の相互関係を活用する。さらに、時間的なスライディングウィンドウメカニズムを使用して、長期間にわたる追跡を行う。実験結果からは、co-trackingが既存の手法に比べて、オクルージョンや長期間のビデオに対する追跡の安定性が向上したことが示されている。

文献

Nikita Karaev, Ignacio Rocco, Benjamin Graham, Natalia Neverova, Andrea Vedaldi, Christian Rupprecht, CoTracker: It is Better to Track Together, arXiv:2307.07635v1, 2023.

https://arxiv.org/pdf/2307.07635v1.pdf

関連する外部ページ

CSPNet (Cross Stage Parital Network)

CSPNet は,ステージの最初の特徴マップ (feature map) と最後の特徴マップ (feature map) を統合することを特徴とする手法.

CSPNet は, ResNet, ResNeXt, DenseNet などに適用でき, ImageNet データセットを用いた画像分類の実験では,計算コスト,メモリ使用量,推論の速度,推論の精度の向上ができるとされている. その結果として,物体検出 についても改善ができるとされている.

CSPNet の公式の実装 (GitHub) のページでは, 画像分類として, CSPDarkNet-53, CSPResNet50, CSPResNeXt-50, 物体検出として, CSPDarknet53-PANet-SPP, CSPResNet50-PANet-SPP, CSPResNeXt50-PANet-SPP 等の実装が公開されている.

Scaled YOLO v4 では,CSPNet の技術が使われている.

【関連用語】 AlexeyAB darknet, 画像分類, 物体検出, Scaled YOLO v4, pytorchimagemodels

csvkit

csvkit は,CSV ファイルを操作する機能を持ったソフトウェア.

csvkit の公式ドキュメント: https://csvkit.readthedocs.io/en/latest/

【主な機能】

csvkit 及び類似ソフトウェアのインストール

csvkit 及び類似ソフトウェアのインストールは次のような手順になる.

csvkit に同封されているデータファイル

次の URL で公開されている.

URL: https://github.com/wireservice/csvkit/tree/master/examples/realdata

上の URL をWebブラウザで開くか,次のコマンドでダウンロードできる.

curl -L -O https://raw.githubusercontent.com/wireservice/csvkit/master/examples/realdata/ne_1033_data.xlsx

CoRR

Computing Research Repository を,縮めて 「CoRR」という. URL は次の通り.

CoRR の URL: https://arxiv.org/corr

cudart64_100.dll

cudart64_100.dll は,NVIDIA CUDA 10.0 のファイル. NVIDIA CUDA 10.0 をインストールすることにより, cudart64_100.dll を得ることができる.

cudart64_101.dll

cudart64_101.dll は,NVIDIA CUDA 10.1 のファイル. NVIDIA CUDA 10.1 をインストールすることにより, cudart64_101.dll を得ることができる.

cudart64_110.dll

cudart64_110.dll は,NVIDIA CUDA 11 のファイル. NVIDIA CUDA 11 をインストールすることにより, cudart64_110.dll を得ることができる.

cudnn64_7.dll

cudnn64_7.dll は,NVIDIA cuDNN 7 のファイル. NVIDIA cuDNN 7 (例えば,NVIDIA cuDNN 7.6.5) をインストールすることにより, cudnn64_7.dll を得ることができる.

Windows では,次の操作により,cudnn64_7.dllパスが通っていることを確認する.

Windowsコマンドプロンプトを開き、次のコマンドを実行する.エラーメッセージが出ないことを確認.

where cudnn64_7.dll

【関連情報】

cudnn64_8.dll

cudnn64_8.dll は,NVIDIA cuDNN v8 のファイル. NVIDIA cuDNN v8 をインストールすることにより, cudnn64_8.dll を得ることができる.

Windows では,次の操作により,cudnn64_8.dllパスが通っていることを確認する.

Windowsコマンドプロンプトを開き、次のコマンドを実行する.エラーメッセージが出ないことを確認.

where cudnn64_8.dll

[image]

【関連情報】

curl のインストール

  • curl の URL: https://curl.se/

    CuRRET データベース (Columbia-Utrecht Reflectance and Texture Database)

    反射率とテクスチャに関するデータベース

    CuRRET データベース (Columbia-Utrecht Reflectance and Texture Database)は次の URL で公開されているデータセット(オープンデータ)である.

    URL: https://www.cs.columbia.edu/CAVE/software/curet/html/about.php

    DeepFace

    DeepFace は,ArcFace 法による顔識別の機能や,顔検出,年齢や性別や表情の推定の機能などを持つ.

    ArcFace 法は,距離学習の技術の1つである. 画像分類において,種類が不定個であるような画像分類に使うことができる技術である. 顔のみで動くということではないし, 顔の特徴を捉えて工夫されているということもない.

    DeepFace の URL: https://github.com/serengil/deepface

    ArcFace 法の概要は次の通り

    関連項目ArcFace 法, 顔検出, 顔識別 (face identification), 顔認識, 顔に関する処理

    実験するときは,顔の部分だけを切り出す作業をペイントソフトなどで行い,その後実験に進むと良いと思います.

    Google Colaboratory で,DeepFace による顔識別の実行,年齢,性別,表情の推定の実行

    次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する).

    1. インストールと設定
      !pip3 install deepface
      !git clone --recursive https://github.com/serengil/deepface
      
      from deepface import DeepFace
      import pandas as pd
      pd.set_option('display.max_rows', None)
      print(pd.get_option('display.max_rows'))
      

      [image]

    2. 顔画像の準備

      単一のディレクトリ ./deepface/tests/dataset に,処理したい顔画像をすべて入れておく

    3. 顔識別の実行

      ディレクトリ内の全画像ファイルとの顔識別を行い,それぞれの顔画像ファイルとの距離を表示.

      df = DeepFace.find(img_path="./deepface/tests/dataset/img38.jpg", db_path="./deepface/tests/dataset", distance_metric='euclidean')
      a = df.sort_values('VGG-Face_euclidean')
      print(a)
      

      [image]

    4. 年齢,性別,表情の推定の実行
      obj = DeepFace.analyze(img_path = "./deepface/tests/dataset/img38.jpg", actions = ['age', 'gender', 'emotion'])
      print(obj)
      

      [image]

    DeepForge

    DeepForge は,ディープラーニングのソフトウェア一式.Webサーバも付属していて,Webブラウザからディープラーニングのソフトウェアの作成,実行,保存が簡単にできる.ソフトウェアの作成は,Webブラウザ上でのエディタでも,Webブラウザ上でのビジュアルなエディタでもできる.ディープラーニングでのニューラルネットワークの構造が図で簡単に確認できて便利

    サイト内の関連ページ

    関連する外部ページ

    DeepLab2

    DeepLab2 は,セグメンテーションの機能を持つ TensorFlow のライブラリである. DeepLab, Panoptic-DeepLab, Axial-Deeplab, Max-DeepLab, Motion-DeepLab, ViP-DeepLab を含む.

    DeepLab2 の公式のデモ(Google Colaboratory のページ)の実行により,下図のように panoptic segmentation の結果が表示される.

    そのデモのページの URL: https://colab.research.google.com/github/google-research/deeplab2/blob/main/DeepLab_Demo.ipynb#scrollTo=6552FXlAOHnX

    [image]

    文献

    Mark Weber, Huiyu Wang, Siyuan Qiao, Jun Xie, Maxwell D. Collins, Yukun Zhu, Liangzhe Yuan, Dahun Kim, Qihang Yu, Daniel Cremers, Laura Leal-Taixe, Alan L. Yuille, Florian Schroff, Hartwig Adam, Liang-Chieh Chen, DeepLab2: A TensorFlow Library for Deep Labeling, CoRR, abs/2106.09748v1, 2021.

    サイト内の関連ページ

    Windows で動く人工知能関係 Pythonアプリケーション,オープンソースソフトウエア): 別ページ »で説明している.

    関連する外部ページ

    関連項目セマンティック・セグメンテーション (semantic segmentation), panoptic segmentation, depth estimation

    Deeplab2 のインストール(Windows 上)
    1. プロトコル・バッファ・コンパイラ (protocol buffer compiler) のインストールを行っておく
    2. コマンドプロンプトを管理者として開く.
    3. Deeplab2 のダウンロード,前提ソフトウエアのインストール

      Deeplab2 を動かすため,protobuf==3.19.6

      cd c:\
      rmdir /s /q c:\deeplab2
      mkdir c:\deeplab2
      cd c:\deeplab2
      git clone https://github.com/google-research/deeplab2.git
      python -m pip install -U tensorflow==2.10.1 protobuf==3.19.6
      
    4. protoc を用いてコンパイル
      cd c:\deeplab2
      protoc deeplab2\*.proto --python_out=.
      

      [image]
    5. Windowsシステム環境変数 PYTHONPATHに,c:\deeplab2追加することにより,パスを通す

      Windows で,コマンドプロンプト管理者として実行

      コマンドプロンプトを管理者として実行: 別ページ »で説明

      powershell -command "$oldpath = [System.Environment]::GetEnvironmentVariable(\"PYTHONPATH\", \"Machine\"); $oldpath += \";c:\deeplab2\"; [System.Environment]::SetEnvironmentVariable(\"PYTHONPATH\", $oldpath, \"Machine\")"
      

      [image]
    6. 新しくコマンドプロンプトを開き,動作確認
      
      
      cd c:\deeplab2\deeplab2\model
      python deeplab_test.py
      
    Deeplab2 のインストール(Ubuntu 上)

    ttps://github.com/google-research/deeplab2/blob/main/g3doc/setup/installation.md の記載による.

    1. protoc のインストール
      sudo apt -y update
      sudo apt -y install libprotobuf-dev protobuf-compiler protobuf-c-compiler python3-protobuf
      
    2. pycocotoos のインストール
      sudo pip3 install tensorflow tf-models-official pillow matplotlib cython 
      sudo pip3 install "git+https://github.com/philferriere/cocoapi.git#egg=pycocotools&subdirectory=PythonAPI"
      
      # install pycocotools
      cd /usr/local
      sudo git clone https://github.com/cocodataset/cocoapi.git
      sudo chown -R $USER cocoapi 
      cd ./cocoapi/PythonAPI
      make
      echo 'export PYTHONPATH=$PYTHONPATH:/usr/local/cocoapi/PythonAPI' >> ~/.bashrc
      
    3. DeepLab2 のインストール
      cd /usr/local
      sudo rm -rf deeplab2
      sudo git clone https://github.com/google-research/deeplab2.git
      sudo chown -R $USER deeplab2
      cd /usr/local
      protoc deeplab2/*.proto --python_out=.
      cd /usr/local
      bash deeplab2/compile.sh
      echo 'export PYTHONPATH=$PYTHONPATH:/usr/local' >> ~/.bashrc
      echo 'export PYTHONPATH=$PYTHONPATH:/usr/local/deeplab2' >> ~/.bashrc
      
    4. TensorFlow モデルのインストール
      cd /usr/local
      sudo rm -rf models
      sudo git clone https://github.com/tensorflow/models.git
      sudo chown -R $USER models
      cd /usr/local/models/research
      protoc object_detection/protos/*.proto --python_out=.
      protoc lstm_object_detection/protos/*.proto --python_out=.
      cd /usr/local/models/research\delf
      protoc delf/protos/*.proto --python_out=.
      echo 'export PYTHONPATH=$PYTHONPATH:/usr/local/models' >> ~/.bashrc
      
    5. DeepLab2 の動作確認
      source ~/.bashrc
      cd /usr/local
      # Model training test (test for custom ops, protobuf)
      python deeplab2/model/deeplab_test.py
      
      # Model evaluator test (test for other packages such as orbit, cocoapi, etc)
      python deeplab2/trainer/evaluator_test.py
      

    DeepLabv3

    セマンティック・セグメンテーションのモデル. 2017年発表.

    関連項目Residual Networks (ResNets) , モデル, セマンティック・セグメンテーション

    DeepLabv3+

    セマンティック・セグメンテーションのモデル. 2018年発表.

    関連項目Residual Networks (ResNets) , モデル, セマンティック・セグメンテーション

    DeepL API の認証キー

    DeepL API の認証キーの取得はオンラインで可能である.クレジットカード番号の登録などが必要になる.

    関連する外部ページ

    DeepL Pro のページ: https://www.deepl.com/pro#developer

    DeepXi

    関連項目】 speech enhancement, speech recognition

    Google Colaboratory での DeepXi のインストール

    公式の手順 https://github.com/anicolson/DeepXi による.

    次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する).

    %cd /content
    !rm -rf DeepXi
    !git clone https://github.com/anicolson/DeepXi.git
    %cd DeepXi
    !pip3 install -r requirements.txt
    

    Deformable DETR

    物体検出の一手法.2021 年発表.

    関連項目DETR, MMDetection, 物体検出

    Demucs

    音源分離(music source separation)を行う 1手法.2019年発表.2021年に hybrid version が発表. 音声と楽器音の混合から,音声や楽器音を分離できる.

    【関連用語】 audio source seperation, music source separation

    Google Colaboratory で,音声,楽曲の分離 (Demucs を使用)

    公式の手順 https://github.com/facebookresearch/demucs による.

    次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する).

    1. Demucs のインストール
      !pip3 install -U git+https://github.com/facebookresearch/demucs#egg=demucs
      !pip3 show demucs
      

      [image]
    2. 処理したいサウンドファイルの準備

      ここでは,1.m4a をダウンロードしている.

      %cd /content
      !curl -O https://www.kkaneko.jp/sample/audio/1.m4a
      
      [image]
    3. Demucs の実行
      !demucs 1.m4a
      

      [image]
    4. 処理結果のダウンロード

      1」のところは,処理したサウンドファイルのファイル名にあわせること.

      from google.colab import files
      %cd separated/mdx_extra_q/1
      files.download('drums.wav')
      files.download('bass.wav')
      files.download('other.wav')
      files.download('vocals.wav')
      

      [image]

    DenseNet121, DenseNet169

    CoRR, abs/1608.06993

    KerasDenseNet121 を用いて DenseNet121 を作成するプログラムは次のようになる. 「weights=None」を指定することにより,最初,重みをランダムに設定する.

    Keras のプログラム】

    m = tf.keras.applications.densenet.DenseNet121(input_shape=INPUT_SHAPE, weights=None, classes=NUM_CLASSES)
    

    Keras の DenseNet169 を用いて DenseNet169 を作成するプログラムは次のようになる. 「weights=None」を指定することにより,最初,重みをランダムに設定する.

    Keras のプログラム】

    m = tf.keras.applications.densenet.DenseNet169(input_shape=INPUT_SHAPE, weights=None, classes=NUM_CLASSES)
    

    Keras の応用のページ: https://keras.io/ja/applications/

    関連項目モデル, 画像分類

    PyTorch, torchvision の DenseNet121 学習済みモデルのロード,画像分類のテスト実行

    PyTorch HUB のページ: https://pytorch.org/hub/pytorch_vision_densenet/ を参考にした.

    Google Colab あるいはパソコン(Windows あるいは Linux)を使用.

    1. 前準備

      前準備として,Python のインストール: 別項目で説明している., PyTorch のインストール を行う.

      Google Colaboratory では, Python, PyTorch はインストール済みなので,インストール操作は不要.

      次に,pip を用いて,pillow のインストールを行う.

      pip install -U pillow
      
    2. ImageNet データセット で学習済みのDenseNet121 モデルのロード

      PyTorch, torchvision のモデルについては: https://pytorch.org/vision/stable/models.html に説明がある.

      import torch
      import torchvision.models as models
      device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
      m = models.densenet121(pretrained=True).to(device)
      
    3. 画像分類したい画像ファイルのダウンロードとロードと確認表示
      from PIL import Image
      import requests
      
      # ダウンロードとロード
      url = 'https://github.com/pytorch/hub/raw/master/images/dog.jpg'
      response = requests.get(url)
      img = Image.open(requests.get(url, stream=True).raw)
      
      # 確認表示
      display(img)
      

      [image]
    4. 画像の前処理.PyTorch で扱えるようにするため.
      from PIL import Image
      from torchvision import transforms
      img = Image.open(filename)
      preprocess = transforms.Compose([
          transforms.Resize(256),
          transforms.CenterCrop(224),
          transforms.ToTensor(),
          transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
      ])
      input_tensor = preprocess(img)
      input_batch = input_tensor.unsqueeze(0)
      
    5. 推論 (inference) の実行

      「m.eval()」は,推論を行うときのためのもの.これを行わないと訓練(学習)が行われる.

      import torch
      if torch.cuda.is_available():
          input_batch = input_batch.to('cuda')
      
      m.eval()
      with torch.no_grad():
          output = m(input_batch)
      
    6. 結果の表示
      import urllib
      url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt")
      try: urllib.URLopener().retrieve(url, filename)
      except: urllib.request.urlretrieve(url, filename)
      
      with open("imagenet_classes.txt", "r") as f:
          categories = [s.strip() for s in f.readlines()]
      
      # The output has unnormalized scores. To get probabilities, you can run a softmax on it.
      probabilities = torch.nn.functional.softmax(output[0], dim=0)
      print(probabilities)
      
      top5_prob, top5_catid = torch.topk(probabilities, 5)
      for i in range(top5_prob.size(0)):
          print(categories[top5_catid[i]], top5_prob[i].item())
      

      Google Colaboratory での結果

      [image]

      Windows での結果

      [image]

      Linux での結果

      [image]
    PyTorch, torchvision の DenseNet169 学習済みモデルのロード,画像分類のテスト実行

    PyTorch HUB のページ: https://pytorch.org/hub/pytorch_vision_densenet/ を参考にした.

    Google Colab あるいはパソコン(Windows あるいは Linux)を使用.

    1. 前準備

      前準備として,Python のインストール: 別項目で説明している., PyTorch のインストール を行う.

      Google Colaboratory では, Python, PyTorch はインストール済みなので,インストール操作は不要.

      次に,pip を用いて,pillow のインストールを行う.

      pip install -U pillow
      
    2. ImageNet データセット で学習済みのDenseNet169 モデルのロード

      PyTorch, torchvision のモデルについては: https://pytorch.org/vision/stable/models.html に説明がある.

      import torch
      import torchvision.models as models
      device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
      m = models.densenet169(pretrained=True).to(device)
      
    3. 画像分類したい画像ファイルのダウンロードとロードと確認表示
      from PIL import Image
      import requests
      from IPython.display import display
      
      # ダウンロードとロード
      url = 'https://github.com/pytorch/hub/raw/master/images/dog.jpg'
      response = requests.get(url)
      img = Image.open(requests.get(url, stream=True).raw)
      
      # 確認表示
      display(img)
      

      [image]
    4. 画像の前処理.PyTorch で扱えるようにするため.
      from PIL import Image
      from torchvision import transforms
      img = Image.open(filename)
      preprocess = transforms.Compose([
          transforms.Resize(256),
          transforms.CenterCrop(224),
          transforms.ToTensor(),
          transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
      ])
      input_tensor = preprocess(img)
      input_batch = input_tensor.unsqueeze(0)
      
    5. 推論 (inference) の実行

      「m.eval()」は,推論を行うときのためのもの.これを行わないと訓練(学習)が行われる.

      import torch
      if torch.cuda.is_available():
          input_batch = input_batch.to('cuda')
      
      m.eval()
      with torch.no_grad():
          output = m(input_batch)
      
    6. 結果の表示
      import urllib
      url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt")
      try: urllib.URLopener().retrieve(url, filename)
      except: urllib.request.urlretrieve(url, filename)
      
      with open("imagenet_classes.txt", "r") as f:
          categories = [s.strip() for s in f.readlines()]
      
      # The output has unnormalized scores. To get probabilities, you can run a softmax on it.
      probabilities = torch.nn.functional.softmax(output[0], dim=0)
      print(probabilities)
      
      top5_prob, top5_catid = torch.topk(probabilities, 5)
      for i in range(top5_prob.size(0)):
          print(categories[top5_catid[i]], top5_prob[i].item())
      

      Google Colaboratory での結果

      [image]

      Windows での結果

      [image]

      Linux での結果

      [image]

    depthimage

    depth image は遠近である depth を示す画像. 画素ごとの色や明るさで depth を表示する.

    画像からの depth image の推定は,ステレオカメラや動画から視差を得る方法が主流である.

    monodepth2 法

    単一のカメラでの画像から depth image を推定する方法としては,ディープラーニングを用いる monodepth2 法 (2019 年発表) が知られる.

    monodepth2 の GitHub のページ: https://github.com/nianticlabs/monodepth2

    次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する).

    1. インストール
      !pip3 install -U numpy pillow matplotlib torch torchvision opencv-python opencv-contrib-python scikit-image
      !git clone --recursive https://github.com/nianticlabs/monodepth2
      

      [image]
    2. depth image プログラム実行
      %cd monodepth2
      !python3 test_simple.py --image_path assets/test_image.jpg --model_name mono+stereo_640x192
      

      [image]
    3. 画像表示
      from PIL import Image
      Image.open('assets/test_image.jpg').show()
      Image.open('assets/test_image_disp.jpeg').show()
      

      [image]
    4. 他の画像で試してみた場合
      [image]

      [image]

    Detectron2

    文献

    Yuxin Wu and Alexander Kirillov and Francisco Massa and Wan-Yen Lo and Ross Girshick, Detectron2, https://github.com/facebookresearch/detectron2, 2019.

    サイト内の関連ページ

    物体検出,インスタンス・セグメンテーション,パノプティック・セグメンテーションの実行(Detectron2,PyTorch, Python を使用)(Windows 上)

    関連する外部ページ

    関連項目ADE20K データセット, インスタンス・セグメンテーション (instance segmentation)

    Google Colaboratory で,Detectron2 のインスタンス・セグメンテーションの実行

    インストールは次のページで説明されている.

    https://github.com/facebookresearch/detectron2/releases

    次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する)

    1. Google Colaboratory で,ランタイムのタイプを GPU に設定する.
    2. まず,PyTorch のバージョンを確認

      PyTorch は,ディープラーニングのフレームワークの 機能を持つ Pythonのパッケージ

      次のプログラム実行により,PyTorch のバージョンが「1.10.0+cu111」のように表示される.

      import torch
      print(torch.__version__)
      
    3. NVIDIA CUDA ツールキット のバージョンを確認 (2)**NVIDIA CUDA ツールキット のバージョン**を確認 NVIDIA CUDA ツールキット は,NVIDIA社が提供している GPU 用のツールキットである.GPU を用いた演算のプログラム作成や動作のための各種機能を備えている.ディープラーニングでも利用されている.

      次のプログラム実行により,NVIDIA CUDA ツールキットのバージョンが「cu111」のように表示される.

      import torch
      CUDA_VERSION = torch.__version__.split("+")[-1]
      print(CUDA_VERSION)
      

      [image]
    4. PyTorch のバージョンを確認
      import torch
      TORCH_VERSION = ".".join(torch.__version__.split(".")[:2])
      print(TORCH_VERSION)
      

      [image]
    5. Detectron2 のインストール

      NVIDIA CUDA ツールキット 11.1, PyTorch 1.10 の場合には,次のようになる

      cu111/torch1.10」のところは, NVIDIA CUDA ツールキット のバージョン, PyTorch のバージョンに合わせる

      !pip3 install detectron2==0.6 -f https://dl.fbaipublicfiles.com/detectron2/wheels/cu111/torch1.10/index.html
      

      [image]
    6. Detectron2 のソースコードをダウンロード

      必要に応じて,中のファイルを利用できるように準備しておく.

      !curl -LO https://github.com/facebookresearch/detectron2/archive/refs/tags/v0.6.tar.gz
      !tar -xvzof v0.6.tar.gz
      

      [image]
    7. coco (common object in context) データセットの中の画像ファイルをダウンロード

      https://colab.research.google.com/drive/16jcaJoc6bCFAQ96jDe2HwtXj7BMD_-m5#scrollTo=FsePPpwZSmqt の記載による

      !curl -O http://images.cocodataset.org/val2017/000000439715.jpg
      from PIL import Image
      Image.open('000000439715.jpg').show()
      

      [image]
    8. インスタンス・セグメンテーションの実行

      https://colab.research.google.com/drive/16jcaJoc6bCFAQ96jDe2HwtXj7BMD_-m5#scrollTo=FsePPpwZSmqt の記載による

      「im = cv2.imread('000000439715.jpg')」で,処理したい画像ファイルをロードしている.

      import detectron2
      from detectron2 import model_zoo
      from detectron2.engine import DefaultPredictor
      from detectron2.config import get_cfg
      from detectron2.utils.visualizer import Visualizer
      from detectron2.data import MetadataCatalog, DatasetCatalog
      
      cfg = get_cfg()
      # add project-specific config (e.g., TensorMask) here if you're not running a model in detectron2's core library
      cfg.merge_from_file(model_zoo.get_config_file("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml"))
      cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5  # set threshold for this model
      # Find a model from detectron2's model zoo. You can use the https://dl.fbaipublicfiles... url as well
      cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url("COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml")
      predictor = DefaultPredictor(cfg)
      
      import cv2
      im = cv2.imread('000000439715.jpg')
      outputs = predictor(im)
      

      [image]
    9. インスタンス・セグメンテーションの結果の確認

      https://colab.research.google.com/drive/16jcaJoc6bCFAQ96jDe2HwtXj7BMD_-m5#scrollTo=FsePPpwZSmqt の記載による

      # look at the outputs. See https://detectron2.readthedocs.io/tutorials/models.html#model-output-format for specification
      print(outputs["instances"].pred_classes)
      print(outputs["instances"].pred_boxes)
      

      [image]
    10. インスタンス・セグメンテーションの結果の表示

      https://colab.research.google.com/drive/16jcaJoc6bCFAQ96jDe2HwtXj7BMD_-m5#scrollTo=FsePPpwZSmqt の記載による

      # We can use `Visualizer` to draw the predictions on the image.
      v = Visualizer(im[:, :, ::-1], MetadataCatalog.get(cfg.DATASETS.TRAIN[0]), scale=1.2)
      out = v.draw_instance_predictions(outputs["instances"].to("cpu"))
      import matplotlib.pyplot as plt
      plt.imshow(out.get_image()[:, :, ::-1])
      

      [image]
    Windows での Detectron2 のインストールと動作確認

    別ページ »で説明している.

    Linux での Detectron2 のインストール

    インストールは次のページで説明されている.

    https://github.com/facebookresearch/detectron2/releases

    このページによれば,Linux マシンで,NVIDIA CUDA ツールキット 11.1, PyTorch 1.9 がインストール済みの場合には,次のような手順になる.

    python -m pip install detectron2==0.5 -f https://dl.fbaipublicfiles.com/detectron2/wheels/cu111/torch1.9/index.html
    

    DETR

    物体検出, panoptic segmentation の一手法.2020年発表.

    関連項目Deformable DETR, MMDetection, panoptic segmentation, 物体検出,

    DiffBIR

    DiffBIRは画像復元の手法の一つである。 画像復元は、低品質または劣化した画像を元の高品質な状態に修復するタスクである。 このタスクでは、ノイズや歪みなどの複雑な問題に対処する必要がある。 DiffBIRは、2つの主要なステージから成り立っている。 最初のステージでは、画像復元が行われ、低品質な画像が高品質に修復される。 そして、2番目のステージでは、事前に訓練されたStable Diffusionを使用して、高品質な画像が生成される。 DiffBIRは他の既存の手法よりも優れた結果を得ることができることが実験によって示されている。

    文献

    Xinqi Lin, Jingwen He, Ziyan Chen, Zhaoyang Lyu, Ben Fei, Bo Dai, Wanli Ouyang, Yu Qiao, Chao Dong, DiffBIR: Towards Blind Image Restoration with Generative Diffusion Prior, arXiv:2308.15070v1, 2023.

    https://arxiv.org/pdf/2308.15070v1.pdf

    関連する外部ページ

    diffusion model

    Jascha Sohl-Dickstein, Eric A. Weiss, Niru Maheswaranathan, Surya Ganguli, Deep Unsupervised Learning using Nonequilibrium Thermodynamics, arXiv:1503.03585 [cs.LG].

    display

    IPython の display は,画像表示の機能がある. display は,Jupyter Qt ConsoleGoogle Colaboratory などで動く

    次の Python プログラムは,画像ファイルのダウンロードとロードと確認表示を行う.確認表示で display を用いている.

    from PIL import Image
    import requests
    from IPython.display import display
    
    # ダウンロードとロード
    url = 'https://github.com/pytorch/hub/raw/master/images/dog.jpg'
    response = requests.get(url)
    img = Image.open(requests.get(url, stream=True).raw)
    
    # 確認表示
    display(img)
    

    [image]

    次の Python プログラムは,Iris データセットのロードと確認表示を行う. Pandas データフレームの df にロードしている. 確認表示で display を用いている.

    import pandas as pd
    from sklearn.datasets import load_iris
    from IPython.display import display
    
    iris = load_iris()
    df = pd.DataFrame(iris.data, columns=iris.feature_names)
    df['species'] = iris.target_names[iris.target]
    display(df)
    

    Pandas データフレームのすべての行を表示したいときは,次のように 「pd.set_option('display.max_rows', None)」を使用する

    import pandas as pd
    from sklearn.datasets import load_iris
    from IPython.display import display
    
    iris = load_iris()
    df = pd.DataFrame(iris.data, columns=iris.feature_names)
    df['species'] = iris.target_names[iris.target]
    pd.set_option('display.max_rows', None)
    display(df)
    

    [image]

    Dlib

    Dlib は,数多くの機能を持つソフトウェア. Python, C++ のプログラムから使うためのインタフェースを持つ.

    Dlib の機能には,機械学習,数値計算,グラフィカルモデル推論,画像処理,スレッド,通信,GUI,データ圧縮・一貫性,テスト,さまざまなユーティリティがある.

    Dlib には,顔情報処理に関して,次の機能がある.

    ディープニューラルネットワークの学習済みモデルも配布されている

    Dlib の URL: http://dlib.net/

    Dlib の各種機能は: 別ページ »にまとめ

    関連項目FairFace, Max-Margin 物体検出 , 顔検出 (face detection), 顔ランドマーク (facial landmark), 顔のコード化

    Windows での Dlib のインストール

    Dlib のインストールは,複数の方法がある.

    Dlib 19.24.99 の非公式ビルド: dlib.zip

    私がビルドしたもの,非公式,無保証, 公開されているDlib のソースコードを改変せずにビルドした. Windows 10, Visual Build Tools for Visual Studio 2022 を用いてビルドした.NVIDIA CUDA は使用せずにビルドした. Eigen の MPL2 ライセンスによる.

    zip ファイルは C:\ 直下で展開し,C:\dlib での利用を想定.

    Ubuntu での Dlib のインストール
    Dlib の顔検出

    Dlib の顔検出 は次の仕組みで行われる.

    Dlib には,ディープラーニングCNN (convolutional neural network) を用いた物体検出 が実装されている. そこでは,Max-Margin 物体検出法が利用されている(文献は次の通り). それにより,Dlib の顔検出 が行われる.

    Davis E. King, Max-Margin Object Detection, CoRR, abs/1502.00046, 2015

    Dlib を用いた顔検出のプログラム例

    次のページは,上のプログラム等を記載したGoogle Colaboratory のページである.ページを開き実行できる.

    URL: https://colab.research.google.com/drive/1q-dGCfre8MT5Zet2O3xYoYMUP0sx_KLc?usp=sharing [Google Colaboratory]

    Dlib の顔検出の詳しい手順: 別ページ »で説明している.

    Docker

    Docker は,Windowsなどのオペレーティングシステムの中に, Docker コンテナ という Dockerのエリアを複数作ることができる。 Docker コンテナの中には、ソフトもインストールしたりできるが、 それは、おおもとのWindows などのオペレーティングシステムや,他の Docker コンテナとは隔離される (つまり、Docker コンテナの中のアプリを起動するときは、Docker のコマンドも必要)。 いろんなソフトを試したいときに便利。「サーバ」を立てたいというとき、サーバのソフトを丸ごと Docker コンテナの中に入れておくと、サーバの運用保守(サーバを止めたりと、バージョンアップで入れ替えたりなど)が楽になる可能性がある

    サイト内の主な Docker 関連ページ

    関連する外部ページ

    Windows での Docker Engine, Docker Desktop のインストールと確認

    Docker Desktop のインストール,Ubuntu 22.04 コンテナとイメージの作成(Windows 上)で説明している.

    Ubuntu での Docker Engine, Docker Desktop のインストールと確認

    Docker Engine,Docker Desktop のインストールと使用法,Docker Compose の「はじめよう」を実行(Ubuntu 22.04 上): 別ページ »で説明している.

    Docker Compose

    Docker Compose は, Docker を簡単に管理できるツール.環境変数を個々の Docker コンテナごとに変えるといったことも簡単にできるようになる.

    サイト内の主な Docker 関連ページ

    Docker を使い Ubuntu 22.04 の bash を使う

    次のコマンドを実行する.exit で終了すると,コンテナは削除される(「--rm」を付けている)

    docker run --rm -it --name myubuntu ubuntu:22.04
    PS1='\h:\w\$ '
    

    Docker の主なコマンド

    DreamGaussian

    DreamGaussianは3Dコンテンツ生成の新しいフレームワークであり、特に画像から3Dモデルを生成する(Image-to-3D)とテキストから3Dモデルを生成する(Text-to-3D)の二つの主要なタスクに対応しています。既存の手法であるNeural Radiance Fields(NeRF)は高品質な結果を出すものの、計算時間が長いという課題がありました。DreamGaussianの特長は、3Dガウススプラッティングモデルを用いることで、メッシュの抽出とUV空間でのテクスチャの精緻化が効率的に行える点です。この新しいアプローチにより、DreamGaussianは既存のNeRFベースの手法よりも高速な3Dコンテンツ生成を実現しています。さらに、実験結果では、DreamGaussianがImage-to-3DとText-to-3Dの両方のタスクで既存の方法よりも高速であることが確認されています。

    文献

    Jiaxiang Tang, Jiawei Ren, Hang Zhou, Ziwei Liu, Gang Zeng, DreamGaussian: Generative Gaussian Splatting for Efficient 3D Content Creation, arXiv:2309.16653v1, 2023.

    https://arxiv.org/pdf/2309.16653v1.pdf

    関連する外部ページ

    DUTS データセット

    DUTS データセットは,saliency detection のためのデータセットである. 10,553枚の訓練画像と5,019枚のテスト画像を含む.

    いずれも手動でアノテーションされている.

    次の URL で公開されているデータセット(オープンデータ)である.

    URL: http://saliencydetection.net/duts/

    関連項目】 salient object detection, 物体検出

    Early Stopping

    Early Stopping は, 正則化 (regularization) のための一手法である. training loss の減少が終わるのを待たずに,学習の繰り返しを打ち切る. このとき,検証用データでの検証において,validation loss が増加を開始した時点で,学習の繰り返しを打ち切る.

    KerasEarly Stopping を自動で行いたいとき,次のようにコールバックを書く.

    Keras のプログラム】

    from kernel.callbacks import EarlyStopping
    cb = EarlyStopping(monitor='var_loss', patience = 10)
    

    コールバックは,次のようにして使用する.

    Keras のプログラム】

    history = m.fit(x_train, y_train, batch_size=32, epochs=50, validation_data=(x_test, y_test), callbacks=[cb])
    

    EasyOCR

    EasyOCR は,多言語の文字認識のソフトウエア. テキスト検出に CRAFT を使用.

    [image]

    [image]

    学習用のソースコードも公開されている.

    サイト内の関連ページ

    EasyOCR のインストールと動作確認(多言語の文字認識)(Python,PyTorch を使用)(Windows 上): 別ページ »で説明している.

    関連する外部ページ

    関連項目CRAFT, OCR

    Google Colaboratory で,EasyOCR による日本語読み取りの実行

    公式の手順 (https://github.com/JaidedAI/EasyOCR)による

    次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する).

    1. EasyOCR のインストール
      !pip3 install git+git://github.com/jaidedai/easyocr.git
      

      [image]
    2. 処理したい画像ファイルを Google Colaboratory にアップロードする

      [image]
    3. OCR の実行

      「ja」は「日本語」の意味.

      import easyocr
      reader = easyocr.Reader(['ja'])
      result = reader.readtext('1.png')
      

      [image]
    4. 結果の確認
      from IPython.display import display
      display(result)
      

      [image]
    JAIDED AI による EasyOCR のオンラインデモ

    JAIDED AI による EasyOCR のオンラインデモの URL: https://www.jaided.ai/easyocr/

    [image]

    [image]

    EdgeBoxes 法

    エッジから,オブジェクトのバンディングボックス(包含矩形)を求める方法.

    関連項目物体検出

    EfficientDet

    zylo117 による EfficientDet の実装 (GitHub) のページ: https://github.com/zylo117

    関連項目物体検出

    Google Colaboratory で,EfficientDet のインストール

    次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する)

    # install requirements
    !pip3 install pycocotools numpy opencv-python opencv-contrib-python tqdm tensorboard tensorboardX pyyaml webcolors
    !pip3 install torch==1.4.0
    !pip3 install torchvision==0.5.0
     
    # run the simple inference script
    !rm -rf Yet-Another-EfficientDet-PyTorch
    !git clone https://github.com/zylo117/Yet-Another-EfficientDet-PyTorch
    !mkdir Yet-Another-EfficientDet-PyTorch/weights
    !(cd Yet-Another-EfficientDet-PyTorch/weights; curl -L -O https://github.com/zylo117/Yet-Another-Efficient-PyTorch/releases/download/1.0/efficientdet-d0.pth)
    !(cd Yet-Another-EfficientDet-PyTorch; python3 efficientdet_test.py)
    

    [image]

    Eigen 3

    Eigen は, 次の機能を持つ C++ テンプレートライブラリ.SSEを使うように最適化されている.

    Eigen の URL: https://eigen.tuxfamily.org/index.php

    Windows で Eigen 3 のインストール

    Windows での Eigen 3 のインストール: 別ページ »で説明している.

    Ubuntu で Eigen のインストール

    Ubuntu でインストールを行うには,次のコマンドを実行.

    sudo apt -y update
    sudo apt -y install libeigen3-dev
    

    ELSED

    ELSED線分検知の一手法.2021年発表.

    [image]

    文献

    Iago Suárez and José M. Buenaposada and Luis Baumela, ELSED: Enhanced Line SEgment Drawing, Pattern Recognition, vol. 127, pages 108619, arXiv:2108.03144, 2022. doi: https://doi.org/10.1016/j.patcog.2022.108619.

    arXiv: https://arxiv.org/abs/2108.03144

    https://arxiv.org/pdf/2108.03144.pdf

    サイト内の関連ページ

    ELSED のインストールと動作確認(線分検知)(Build Tools, Python を使用)(Windows 上)

    関連する外部ページ

    関連項目線分検知

    Emotion-Investigator

    SanjayMarreddi の Emotion-Investigator は,顔検出 (face detection)と,Happy, Sad, Disgust, Neutral, Fear, Angry, Surprise の表情推定を行う.

    サイト内の関連ページ

    関連する外部ページ

    ESRGAN

    超解像 (super resolution) の一手法.2018 年発表.

    関連項目GAN (Generative Adversarial Network), image super resolution, video super resolution, 超解像 (super resolution)

    Everything

    Everything は,Windows で動くファイル検索のソフトウェア.

    Everything のページ http://www.voidtools.com/

    Windows での Everything のインストール

    Windows での cmake のインストールには,複数の方法がある.次のいずれかによりインストールできる.

    FaceForensics++ データセット

    FaceForensics++ データセットは,自動合成された顔画像のデータセット

    FaceForensics++ データセットは,次の URL で公開されているデータセット(オープンデータ)である.

    URL: https://github.com/ondyari/FaceForensics

    【関連情報】

    FairFace (Face Arrtibute Dataset for Balanced Race, Gender, and Age)

    性別,年齢,人種に関するバイアス (bias) 等の問題がないとされる顔データセットが発表された.2021年発表. 顔の性別,年齢等の予測の精度向上ができるとされている.

    関連項目dlib, 顔のデータベース, 顔ランドマーク (facial landmark), 顔の性別,年齢等の予測

    Google Colaboratory での FairFace デモプログラムの実行

    顔の性別,年齢等の予測を行う.

    次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する).

    1. Google Colaboratory で,ランタイムのタイプを GPU に設定する.
    2. ソースコード等のダウンロード

      !git clone https://github.com/dchen236/FairFace 
      

      [image]
    3. 公式の GitHub のページの記載により,事前学習済みモデルをダウンロードする

      公式の GitHub のページ: https://github.com/dchen236/FairFace

      2つのファイルをダウンロードする.

      [image]
    4. いまダウンロードしたファイルについて.

      Google Colaboratory 「fair_face_models」という名前のディレクトリを作る. そして,いまダウンロードしたファイルのファイル名を次のように変えて, 「fair_face_models」ディレクトリの下に置く. (ファイル名については,predict.py の中で指定されているファイル名にあわせる)

      [image]
    5. 実行する

      %cd FairFace
      !python3 predict.py --csv test_imgs.csv
      

      [image]

      test_imgs.csv には,次の画像ファイルのファイル名が設定されている.

      [image]

      自前の画像で動作確認したいときは,画像ファイル名を書いた csv ファイルを準備する

    6. 実行結果の確認

      性別,年齢などが推定されている.

      !cat test_outputs.csv
      

      [image]
    Windows での FairFace デモプログラムの実行

    顔の性別,年齢等の予測を行う.

    1. 前準備として pytorch, dlib のインストール,Git のインストール: 別項目で説明している.

      Git の公式ページ: https://git-scm.com/を行っておくこと

    2. ソースコード等のダウンロード

      git clone https://github.com/dchen236/FairFace 
      
    3. 公式の GitHub のページの記載により,事前学習済みモデルをダウンロードする

      公式の GitHub のページ: https://github.com/dchen236/FairFace

      2つのファイルをダウンロードする.

      [image]
    4. いまダウンロードしたファイルについて.

      「fair_face_models」という名前のディレクトリを作る. そして,いまダウンロードしたファイルのファイル名を次のように変えて, 「fair_face_models」ディレクトリの下に置く. (ファイル名については,predict.py の中で指定されているファイル名にあわせる)

      [image]
    5. 実行する

      cd FairFace
      python predict.py --csv test_imgs.csv
      

      [image]

      test_imgs.csv には,次の画像ファイルのファイル名が設定されている.

      [image]

      自前の画像で動作確認したいときは,画像ファイル名を書いた csv ファイルを準備する

    6. 実行結果の確認

      性別,年齢などが推定されている.

      type test_outputs.csv
      

      [image]

    Fashion MNIST データセット

    Fashion MNIST データセットは,公開されているデータセット(オープンデータ)である.

    Fashion MNIST データセットは,10 種類のモノクロ画像と,各画像に付いた ラベル(10 種類の中の種類を示す)から構成されるデータセットである.

  • 画素はグレースケールであり,画素値は0~255である.0が白,255が黒.

    文献

    Han Xiao, Kashif Rasul, and Roland Vollgraf, Fashion-MNIST: a Novel Image Dataset for Benchmarking Machine Learning Algorithms, arXiv:1708.07747 [cs.LG], 2017.

    サイト内の関連ページ

    関連する外部ページ

    関連項目Keras に付属のデータセット, MNIST データセット, TensorFlow データセット, オープンデータ, 画像分類

    Python での Fashion MNIST データセットのロード(TensorFlow データセットを使用)

    次の Python プログラムは,TensorFlow データセットから,Fashion MNIST データセットのロードを行う. x_train, y_train が学習用のデータ.x_test, y_test が検証用のデータになる.

    次の Python プログラムでは,TensorFlow データセットから,Fashion MNIST データセットのロードを行う. x_train と y_train を 25枚分表示することにより,x_train と y_train が,モノクロ画像であることが確認できる.

    tensorflow_datasets の loadで, 「batch_size = -1」を指定して,一括読み込みを行っている.

    from __future__ import absolute_import, division, print_function, unicode_literals
    import tensorflow as tf
    import numpy as np
    import tensorflow_datasets as tfds
    
    %matplotlib inline
    import matplotlib.pyplot as plt
    import warnings
    warnings.filterwarnings('ignore')   # Suppress Matplotlib warnings
    
    # MNIST データセットのロード
    mnist, mnist_metadata = tfds.load('mnist', with_info = True, shuffle_files=True, as_supervised=True, batch_size = -1)
    x_train, y_train, x_test, y_test = mnist['train'][0], mnist['train'][1], mnist['test'][0], mnist['test'][1]
    
    plt.style.use('default')
    plt.figure(figsize=(10,10))
    for i in range(25):
        plt.subplot(5,5,i+1)
        plt.xticks([])
        plt.yticks([])
        plt.grid(False)
    # squeeze は,サイズ1の次元を削除.numpy は tf.Tensor を numpy に変換
        plt.imshow(np.squeeze(x_train[i]), cmap=plt.cm.binary)
        plt.xlabel(y_train[i].numpy())
    
    # 確認表示
    plt.show()
    

    [image]
    Python での Fashion MNIST データセットのロード(Keras を使用)

    次の Python プログラムは,Keras に付属のデータセットの中にある Fashion MNIST データセットのロードを行う. x_train, y_train が学習用のデータ.x_test, y_test が検証用のデータになる.

    from tensorflow.keras.datasets import fashion_mnist
    (x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()
    

    次の Python プログラムは,Keras に付属のデータセットの中にある Fashion MNIST データセットのロードを行う. x_train と y_train を 25枚分表示することにより,x_train と y_train が,モノクロ画像であることが確認できる.

    import tensorflow.keras
    from tensorflow.keras.datasets import fashion_mnist
    %matplotlib inline
    import matplotlib.pyplot as plt
    import warnings
    warnings.filterwarnings('ignore')   # Suppress Matplotlib warnings
    
    # Fashion MNIST データセットのロード
    (x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()
    
    plt.style.use('default')
    plt.figure(figsize=(10,10))
    for i in range(25):
        plt.subplot(5,5,i+1)
        plt.xticks([])
        plt.yticks([])
        plt.grid(False)
        plt.imshow(x_train[i], cmap=plt.cm.binary)
        plt.xlabel(y_train[i])
    
    # 確認表示
    plt.show()
    

    [image]
    TensorFlow データセットからのロード,学習のための前処理

    TensorFlow データセット から Fashion MNIST データセット をロード

    結果は,TensorFlow の Tensor である.

    type は型,shape はサイズ,np.max と np.mi は最大値と最小値.

    tensorflow_datasets の loadで, 「batch_size = -1」を指定して,一括読み込みを行っている.

    from __future__ import absolute_import, division, print_function, unicode_literals
    import tensorflow as tf
    import numpy as np
    import tensorflow_datasets as tfds
    
    %matplotlib inline
    import matplotlib.pyplot as plt
    import warnings
    warnings.filterwarnings('ignore')   # Suppress Matplotlib warnings
    
    # Fashion MNIST データセットのロード
    fashion_mnist, fashion_mnist_metadata = tfds.load('fashion_mnist', with_info = True, shuffle_files=True, as_supervised=True, batch_size = -1)
    x_train, y_train, x_test, y_test = fashion_mnist['train'][0], fashion_mnist['train'][1], fashion_mnist['test'][0], fashion_mnist['test'][1]
    print(fashion_mnist_metadata)
    # 【x_train, x_test, y_train, y_test の numpy ndarray への変換と,値の範囲の調整(値の範囲が 0 〜 255 であるのを,0 〜 1 に調整)】
    x_train = x_train.numpy().astype("float32") / 255.0
    x_test = x_test.numpy().astype("float32") / 255.0
    y_train = y_train.numpy()
    y_test = y_test.numpy()
    print(type(x_train), x_train.shape, np.max(x_train), np.min(x_train))
    print(type(x_test), x_test.shape, np.max(x_test), np.min(x_test))
    print(type(y_train), y_train.shape, np.max(y_train), np.min(y_train))
    print(type(y_test), y_test.shape, np.max(y_test), np.min(y_test))
    

    Fast-Robust-ICP

    ICP の一手法

    Fast-Robust-ICP のページ(Git Hub): https://github.com/yaoyx689/Fast-Robust-ICP

    関連項目K 近傍探索 (K nearest neighbour), ICP

    Google Colaboratory で,Fast-Robust-ICP の実行

    次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する).

    1. インストール
      
      

      [image]
    2. Fast-Robust-ICP の実行

      実行でのオプションについては,Fast-Robust-ICP のページ(Git Hub): https://github.com/yaoyx689/Fast-Robust-ICP

      
      

      [image]
    Windows での Fast-Robust-ICP のインストール

    ソースコードからビルドする

    1. Windows では,前準備として次を行う.
    2. コマンドプロンプトを管理者として開き次のコマンドを実行する.

      c:\Fast-Robust-ICP にインストールされる.

      cd %LOCALAPPDATA%
      rmdir /s /q Fast-Robust-ICP
      git clone --recursive https://github.com/yaoyx689/Fast-Robust-ICP
      cd Fast-Robust-ICP
      rmdir /s /q build
      mkdir build
      cd build
      del CMakeCache.txt
      cmake -G "Visual Studio 17 2022" -T host=x64 ^
          -DCMAKE_INSTALL_PREFIX="c:/Fast-Robust-ICP" ^
          -DEIGEN3_INCLUDE_DIRS="c:/eigen/include;c:/eigen/include/eigen3" ^
      ..
      mklink c:\eigen\include\eigen c:\eigen\include\eigen3 
      cmake --build . --config RELEASE
      del c:\eigen\include\eigen
      

    FERET データベース

    FERET データベースは顔のデータベース.詳細情報は,次のWebページにある.

    https://www.nist.gov/itl/products-and-services/color-feret-database

    関連項目顔のデータベース

    FFHQ (Flickr-Faces-HQ) データセット

    FFHQ (Flickr-Faces-HQ) データセット は,70,000枚の顔画像データセット. 機械学習による顔の生成などの学習や検証に利用できるデータセットである.

    FFHQ (Flickr-Faces-HQ) データセットは次の URL で公開されているデータセット(オープンデータ)である.

    URL: https://github.com/NVlabs/ffhq-dataset

    【関連情報】

    関連項目顔のデータベース

    FFmpeg

    FFmpeg は,動画のデコーダとエンコーダに関するソフトウェア.

    サイト内の関連ページ

    関連する外部ページ

    FFmpeg の公式ページ: https://ffmpeg.org/

    FFTW

    FFTW は, 離散フーリエ変換 (DFT) を行う C のプログラム集.1次元に限らず,より高次元でも動く.

    【関連する外部ページ】

    FFTW の公式ページ: https://www.fftw.org/

    Windows での FFTW のインストール

    Windows での FFTW3 のインストール(ソースコードを使用)(Build Tools for Visual Studio を利用)

    FFTW 3.3.10 の非公式ビルド: fftw3.zip

    私がビルドしたもの,非公式,無保証, https://github.com/FFTW/fftw3 の ソースコードを改変せずにビルドした. Windows 10, Visual Build Tools for Visual Studio 2022 を用いてビルドした. FFTW の GPL ライセンスによる.

    zip ファイルは C:\ 直下で展開し,C:\fftw3 での利用を想定.

    Ubuntu での FFTW のインストール

    Ubuntu での FFTW3 のインストール(Ubuntu 上)

    FIDTM (FIDT map)

    FIDTM(Focal Inverse Distance Transform Map) は, crowd counting の一手法.2021年発表.

    従来の density maps での課題を解決し,従来法よりも精度が上回るとされる. FIDT map を用いて頭部を得る LMDS もあわせて提案されている.

    crowd coungting の結果の例

    [image]

    【関連用語】 crowd counting, JHU-CROWD++ データセット, NWPU-Crowd データセット, ShanghaiTech データセット, UCF-QNRF データセット

    fine tuning (ファイン・チューニング)

    学習済みモデルを使用する. 学習済みモデルの一部に新しいモデルを合わせた上で,追加のデータを使い学習を行う. このとき,学習済みモデルの部分と,新しいモデルの部分の両方について,パラメータ(重みなど)の調整を行う.

    関連項目画像分類 (image classification), 分類, 物体検出

    画像分類のモデル DETR での添加学習(woctezuma の Google Colaboratory のページを使用)

    woctezuma の Google Colaboratory のページを使用する

    URL: https://colab.research.google.com/github/woctezuma/finetune-detr/blob/master/finetune_detr.ipynb#scrollTo=KCrlzjaLQQMm

    このプログラムは,物体検出等の機能を持つモデルである DETR を使い, fine tuning (ファイン・チューニング)と,物体検出を行う.

    COCO データセットで学習済みの DETR について,確認のため, 物体検出を行ったあと, 風船(baloon)についてのfine tuning (ファイン・チューニング)を行い, 風船(baloon)が検出できるようにしている. 風船(baloon)は,COCO データセット には無い.

    1. woctezuma の Google Colaboratory のページを開く

      https://colab.research.google.com/github/woctezuma/finetune-detr/blob/master/finetune_detr.ipynb#scrollTo=KCrlzjaLQQMm

    2. torch 1.8.0, torchvision 0.9.0, torchtext 0.9.0 を使うように書き換える
      
      !pip3 uninstall -y torchtext
      !pip3 install torch==1.8.0 torchvision==0.9.0 torchtext==0.9.0
      import torch, torchvision
      print(torch.__version__, torch.cuda.is_available())
      
      torch.set_grad_enabled(False);
      

      [image]
    3. ソースコードの要点を確認する.

      COCO データセットのクラス名を確認する.

      orange, apple, banana, doc, person などがある.baloon は無い

      [image]

      detr_resnet50 の事前学習済みのモデルをダウンロードしている.

      [image]

      しきい値 0.9, 0.7, 0.0 の 3 通りで実行.しきい値を下げるほど,検出できる物体は増えるが,誤検知も増える傾向にある.

      [image]

      [image]

      fine tuning を行うため,風船 (baloon) の画像,そして,風船の領域を示した情報(輪郭線,包含矩形)の情報を使う. 画像は複数.そのうち1枚は次の通り.

      [image]

      過学習は起きていないようである

      [image]

      fine tuning により,風船(baloon)を検出できるようになった. しきい値は 0.9, 0.7 の 2通り.

      [image]
    4. 自前のデータでfine tuning を行いたいときは,このページの説明通り,COCO データのフォーマットでデータを準備する.

      そのフォーマットは,/content/data/custom (Google Colaboratory の data/custom の下のファイル)が参考になる.

      自前のデータが準備できたら,Google Colaboratory にアップロードし, 次のコードセルの「/content/data/custom」のところを書き換えて,再度実行する.

      [image]

    最初の物体検知(fine tuning の前)で,別の画像で試したいとき.

    画像ファイルをアップロード.プログラムは次のように書き換える.

    fname = '/content/5m126sn2pov30qzu3pc49lampcp6.jpg'
    im = Image.open(fname)
    scores, boxes = detect(im, detr, transform)
    

    URL: https://github.com/woctezuma/finetune-detr

    Flang

    Flang は,LLVMのサブプロジェクトである.

    サイト内の関連ページ

    関連項目LLVM

    flann

    flann は近似近傍探索の機能を持ったソフトウェア

    Windows での flann のインストール

    Windows での flann のインストール(Windows 上): 別ページ »で説明している.

    FlexGen

    FlexGen は,大規模言語モデル (large language model)を用いた推論で必要とされる計算とメモリの要求を削減する技術. 実験では,大規模言語モデル OPT を,16GB の単一 GPU で実行したとき 100倍以上の高速化が可能であるとされている.

    文献】 Ying Sheng, Lianmin Zheng, Binhang Yuan, Zhuohan Li, Max Ryabinin, Beidi Chen, Percy Liang, Ce Zhang, Ion Stoica, Christopher Ré., High-throughput Generative Inference of Large Language Model with a Single GPU, 2023.

    サイト内の関連ページ

    関連する外部ページ

    FlexGen の GitHub のページ: https://github.com/FMInference/FlexGen

    関連項目OPT

    FLIC (Frames Labeled In Cinema)データセット

    FLIC は, 5003枚の画像(訓練データ: 3987枚,検証データ: 1016枚)で構成されている. 画像の上半身についてアノテーションが行われている. ほとんどの人物がカメラ正面を向いている.

    ディープラーニングにより姿勢推定を行うためのデータとして利用できる.

    次の URL で公開されているデータセット(オープンデータ)である. http://bensapp.github.io/flic-dataset.html

    【関連情報】

    FordA データセット

    FordA データセットは,時系列データである.

    FordA データセットは,公開されているデータセット(オープンデータ)である.

    URL: http://www.timeseriesclassification.com/description.php?Dataset=FordA

    教師データ数:3601

    テストデータ数: 1320

    モーターセンサーにより計測されたエンジンノイズの計測値.

    FSDnoisy18k データセット

    20種類, 約 42.5 時間分のサウンドである.

    次の URL で公開されているデータセット(オープンデータ)である.

    http://www.eduardofonseca.net/FSDnoisy18k/

    関連項目】 sound data

    FZKViewer

    URL: https://www.iai.kit.edu/1302.php

    Windows での FZKViewer のインストールは 別ページ »で説明している.

    FZKViewer で CityGML のファイルを開くときは, File, Open, Open GML File... と操作する.

    [image]

    ファイルが読み込まれると,次のように表示される.

    [image]

    関連項目CityGML

    F 検定 (F test)

    帰無仮説: 正規分布に従う2群の標準偏差が等しい . F 検定を,t 検定の行う前の等分散性の検定に使うのは正しくないという指摘もある.

    R システム で,2群 s1, s2 の F 検定を行うプログラム

    var.test(s1, s2)
    

    関連項目検定

    GAN (generative adversarial network)

    GAN (Generative Adversarial Network) では, 生成器 (generator) でデータを生成し, 識別機 (discriminator) で,生成されたデータが正当か正当でないかを識別する.

    関連項目Applications of Deep Neural Networks, Real-ESRGAN, TecoGAN, Wasserstein GAN (WGAN), Wasserstein GAN with Fradient Penalty (WGAN-GP) ディープラーニング

    Git

    Git はバージョン管理システム.Windows 版の git の1つ「git for Windows」には,MinGWが同封されている.

    Git の公式ページ: https://git-scm.com/

    Windows でのGit のインストール

    Windows での git のインストールには,複数の方法がある.次のいずれかによりインストールできる.

    Ubuntu でのGit のインストール

    Ubuntu での git のインストールは, 端末で,次のコマンドを実行する.

    sudo apt -y update
    sudo apt -y install git
    

    GitHub からのファイルのダウンロード

    GitHub からのファイルのダウンロードは, curl コマンドで, 次のように行う.

    curl -L https://github.com/opencv/opencv/blob/master/samples/data/home.jpg?raw=true -o home.jpg
    

    GlueStick

    GlueStick 法はイメージ・マッチングの一手法.2023年発表. 線分を使ったイメージ・マッチングは,照明条件や視点の変化,テクスチャのない領域でもマッチングできるメリットがある. GlueStick 法は,点と線分の両方を利用してイメージ・マッチングを行う. その際にCNNを利用.

    [image]

    [image]

    文献

    Rémi Pautrat, Iago Suárez, Yifan Yu, Marc Pollefeys, Viktor Larsson, GlueStick: Robust Image Matching by Sticking Points and Lines Together, ArXiv, 2023. ·

    https://arxiv.org/pdf/2304.02008v1.pdf

    関連する外部ページ

    GNN (グラフニューラルネットワーク)

    GNN は、グラフ構造を持つデータを用いた学習を可能とする技術である.

    関連項目PyTorch Geometric Temporal

    GnuWin

    GnuWin は, Win32 版の GNU ツールと,その他類似のオープンソースライセンスのツール

    【関連する外部ページ】

    Google アカウント

    Google アカウントは,Google のオンラインサービス等の利用のときに使うアカウント. Google オンラインサービスの利用条件などは,利用者で確認すること.

    Google アカウントの取得: 別ページ »で説明

    Google Colaboratory

    Google Colaboratory の利用により, オンラインで,Web ブラウザを用いて,次のことができる.

    Google Colaboratory は,オンラインで使用する. Google Colaboratory の使用には,Google アカウントの取得が必要.

    詳しくは: 別ページ »で説明

    Google Colaboratory で TensorFlow, Keras のバージョン確認

    Google Colaboratory のコードセルで,次の Python プログラムを実行

    import tensorflow as tf
    print(tf.__version__)
    
    import keras
    print(keras.__version__)
    

    [image]
    Google Colaboratory で NVIDIA CUDA のバージョン確認

    Google Colaboratory のコードセルで,次の Python プログラムを実行

    !nvcc -V 
    

    [image]

    Google Colaboratory のコードセルで,次の Python プログラムを実行

    import torch
    CUDA_VERSION = torch.__version__.split("+")[-1]
    print(CUDA_VERSION)
    

    [image]
    Google Colaboratory で GPU の確認

    !nvidia-smi --query-gpu=gpu_name,driver_version,memory.total --format=csv
    

    [image]
    Google Colaboratory を使用中であるかを判別する Python プログラム
    try:
        from google.colab import drive
        USE_COLAB = True
    except:
        USE_COLAB = False
    

    Google Colaboratory での実行結果

    [image]

    Windowsコマンドプロンプトでの実行結果

    [image]

    GPU

    GPU は,グラフィックス・プロセッシング・ユニット(Graphics Processing Unit)の略である.現在は,3次元のビデオゲーム,さまざまな計算,ディープラーニングの高速な並列処理などに用いられている.

    Graphviz

    Graphviz はグラフデータ構造の機能を持ったソフトウェアである.

    URL: https://graphviz.gitlab.io/

    Windows での Graphviz のインストール

    Windows での Graphviz のインストールには,複数の方法がある.次のいずれかによりインストールできる.

    インストールの終了後,C:\Program Files\Graphviz\bin にパスを通す

    Ubuntu での Graphviz のインストール

    Ubuntu での graphviz のインストール

    sudo apt -y update
    sudo apt -y install graphviz libgraphviz-dev python3-graphviz
    

    grep

    grep は,正規表現で,テキストファイルの中から行を選択する機能を持つソフトウェア.

    Windows での grep のインストール
    1. GnuWin のページから grep for Windows をダウンロードし,インストール

      http://gnuwin32.sourceforge.net/packages/grep.htm

    2. Windows のシステム環境変数 Path に次の値を追加し,パスを通す

      Windows での環境変数の設定は,マイコンピュータを右クリック → プロパティ→ 詳細設定 → 環境変数をクリック

      Windowsの画面の表示では、「\」(円マーク)が表示される

    gsutil

    gsutil は Google Cloud Strage のアクセス機能を持ったアプリケーション

    公式ページは https://cloud.google.com/storage/docs/gsutil?hl=ja

    Windows では, コマンドプロンプトを管理者として開き, 次のコマンドを実行することにより, gsutil のインストールを行うことができる.

    cd %HOMEPATH%
    curl -L -O https://dl.google.com/dl/cloudsdk/channels/rapid/GoogleCloudSDKInstaller.exe
    .\GoogleCloudSDKInstaller.exe
    

    He の初期値

    He らの方法 (2015年) では,前層のユニット数(ニューロン数)を n とするとき, sqrt( 2 / n ) を標準偏差とする正規分布に初期化する. ただし,この方法は ReLU に特化した手法であるとされている. この方法を使うとき,層の入力は,正規化済みであること.

    Kaiming He, Xiangyu hang, Shaoqing Ren and Jian Sun, Delving Deep into Rectifiers: Surpassing Human-Level, Performance on ImageNet Classification, pp. 1026^1-34.

    HDF5

    HDF5 は,階層データを扱うライブラリソフトウェア.

    Suport th HDF Group の公式ページ: https://support.hdfgroup.org/

    Windows での HDF5 のインストール

    Windows での HDF5 のインストール(Windows 上): 別ページ »で説明している.

    HELEN データセット

    HELENデータセットは,顔画像と,顔のパーツの輪郭のデータセットである.

    次の URL で公開されているデータセット(オープンデータ)である.

    http://www.ifp.illinois.edu/~vuongle2/helen/

    【関連情報】

    関連項目顔のデータベース

    HierText データセット

    HierTextは,文字認識,レイアウト解析,テキスト検出に利用できるデータセットである. このデータセットには,Open Imagesデータセットから選ばれた11639枚の画像が含まれており,これらの画像はテキストコンテンツとレイアウト構造が豊富である. さらに,約120万語の単語が提供されている. HierTextのアノテーションは,単語,行,段落のレベルを含んでいる. 訓練セットには8,281枚の画像が含まれ,検証セットには1,724枚の画像が含まれ,さらにテストセットには1,634枚の画像が含まれている.

    サイト内の関連ページ

    HierText データセットのインストール(テキスト検出,文字認識のデータセット)(Windows 上)

    関連する外部ページ

    公式のGitHub のページ https://github.com/google-research-datasets/hiertext

    関連項目Unified Scene Text Detection

    HMDB51 (a large human motion database) データセット

    HMDB51 (a large human motion database) データセット は,人間の行動データセット. 機械学習による行動分類,行動認識,ビデオ検索などの学習や検証に利用できるデータセットである.

    HMDB51 (a large human motion database) データセット >は次の URL で公開されているデータセット(オープンデータ)である.

    https://serre-lab.clps.brown.edu/resource/hmdb-a-large-human-motion-database/#introduction

    【関連情報】

    Hour Grass Network

    Hour Grass Network は,stacked hourglass と呼ばれるアーキテクチャを特色とする CNN (convolutional neural network) である.

    姿勢推定 (pose estimation) は,画像から,関節 (joint) の (x,y) 座標を得たり, ヒートマップを得る(ヒートマップでは,画素ごとに値を持ち,その値は,関節である確率が高いほど,高い値になる) 姿勢制御では,さまざまなスケールでの情報を扱うことが課題とされ, stacked hourglass で解決できるとされている. hougrass では,最初にプーリングを行い,その後アップサンプリングを行う. hougrass を直接に並べて stacked hourglass を構成する.

    Hour Grass Network の文献は次の通りである.

    A. Newell, K. Yang, and J. Deng. Stacked hourglass net- works for human pose estimation. In ECCV, 2016, CoRR, abs/1603.06937.

    https://arxiv.org/pdf/1603.06937v2.pdf

    関連項目】 姿勢推定

    Windows でのインストールと学習

    Hour Grass Network を用いた姿勢推定については,次の文献がある.

    qhttps://github.com/bearpaw/pytorch-pose

    上の文献では,ディープラーニングにより,人体全身の姿勢推定を行っている. その学習は,次の手順で行う

    git clone https://github.com/bearpaw/pytorch-pose
    py -3.6 -m pip install scipy==1.1.0 imutils easydict progress
    py -3.6 -m pip install -U torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu117
    cd pytorch-pose
    mkdir .\checkpoint
    mkdir .\checkpoint\mpii
    mkdir .\checkpoint\mpii\hg_s1_b1
    # MPII データセットを用いた学習
    py -3.6 .\example\main.py --dataset mpii --arch hg --stack 1 --block 1 --features 256 --checkpoint .\checkpoint\mpii\hg_s1_b1 --anno-path .\data\mpii\mpii_annotations.json --image-path .\mpii\images
    

    HQ-SAM (Segment Anything in High Quality)

    HQ-SAMは、既存のSAM(Segment Anything Model)を拡張し、より高精度なゼロショットセグメンテーションを実現する手法である。SAMは、プロンプト(点、バウンディングボックス、粗いマスクなど)を入力として、多様なオブジェクトや視覚構造のセグメンテーションを可能にするモデルである。しかし、SAMは細かい構造を持つオブジェクトに対するセグメンテーションが不十分で、その精度に限界がある。この問題を解決するために、HQ-SAMはSAMを拡張している。HQ-SAMでは、SAMのマスクデコーダに新しい学習可能な「HQ-Output Token」を導入している。さらに、グローバルなセマンティックコンテキストとローカルな境界(バウンダリ)の詳細を両方考慮する「Global-local Feature Fusion」も導入されている。複数のデータセットでの実験により、HQ-SAMが高精度なセグメンテーションマスクを生成できることが確認されている。

    文献】 Ke, Lei and Ye, Mingqiao and Danelljan, Martin and Liu, Yifan and Tai, Yu-Wing and Tang, Chi-Keung and Yu, Fisher, Segment Anything in High Quality, arXiv:2306.01567, 2023.

    https://arxiv.org/pdf/2306.01567v1.pdf

    サイト内の関連ページ

    関連する外部ページ

    関連項目SAM (Segment Anything Model)

    HRNetw32

    姿勢推定(pose estimation) の一手法.

    関連項目MMPose, 姿勢推定(pose estimation)

    Human 3.6M データセット

    ディープラーニングにより姿勢推定を行うためのデータとして利用できる.

    利用には, https://vision.imar.ro/human3.6m/register.php での申請を必要とする.

    http://vision.imar.ro/human3.6m/description.php

    Catalin Ionescu, Dragos Papava, Vlad Olaru and Cristian Sminchisescu, Human3.6M: Large Scale Datasets and Predictive Methods for 3D Human Sensing in Natural Environments, IEEE Transactions on Pattern Analysis and Machine Intelligence, vol. 36, No. 7, July 2014

    iBUG 300-W データセット

    iBUG 300-W データセットは, 顔の 68 ランドマーク のデータである.7764枚の顔画像について,手作業で,顔の 68 ランドマークのアノテーションとラベル付が行われている.

    顔ランドマーク (facial landmark)は,目,眉,鼻,口,あごのラインなど,顔のパーツの構造を特定でぃる形状予測器 (shape predictor) の学習に使うことができる.

    iBUG 300-W データセットの URL: https://ibug.doc.ic.ac.uk/resources/300-W/

    関連項目顔の 68 ランドマーク, 顔ランドマーク (facial landmark), 顔のデータベース

    image content removal(画像コンテンツの除去)

    画像の中で,除去する対象となるオブジェクトの境界などを指定することにより, 指定されたオブジェクトを除去し,除去された部分の画素は, image completion and extrapolation で補う.

    次の文献では, 除去する対象となるオブジェクトの境界を正確に指定しなくても, オブジェクトスコアマップ (object score map) を scene parsing network を用いて 推定することにより, image content removal(画像コンテンツの除去)ができるとされている.

    この論文の手法の SunkskyF による実装は,次のページで公開されている.

    https://github.com/SunskyF/StructCompletion-python

    実行の前準備として,「pip install -U opencv-python opencv-contrib-python」を実行する.demo.py の実行結果は次のとおりである.

    [image]

    [image]

    関連項目】 image completion and extrapolation

    ImageMagick

    関連項目画像データの形式変換MagickWand

    ImageMagick の主なコマンド

    Windows でのインストールは,別ページ »で説明している.

    Ubuntu でインストールを行うには,次のコマンドを実行.

    sudo apt -y update
    sudo apt -y install imagemagick
    

    image matting

    前景の色を F,背景の色を B とし,元画像の色は I = alpha * F + (1 - alpha) * B とする. 元画像 I は既知であり,F, B, alpha は未知であるとする. このとき alpha を推定することを image matting という(alpha image matting ともいう).

    写真や動画の前景背景分離に用いることができる. 物体検出 や salient object detection との違いとしては, ガラスなどの半透明なもの,髪の毛や網のようなもの,そして,前景が必ずしも画面中央に集まっているとは限らず,画面全域にある(網越しに外を見るような場合)を想定していることがある.

    【関連情報】

    関連項目GCA, IndexNet, DIM, AIM-500 (Automatic Image Matting-500) データセット

    Trimap-based matting

    trimap では,次の 3つを考える. 前景である画素は白,背景である画素は黒,transaction である画素は灰色の 3通りに 塗り分けた画像を trimap という.

    Trimap-based matting では, 元画像と,その trimap を用いて image matting を行う. ディープラーニングによる Trimap-based matting の手法としては,Xu らの Deep Image Matting (DIM) (2017年)(文献 [1]) などが知られている.

    【関連情報】

    Backgroud matting

    Backgroud matting は,image matting において背景画像を用いる. つまり,元画像と,追加の背景画像を用いて image matting を行う. 元画像での背景と,追加の背景画像は同一の場所で撮影されたものが想定されている.そのとき,全に一致しなくてもよい(わずかな位置のずれや照明条件の変化は許容される).

    ディープラーニングによるbackground matting Shanchuan Lin らの Backgroud Matting (2021年)(文献 [2])などが知られる. Backbone に ResNet50, ASPP (Atrous Spatial Pyramid Pooling, DeepLabv3 のものに従う).

    Background matting では,Trimap を必要としない. ZOOM などのビデオ会議などで,グリーンバックを使わずに,前景と背景を分離するとき, 背景の取得は容易であり, Background matting は有用である.

    【関連情報】

    Portrait matting

    人物や動物に特化した image matting である. 人物や動物が写った写真や動画に対して,image matting を行う. このとき,Trimap や 背景画像などの追加の情報を準備することなく image matting を行う手法が種々提案されている.

    Automatic image matting

    Trimap や 背景画像などの追加の情報を必要とせず, 人物や動物など以外でも(例えば,半透明のコップ,網ごしの風景写真など) image matting を行うもの. Li らの GFM (文献 [3])(2020 年)は,ディープラーニングによる Trimap の推定が行われており, Li らの unified semantic model (文献 [4])(2021 年)は,Salient Opaque, Salient Transparent/Meticulous, Non-Salient の 3種類の画像を扱えるモデルであり,GGM の拡張により,unified semantic model の推定を行っている.

    ImageNet データセット

    ImageNet データセットは、画像分類物体検出のタスクで利用されるデータセット。 機械学習における画像分類物体検出のタスクで、学習、検証、テストに利用される。 ImageNet-1K は ImageNet データセットのサブセットで、ImageNet Large Scale Visual Recognition Challenge(ILSVRC)でベンチマークで使用されている。

    [image]
    プログラム

    ImageNet-1K の 1000クラスの表示

    このプログラムはImageNet-1Kの1000クラスのデータファイル(クラス番号とクラス名のデータファイル)をダウンロードし、JSONに変換して保存した後、クラス番号とクラス名をすべて表示します。インターネット接続が必要で、requestsライブラリが必要です。

    import requests
    import json
    
    def download_file(url, filename):
        """指定されたURLからファイルをダウンロードし、ローカルに保存する"""
        response = requests.get(url)
        with open(filename, 'wb') as file:
            file.write(response.content)
    
    def convert_txt_to_json(txt_file, json_file):
        """テキストファイルをJSON形式に変換し、保存する"""
        imagenet_classes = {}
        with open(txt_file, "r") as f:
            for i, line in enumerate(f):
                imagenet_classes[str(i)] = line.strip()
        with open(json_file, "w") as f:
            json.dump(imagenet_classes, f)
    
    def display_classes(json_file):
        """JSONファイルからクラス情報を読み込み、表示する"""
        with open(json_file) as f:
            imagenet_classes = json.load(f)
        for class_id, class_name in imagenet_classes.items():
            print(f"Class ID: {class_id}, Class Name: {class_name}")
    
    # メイン処理
    if __name__ == "__main__":
        url = "https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt"
        txt_filename = "imagenet_classes.txt"
        json_filename = "imagenet_class_index.json"
        # ファイルのダウンロード
        download_file(url, txt_filename)
        # テキストファイルをJSONに変換
        convert_txt_to_json(txt_filename, json_filename)
        # クラス情報の表示
        display_classes(json_filename) 
    

    ImegeNet のクラス: 別ファイルに記載している.

    ImageNet データセットは次の URL で公開されているデータセット(オープンデータ)である.

    ImageNet データセットの URL: https://image-net.org/

    関連する外部ページ

    関連項目画像分類, 物体検出

    IMDb データセット

    IMDb の URL: https://www.imdb.com/

    IMDb での映画の批評は,批評文とスコア(10点満点)である. IMDb データセットでは,7点以上の批評は positive,4点以下の批評は negative としている.つまり,2種類ある. そして,IMDb データセットには,positive か negative の批評のみが含まれている(中間の点数である 5点,6点のものは含まれていない).そして, positive,negative の批評が同数である. 学習用として,positive,negative がそれぞれ 25000. 検証用として,positive,negative がそれぞれ 25000.

    IMDb データセットのURL: https://ai.stanford.edu/%7Eamaas/data/sentiment/

    関連項目Keras に付属のデータセット, TensorFlow データセット, オープンデータ,

    Python での IMDb データセットのロード(TensorFlow データセットを使用)

    次の Python プログラムは,TensorFlow データセットから,IMDb データセットのロードを行う. x_train, y_train が学習用のデータ.x_test, y_test が検証用のデータになる.

    次のプログラムでは,そして確認表示を行う.

    tensorflow_datasets の loadで, 「batch_size = -1」を指定して,一括読み込みを行っている.

    from __future__ import absolute_import, division, print_function, unicode_literals
    import tensorflow as tf
    import numpy as np
    import tensorflow_datasets as tfds
    
    %matplotlib inline
    import matplotlib.pyplot as plt
    import warnings
    warnings.filterwarnings('ignore')   # Suppress Matplotlib warnings
    
    imdb_reviews, imdb_reviews_metadata = tfds.load('imdb_reviews', with_info = True, shuffle_files=True, as_supervised=True, batch_size = -1)
    x_train, y_train, x_test, y_test = imdb_reviews['train'][0], imdb_reviews['train'][1], imdb_reviews['test'][0], imdb_reviews['test'][1]
    
    # 確認表示
    import pandas as pd
    display(pd.DataFrame(x_train[0:14], y_train[0:14]))
    

    [image]
    Python での IMDb データセットのロード(Keras を使用)

    IMDb データセットは,次のプログラムでロードできる.

    Keras のプログラム】

    from tensorflow.keras.datasets import imdb
    (x_train, y_train), (x_test, y_test) = imdb.load_data()
    

    Imm 顔データベース (IMM Face Database)

    40種類の人間の顔を撮影した240枚の画像. 58個の顔ランドマークが付いている.

    URL: http://www2.imm.dtu.dk/pubdb/pubs/3160-full.html

    M. M. Nordstr{\o}m and M. Larsen and J. Sierakowski and M. B. Stegmann, The IMM Face Database - An Annotated Dataset of 240 Face Images

    http://www2.imm.dtu.dk/pubdb/edoc/imm3160.pdf

    関連項目顔のデータベース

    iNaturalist データセット

    画像のデータセット.アノテーションとしてバウンディングボックスが付けられている.Imbalance の大きさを特徴とする.

    次の URL で公開されているデータセット(オープンデータ)である.

    URL: https://github.com/visipedia/inat_comp/tree/master/2017

    関連項目画像分類, 物体検出

    InsightFace

    顔検出 (face detection),顔のアラインメント, 顔検証 (face verification)顔識別 (face identification)の機能を持つ.

    InsightFace の GitHub のページ: https://github.com/deepinsight/insightface

    関連項目ArcFace 法, Chandrika Deb の顔マスク検出, Dlib の顔検出, face alignment, MobileFaceNets, 顔検出 (face detection)

    Google Colaboratory で,InsightFace による顔検出及び年齢と性別の予測

    公式ページ (https://github.com/deepinsight/insightface/tree/master/python-package) に記載の顔検出及び年齢と性別の予測のプログラムを変更して実行.

    このプログラムは buffalo_l という名前の事前学習済みモデルを使用している.

    次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する).

    1. InsightFace のインストール

      GPU を使わない場合には「onnxruntime-gpu」でなく,「onnxruntime」をインストールすること.

      !pip3 install -U insightface onnxruntime-gpu opencv-python numpy
      

      [image]
    2. 顔検出及び年齢と性別の予測の実行

      動作確認のため,公式ページ (https://github.com/deepinsight/insightface/tree/master/python-package) に記載の,顔検出及び年齢と性別の予測のプログラムを実行する.

      このプログラムは buffalo_l という名前の事前学習済みモデルを使用している.

      • 顔検出のモデル: SCRFD-10GF
      • 顔認識のモデル: ResNet50@WebFace600K
      • 顔のアラインメント: 2d106, 3d68
      • 属性: 年齢,性別

      このプログラムの実行により,result.jpg ファイルができる.

      import cv2
      import numpy as np
      %matplotlib inline
      import matplotlib.pyplot as plt
      import warnings
      warnings.filterwarnings('ignore')   # Suppress Matplotlib warnings
      import insightface
      from insightface.app import FaceAnalysis
      from insightface.data import get_image as ins_get_image
      
      app = FaceAnalysis(providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
      app.prepare(ctx_id=0, det_size=(640, 640))
      
      img = ins_get_image('t1')
      faces = app.get(img)
      rimg = app.draw_on(img, faces)
      for i in faces:
        print("gender %s, age %d" % (('F' if i['gender'] == 0 else 'M'), i['age']))
      plt.style.use('default')
      plt.imshow(cv2.cvtColor(rimg, cv2.COLOR_BGR2RGB))
      plt.show()
      cv2.imwrite("./result.jpg", rimg)
      

      [image]
    3. 顔検出及び年齢と性別の予測の実行

      顔の画像ファイルは何でも良いが,ここでは,画像ファイルをダウンロードしている.

      !curl -O https://www.kkaneko.jp/sample/face/3284.png
      !curl -O https://www.kkaneko.jp/sample/face/3285.png
      !curl -O https://www.kkaneko.jp/sample/face/3287.png
      !curl -O https://www.kkaneko.jp/sample/face/3288.png
      !curl -O https://www.kkaneko.jp/sample/face/3289.png
      !curl -O https://www.kkaneko.jp/sample/face/3290.png
      

      [image]

      いま準備した画像ファイルについて,顔検出及び年齢と性別の予測の実行

      import cv2
      import numpy as np
      %matplotlib inline
      import matplotlib.pyplot as plt
      import warnings
      warnings.filterwarnings('ignore')   # Suppress Matplotlib warnings
      import insightface
      from insightface.app import FaceAnalysis
      from insightface.data import get_image as ins_get_image
      
      app = FaceAnalysis(providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
      app.prepare(ctx_id=0, det_size=(640, 640))
      
      files = ['3284.png', '3285.png','3287.png', '3288.png', '3289.png', '3290.png']
      
      for f in files:
          img = cv2.imread(f)
          faces = app.get(img)
          for i in faces:
              print("gender %s, age %d" % (('F' if i['gender'] == 0 else 'M'), i['age']))
          rimg = app.draw_on(img, faces)
          plt.style.use('default')
          plt.imshow(cv2.cvtColor(rimg, cv2.COLOR_BGR2RGB))
          plt.show()
      

      [image]

      [image]

      [image]
    InsightFace のインストールと動作確認(顔検出,年齢と性別の推定,顔識別,人体検出)(InsightFace,PyTorch,Python を使用)(Windows 上)

    別ページ »で説明している.

    InsightFace のインストールと動作確認(顔検出,年齢と性別の推定)(Python, PyTorch を使用)(Ubuntu 上)

    別ページ »で説明している.

    Iris データセット

    Iris データセットは公開されているデータセット(オープンデータ)である.

    文献

    R.A. Fisher, The use of multiple measurements in taxonomic problems, Annual Eugenics, 7, Part II, pp. 179-188, 1936.

    サイト内の関連ページ

    関連する外部ページ

    関連項目オープンデータ, データフレーム

    JAX: Autograd and XLA のインストール(Ubuntu 上)

    URL: https://github.com/google/jax

    Ubuntu でインストールを行うには,次のコマンドを実行.

    sudo apt -y install python3-pip
    sudo pip3 install -U "jax[cuda111]" -f https://storage.googleapis.com/jax-releases/jax_releases.html
    

    JHU-CROWD++ データセット

    画像数は 4822枚である. 各画像の人物数は 0 から 25791 である.

    【関連用語】 crowd counting, FIDTM, オープンデータ

    Johns Hopkins 大の COVID-19 データレポジトリ

    国別,地域別の感染者データ

    URL: https://github.com/CSSEGISandData/COVID-19

    次の Python プログラムは, Johns Hopkins 大の COVID-19 データレポジトリからデータをダウンロードし,ロードし,表示する.

    !curl -LO https://github.com/CSSEGISandData/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv
    import pandas as pd
    df = pd.read_csv("./time_series_covid19_confirmed_global.csv")
    display(df)
    display(df.groupby(['Country/Region'], as_index=False).sum())
    

    関連項目時系列データ

    JupyterLab

    Jupyter Lab は Python プログラム作成に関する種々の機能を持ったソフトウェア.

    JupyterLab について:別ページ で説明している.

    Jupyter Qt Console

    Jupyter Qt Console は Python コンソールの機能を持ったソフトウェア.

    Jupyter Qt Console について:別ページ で説明している.

    Jupyter ノートブック (Jupyter Notebook)

    Jupyter ノートブックは,Pythonなどのプログラムのソースコード,実行結果などを1つのノートとして残す機能をもったノートブック.

    Jupyter ノートブック について:別ページ で説明している.

    Keras

    Keras は 機械学習のAPI の機能を持つ. Python 言語から利用可能. TensorFlow, CNTK, Theano など,さまざまなディープラーニングのフレームワークの上で動く.

    Keras の概要

    次のプログラムでは,損失関数を, categorical crossentropy, 最適化法を 確率的勾配降下法 (SGD 法), 尺度を accuracy に設定している.

    m.compile(optimizer=tf.keras.optimizers.SGD(lr=0.01, momentum=0.9, nesterov=True),
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
    

    ※ 目的関数については: https://keras.io/ja/objectives/

    関連する外部ページ

    サイト内の関連ページ

    関連項目Applications of Deep Neural Networks, TensorFlow, ディープラーニング

    Keras のインストール

    Keras-GAN のページ

    Avatar Erik Linder-Norén により GitHub で公開されているKeras-GAN のページ

    URL は次の通り.

    Keras-GAN のページ: https://github.com/eriklindernoren/Keras-GAN  

    Keras でのカーネルの初期化

    次のプログラムの中の kernel_initializer の部分. 標準偏差を 0.01 になるように重みを設定している.

    Keras のプログラム】

    m.add(Dense(units=100, input_dim=len(768[0])), kernel.iniializer.TruncatedNormal(stddev=0.01))  
    
     

    Keras での学習

    教師データ x_trainy_train (x_train は入力データの numpy 配列もしくは numpy 配列のリスト,y_train はクラス番号の numpy 配列)を用いて, バッチサイズが 32,エポック数を 10 として学習したいときには,次のコマンドを用いる.

    Keras のプログラム】

    history = m.fit(x_train, y_train, batch_size=32, epochs=50, validation_data=(x_test, y_test))
    
     

    Keras での検証(バリデーション)

    Keras での学習において,「validation_data」を付けることで,検証(バリデーション)が行われる.

    このとき,検証(バリデーション)に使うデータ(x_test, y_test)をいろいろ変えながら,Kerasでの検証(バリデーション)を行う.

    Keras のプログラム】

    history = m.fit(x_train, y_train, batch_size=32, epochs=50, validation_data=(x_test, y_test))
    

    結果(上のプログラムでは history)を見て,過学習学習不足を判断する.history は次のようなプログラムで表示できる.

    Keras のプログラム】

    import pandas as pd
    h = pd.DataFrame(history.history)
    h['epoch'] = history.epoch
    print(h)
    
     

    Keras でのコンパイル

    Kerasモデルのコンパイルにおいては, オプティマイザ(最適化器)損失関数メトリクスの指定を行う必要がある.

    Keras でのモデル m のコンパイルのプログラムは「m.compile」のように書く.

    Keras に付属のデータセット

    データセットは,データの集まりのこと. Python の keras には,次のデータセットを簡単にダウンロードできる機能がある.

    keras に付属のデータセットを取得するときのオプションについては, https://keras.io/ja/datasets/(日本語版), https://keras.io/api/datasets/(英語版) に説明されている.

    関連項目Boston housing price 回帰データセット, CIFAR-10 データセット, CIFAR100 データセット, IMDb データセット, Reuters newswire topics データセット, MNIST データセット, Fashion MNIST データセット  

    Keras の応用

    Keras の応用としては, MobileNetV2, Inception-ResNet, ResNet50DenseNet121, DenseNet169NASNetなどの画像分類のモデルがある. (その詳細は,https://keras.io/ja/applications/

    Keras では,これらモデルについて,ImageNet データセット での学習済みモデルを,次のようなプログラムで,簡単に使えるようにすることができる.

    Keras のプログラム】

    from tensorflow.keras.applications.mobilenet_v3 import MobileNetV3
    m = MobileNetV3(weights='imagenet')
    

    関連項目ResNet50, ResNet101, ResNet152, その他の ResNet, Inception-ResNet, DenseNet121, DenseNet169, NASNet, MobileNetV2

    Keras で利用可能な画像分類のモデルは,https://keras.io/api/applications/index.html で説明されている.

    Kinetics Human Action Video Dataset (Kinetics Human Action Video データセット)

    400/600/700 種類の人間の行動をカバーする最大65万のビデオクリップの URL リンク集とアノテーションである. それぞれのクリップには,1つの行動クラスがアノテーションされている. ビデオの長さは,約10秒である. 機械学習による行動分類,行動認識,ビデオ検索などの学習や検証に利用できるデータセットである.

    ディープラーニングで,人間の行動推定に利用できる.

    Kinetics データセット >は次の URL で公開されているデータセット(オープンデータ)である.

    https://deepmind.com/research/open-source/kinetics

    【関連情報】

    Google Colaboratory で,Kinetics データセットのダウンロード

    次のコマンドは Google Colaboratory で動く(コードセルを作り,実行する).

    !curl -O https://storage.googleapis.com/deepmind-media/Datasets/kinetics700_2020.tar.gz
    !tar -xvzof kinetics700_2020.tar.gz
    !ls kinetics700_2020
    

    [image]
    Windows での Kinetics データセットのダウンロード
    mkdir c:\data
    mkdir c:\data\kinetics
    cd c:\data\kinetics
    curl -O https://storage.googleapis.com/deepmind-media/Datasets/kinetics700_2020.tar.gz
    "c:\Program Files\7-Zip\7z.exe" x kinetics700_2020.tar.gz
    "c:\Program Files\7-Zip\7z.exe" x kinetics700_2020.tar
    

    KITTI データセット

    カラーのカメラ,モノクロのステレオカメラ,3次元レーザースキャナなどのさまざまなセンサーのデータから構成される.

    http://www.cvlibs.net/datasets/kitti

    【関連情報】

    関連項目オープンデータ, 物体検出

    KITTY オドメトリデータセットのダウンロード

    車両からの観測画像と車両の自己位置のデータ.ビジュアルオドメトリに使用.

    URL: https://github.com/uoip/monoVO-python

    1. テスト用の画像データのダウンロードと展開(解凍)

      テスト画像データをダウンロードしたい.再度,uoip / monoVO-python の Web ページを開く

      https://github.com/uoip/monoVO-python

    2. KITTY odometry data set (grayscale, 22 GB)」をクリック.

      [image]
    3. 濃淡 (grayscale) 画像が欲しいので,「Download odometry data set (grayscale, 22GB)」をクリック.

      これは,画像データの .zip ファイルである(多数の .png形式の画像ファイルを zip 形式に固めたものである).

      [image]
    4. メールアドレスを登録し,「Request Download Link」をクリック.

      [image]
    5. 電子メールで通知が送られてくるので確認の上,電子メールの中のリンクをクリックする.
      • 件名を確認し,他のメールと勘違いしていないことをよく確認したうえでリンクをクリックすること.
      • 通知が送られるまで,それほど時間はかからない.
      • 電子メールの中身を他の人に見せる(他の人に代理作業を頼む)のはマナー違反
    6. リンクをクリックするので、ダウンロードが始まるので確認する.

      ※ ダウンロードには時間がかかる

    7. いまダウンロードしたテスト用画像データの .zip ファイルを,分かりやすいディレクトリ(日本語を含まないこと)に展開(解凍)する.

      Windows での展開(解凍)に便利な 7-Zip: 別ページ »で説明

      この .zip ファイルは,C:\data_odometry_gray\dataset に展開(解凍)したものとして,説明を続けるので,適切に読み替えてください.

    8. 展開(解凍)してできたファイルを確認する.
      • .png 形式のファイルが多数ある
      • ファイル名は6桁の数字の連番になっている
      • 多数のディレクトリに分かれている

      [image]
    KITTI データセットのビジュアライザ

    https://github.com/navoshta/KITTI-Dataset

    KITTI データセットの Python インタフェース

    https://github.com/utiasSTARS/pykitti

    K 近傍探索 (K nearest neighbour)

    K 近傍探索 (K nearest neighbour)のアルゴリズムは,次の性質を持つ.

    関連項目Fast-Robust-ICP, libnabo, libpointmatcher

    ks_1033_data

    ks_1033_data は,次のページで CSV ファイルと Excel ファイルで公開されているデータセット(オープンデータ)である.

    https://github.com/wireservice/csvkit/tree/master/examples/realdata

    関連項目オープンデータ, データフレーム

    Google Colaboratory で,ks_1033_data データセットのダウンロード

    次のコマンドは Google Colaboratory で動く(コードセルを作り,実行する).

    !curl -O https://github.com/wireservice/csvkit/tree/master/examples/realdata/ks_1033_data.csv
    !ls -al ks_1033_data.csv
    

    [image]

    L2 正則化

    正則化の一手法である. L2 正則化では,重みの二乗の合計に比例したペナルティを,重みに与える.

    L2 正則化を行う Keras のプログラム

    L2 正則化を行いたいときは 次のようにする.

    import tensorflow.compat.v2 as tf
    tf.keras.layers.Dense(128, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.001))
    

    LabelMe インタフェース

    LabelMe インタフェースは,アノテーションのツール.

    関連項目】 アノテーション (annotation)

    Windows での LabelMe のインストールと確認

    公式ページ https://github.com/wkentaro/labelmeの記載に従う.

    1. インストール

      Windows では,コマンドプロン プトを管理者として実行し, 次のコマンドを実行する.

      python -m pip install labelme
      
    2. 確認のため「labelme」で起動

      [image]

    LAION

    LAION-2B の画像数は約20億枚. LAION-5B の画像数は約50億枚.

    関連する外部ページ

    LAION の公式ページ: https://laion.ai/

    LaMa

    LaMa は,Image Inpainting (イメージ・インペインティング)のための技術である.2021年発表.

    Image Inpainting (イメージ・インペインティング) 画像の欠落部分を補うことで,画像の中の不要な部分を消すときにも役立つ.

    LaMa のデモページ

    関連項目】 image inpainting

    Windows での Lama Cleaner のインストール

    Windows での Lama Cleaner のインストール: 別ページで説明してリウ.

    LAPACK

    lapack は,行列に関する種々の問題(連立1次方程式,固有値問題,などなど多数)を解く機能を持つソフトウェア.BLAS の機能を使う.

    netlib の lapack のページ: http://www.netlib.org/lapack

    lapack 参照実装の Web ページ: https://github.com/Reference-LAPACK/lapack-release

    関連項目BLAS, clapack, OpenBLAS

    Windows での LAPACK のインストール

    Windows での LAPACK のインストール(Windows 上): 別ページ »で説明している.

    Ubuntu での LAPACK のインストール

    Ubuntu でインストールを行うには,次のコマンドを実行.

    sudo apt -y update
    sudo apt -y install libopenblas-dev liblapack-dev
    
    LAPACK のプログラム例

    dgeev()関数 (固有値と固有ベクトル)を使用.

    #include<stdio.h>
    
    // CLAPACK ではなく LAPACK を直接呼び出す.
    
    // CLAPACK については,次の URL を見よ.
    //   see http://www.netlib.org/clapack/clapack.h
    
    // ?geev : simple driver for eigenvalues/vectors
    
    // 決まり文句 (CLAPACK との互換用)
    
    #define doublereal double
    #define integer long int
    
    extern
      integer dgeev_(char *jobvl, char *jobvr, integer *n, doublereal *a,
             integer *lda, doublereal *wr, doublereal *wi, doublereal *vl,
             integer *ldvl, doublereal *vr, integer *ldvr, doublereal *work,
             integer *lwork, integer *info);
    
    integer eigenvalues( integer n, doublereal *a, doublereal *wr, doublereal *wi ) {
      /* LAPACK の _dgeev() を使って固有値(だけ)を求める */
    
      integer n3 = n * n * n;
      integer info;
    
      doublereal *vl = (doublereal *)calloc(sizeof(doublereal), n * n);
      doublereal *vr = (doublereal *)calloc(sizeof(doublereal), n * n);
      doublereal *work = (doublereal *)calloc(sizeof(doublereal), n3);
    
    
      (void) dgeev_(
            /* char *jobvl */      "N",  /* "N" なので左固有ベクトルを計算しない */
            /* char *jobvr */      "N",  /* "N" なので右固有ベクトルを計算しない */
            /* integer *n */       &n,   /* 正方行列の次数 */
            /* doublereal *a, */   a,    /* A */
            /* integer *lda, */    &n,   /* A 用の作業領域 */
            /* doublereal *wr, */  wr,   /* 固有値の実部 */
            /* doublereal *wi, */  wi,   /* 固有値の虚部 */
            /* doublereal *vl, */  vl,   /* 左固有値 */
            /* integer *ldvl, */   &n,   /* 左固有値の作業用 */
            /* doublereal *vr, */  vr,   /* 右固有値 */
            /* integer *ldvr, */   &n,   /* 左固有値の作業用 */
            /* doublereal *work, */ work, /* 作業用 */
            /* integer *lwork, */  &n3,   /* 作業用の行列の次元 */
            /* integer *info */    &info);
    
      free( work );
      free( vr );
      free( vl );
    
      return info;
    
    }
    
    integer eigenvalues_rightvectors( integer n, doublereal *a, doublereal *wr, doublereal *wi, doublereal *vr ) {
      /* LAPACK の _dgeev() を使って固有値と右固有ベクトルを求める */
      /* A * v(j) = lambda(j) * v(j), v(j) is the right eigen vector */
    
      integer n3 = n * n * n;
      integer info;
    
      doublereal *vl = (doublereal *)calloc(sizeof(doublereal), n * n);
      doublereal *work = (doublereal *)calloc(sizeof(doublereal), n3);
    
    
      (void) dgeev_(
            /* char *jobvl */      "N",  /* "N" なので左固有ベクトルを計算しない */
            /* char *jobvr */      "V",  /* "V" なので右固有ベクトルを計算する */
            /* integer *n */       &n,   /* 正方行列の次数 */
            /* doublereal *a, */   a,    /* A */
            /* integer *lda, */    &n,   /* A 用の作業領域 */
            /* doublereal *wr, */  wr,   /* 固有値の実部 */
            /* doublereal *wi, */  wi,   /* 固有値の虚部 */
            /* doublereal *vl, */  vl,   /* 左固有値 */
            /* integer *ldvl, */   &n,   /* 左固有値の作業用 */
            /* doublereal *vr, */  vr,   /* 右固有値 */
            /* integer *ldvr, */   &n,   /* 左固有値の作業用 */
            /* doublereal *work, */ work, /* 作業用 */
            /* integer *lwork, */  &n3,   /* 作業用の行列の次元 */
            /* integer *info */    &info);
    
      free( work );
      free( vl );
    
      return info;
    }
    
    int main( integer argc, char **argv ) {
      int i;
      integer n = 10;
      doublereal *a  = (doublereal *)calloc(sizeof(doublereal), n * n);
      doublereal *wr = (doublereal *)calloc(sizeof(doublereal), n);
      doublereal *wi = (doublereal *)calloc(sizeof(doublereal), n); 
      /* doublereal *vr = (doublereal *)calloc(sizeof(doublereal), n * n); */
    
      eigenvalues( n, a, wr, wi );
      for(i = 0; i < n; i++) {
        printf("%5d %15.7e %15.7e\n", i + 1, *(wr + i), *(wi + i));
      }
    
      free(wi);
      free(wr);
      free(a);
    
      return 0;
    }
    

    Leeds Sports Pose Dataset (LSP データセット)

    スポーツ選手を中心としで,Flickr から収集した2000枚の画像に, 姿勢(ポース)についてのアノテーションを行ったもの. 最も目立つ人物が,およそ150ピクセルになるようにスケーリングされている. 各画像には,14個のジョイント(関節)の位置がアノテーションされている. オリジナル画像の帰属 (attribution) とFlickrのURLは,各画像ファイルのJPEGコメントに記載されている.

    ディープラーニングにより姿勢推定を行うためのデータとして利用できる.

    次の URL で公開されているデータセット(オープンデータ)である.

    URL: https://dbcollection.readthedocs.io/en/latest/datasets/leeds_sports_pose_extended.html

    【関連情報】

    Google Colaboratory で,Leeds Sports Pose Dataset (LSP データセット)のダウンロード

    次のコマンドは Google Colaboratory で動く(コードセルを作り,実行する).

    !curl -O http://sam.johnson.io/research/lsp_dataset.zip
    !curl -O http://sam.johnson.io/research/lspet_dataset.zip
    !unzip lsp_dataset.zip -d lsp_dataset
    !unzip lspet_dataset.zip -d lspet_dataset
    !ls -la lspet_dataset
    

    [image]

    アノテーションファイルは,次の URL からダウンロードできる.

    https://drive.google.com/file/d/1GZxlTLuMfA3VRvz2jyv8fhJDqElNrgKS/view

    Windows での,Leeds Sports Pose Dataset (LSP データセット)のダウンロード

    Windows の場合.次により c:\data\lsp にダウンロードされる.

    mkdir c:\data
    mkdir c:\data\lsp
    mkdir c:\data\lsp\images
    cd c:\data\lsp\images
    curl -O http://sam.johnson.io/research/lsp_dataset.zip
    curl -O http://sam.johnson.io/research/lspet_dataset.zip
    powershell -command "Expand-Archive -DestinationPath . -Path lsp_dataset.zip"
    powershell -command "Expand-Archive -DestinationPath . -Path lspet_dataset.zip"
    

    アノテーションファイルは,次の URL からダウンロードできる.

    https://drive.google.com/file/d/1GZxlTLuMfA3VRvz2jyv8fhJDqElNrgKS/view

    Ubuntu での,Leeds Sports Pose Dataset (LSP データセット)のダウンロード

    Ubuntu の場合.次により,/usr/local/data/lsp/images にダウンロードされる.

    mkdir -p /usr/local/data/lsp/images
    cd /usr/local/data/lsp/images
    curl -O http://sam.johnson.io/research/lsp_dataset.zip
    curl -O http://sam.johnson.io/research/lspet_dataset.zip
    unzip lsp_dataset.zip -d lsp_dataset
    unzip lspet_dataset.zip -d lspet_dataset
    

    アノテーションファイルは,次の URL からダウンロードできる.

    https://drive.google.com/file/d/1GZxlTLuMfA3VRvz2jyv8fhJDqElNrgKS/view

    LFW データセット

    LFWデータセットには,「in-the-wild」のラベル付きの顔のデータベースである. 合計で 13,233枚,5,749人の顔画像が含まれている.

    機械学習による顔認識の学習や検証に利用できるデータセットである.

    関連項目顔認識 (face recognition), 顔のデータベース

    libc++

    libc++ は,LLVMのサブプロジェクトである.

    libc++ は,C++ の標準ライブラリである.

    【関連する外部ページ】

    関連項目LLVM

    libiconv

    Windows での libiconv のインストール

    Windows での libiconv のインストール(Windows 上): 別ページ »で説明している.

    libnabo

    libnabo は,K 近傍探索 (K nearest neighbour) の機能を持つライブラリ.

    ANN よりも高速だとされている.

    関連項目K 近傍探索 (K nearest neighbour)

    Windows での libnabo のインストール

    ソースコードからビルドする

    https://github.com/CAOR-MINES-ParisTech/libpointmatcher/blob/master/doc/CompilationWindows.md の手順に従う.

    1. Windows では,前準備として次を行う.
    2. インストール

      Visual Studio の x64 Native Tools コマンドプロンプト管理者として実行する. 次のコマンドを実行する.

      c:\libnabo にインストールされる.

      cd %LOCALAPPDATA%
      rmdir /s /q libnabo
      git clone --recursive https://github.com/ethz-asl/libnabo
      cd libnabo
      rmdir /s /q build
      mkdir build
      cd build
      del CMakeCache.txt
      cmake -G "Visual Studio 17 2022" -T host=x64 ^
          -DCMAKE_BUILD_TYPE=Release ^
          -DCMAKE_INSTALL_PREFIX="c:/libnabo" ^
          -DEIGEN_INCLUDE_DIR="c:/eigen/include/eigen3" ^
          -DLIBNABO_BUILD_PYTHON=OFF ^
          -DCMAKE_BUILD_TYPE=RelWithDebInfo ^
      ..
      msbuild /m:2 libnabo.sln -p:Configuration=Release
      
    3. テストプログラムのビルド

      Visual Studio の x64 Native Tools コマンドプロンプト管理者として実行する. 次のコマンドを実行する.

      c:\libnabo にインストールされる.

      cd %LOCALAPPDATA%\libnabo\examples
      del CMakeCache.txt
      cmake -G "Visual Studio 17 2022" -T host=x64 ^
          -DCMAKE_BUILD_TYPE=Release ^
          -DCMAKE_INSTALL_PREFIX="c:/libnabo" ^
          -DEIGEN_INCLUDE_DIR="c:/eigen/include/eigen3" ^
          -DLIBNABO_BUILD_PYTHON=OFF ^
          -DCMAKE_BUILD_TYPE=RelWithDebInfo ^
      ..
      msbuild /m:2 libnabo.sln -p:Configuration=Release
      
    Ubuntu での libnabo のインストール

    Ubuntu でインストールを行うには,次のコマンドを実行.

    /usr/local/libnabo にインストールされる.

    sudo apt -y update
    sudo apt -y install libboost-all-dev libeigen3-dev git cmake cmake-curses-gui cmake-gui
    
    cd /tmp
    sudo rm -rf libnabo
    sudo git clone --recursive https://github.com/ethz-asl/libnabo
    sudo chown -R $USER libnabo
    
    cd /tmp/libnabo
    mkdir build
    cd build
    cmake \
        -DCMAKE_BUILD_TYPE=Release \
        -DCMAKE_INSTALL_PREFIX="/usr/local" \
        -DCMAKE_BUILD_TYPE=RelWithDebInfo \
    ..
    make 
    sudo make install
    cd /tmp/libnabo/examples
    cmake \
        -DCMAKE_BUILD_TYPE=Release \
        -DCMAKE_INSTALL_PREFIX="/usr/local" \
        -DCMAKE_BUILD_TYPE=RelWithDebInfo \
    ..
    make 
    sudo make install
    

    liboctave

    自分で,C++ のプログラムを書き,liboctave の機能を呼び出すことが簡単にできる.

    liboctave の C++ プログラムの見本

    「clock_t c = clock();」と「fprintf( stderr, "done, elapsed time = %f [sec]", ( (double)clock() - (double)c ) / CLOCKS_PER_SEC ); 」の2行は経過時間の測定のためです.

    #include<stdio.h>
    #include<time.h>
    #include<octave/config.h>
    #include<octave/Matrix.h>
    
    // 正方行列のサイズを指定
    #define DIM 2000
    
    int main( int argc, char **argv )
    {
      fprintf( stderr, "start, \n" );
      clock_t c = clock();
    
      // 行列の積と固有値/固有ベクトル
      Matrix X(DIM, DIM);
      Matrix Y(DIM, DIM, 1.0);
      Matrix Z = X * Y;
      EIG eig(X);
    
      fprintf( stderr, "done, elapsed time = %f [sec]", ( (double)clock() - (double)c ) / CLOCKS_PER_SEC );
      return 0;
    }
    

    Octave の 関数 conv2 を用いて,2次元の畳み込み(コンボリューション)を行う.

    関数 conv2 は,Octave ソースコードの DLD-FUNCTIONS/conv2.cc で定義されているので,「#include<octave/conv2.cc>」を含める.

    「clock_t c = clock();」と「fprintf( stderr, "done, elapsed time = %f [sec]", ( (double)clock() - (double)c ) / CLOCKS_PER_SEC ); 」の2行は経過時間の測定のため.

    // liboctave を用いた 2次元畳み込み(コンボリューション) #include<stdio.h> #include<time.h> #include<octave/config.h> #include<octave/Matrix.h> #include<octave/conv2.cc> // 正方行列のサイズを指定 #define DIM 2000 #define DIM2 21 int main( int argc, char **argv ) { printf( "start, \n" ); clock_t c = clock(); MArray2<double> a(DIM, DIM); MArray2<double> b(DIM2, DIM2); MArray<double> r(DIM, DIM); r = conv2(a, b, SHAPE_FULL); printf( "done, elapsed time = %f [sec]", ( (double)clock() - (double)c ) / CLOCKS_PER_SEC ); return 0; }

    libpointmatcher

    Iterative Closest Point (ICP) の機能を持ち, 点群 (point cloud) のアラインメントを行うことができる. point-to-point の ICP と,point-to-plane ICP の機能を持つ. point-to-point の ICP では,剛体変換だけでなく,スケールの変更にも対応している.

    関連項目K 近傍探索 (K nearest neighbour), ICP

    Windows での libpointmatcher のインストール

    ソースコードからビルドする

    https://github.com/CAOR-MINES-ParisTech/libpointmatcher/blob/master/doc/CompilationWindows.md の手順に従う.

    1. Windows では,前準備として次を行う.
    2. インストール

      Visual Studio の x64 Native Tools コマンドプロンプト管理者として実行する. 次のコマンドを実行する.

      エラーを回避するために「/bigobj」を設定.

      c:\libpointmatcher にインストールされる.

      boost-1_83」のところは,先ほど確認したインクルードディレクトリに一致させること.

      cd %LOCALAPPDATA%
      rmdir /s /q libpointmatcher
      git clone --recursive https://github.com/ethz-asl/libpointmatcher
      cd libpointmatcher
      rmdir /s /q build
      mkdir build
      cd build
      del CMakeCache.txt
      cmake -G "Visual Studio 17 2022" -T host=x64 ^
          -DCMAKE_BUILD_TYPE=Release ^
          -DCMAKE_INSTALL_PREFIX="c:/libpointmatcher" ^
          -DEIGEN_INCLUDE_DIR="c:/eigen/include/eigen3" ^
          -DBoost_USE_STATIC_LIBS=ON ^
          -DBOOST_ROOT="c:/boost/build" ^
          -DBoost_INCLUDE_DIR="c:/boost/build/include/boost-1_83" ^
          -DBoost_DIR="c:/boost/build" ^
          -Dlibnabo_DIR="%LOCALAPPDATA%/libnabo/build" ^
          -DCMAKE_BUILD_TYPE=RelWithDebInfo ^
          -DCMAKE_C_FLAGS="/DWIN32 /D_WINDOWS /W0 /utf-8 /bigobj" ^
          -DCMAKE_CXX_FLAGS="/DWIN32 /D_WINDOWS /GR /EHsc /W0 /utf-8 /bigobj" ^
      ..
      msbuild /m:2 libpointmatcher.sln -p:Configuration=Release
      
    Ubuntu での libpointmatcher のインストール

    ソースコードからビルドする

    公式ページの https://github.com/CAOR-MINES-ParisTech/libpointmatcher/blob/master/doc/CompilationWindows.md

    1. 前準備

      libnabo のインストール が必要.

    2. インストール

      Ubuntu でインストールを行うには,次のコマンドを実行.

      /usr/local/libpointmatcher にインストールされる.

      sudo apt -y update
      sudo apt -y install libboost-all-dev libeigen3-dev git cmake cmake-curses-gui cmake-gui
      
      cd /tmp
      sudo rm -rf libpointmatcher
      git clone --recursive https://github.com/ethz-asl/libpointmatcher
      sudo chown -R $USER libpointmatcher
      
      cd /tmp/libpointmatcher
      mkdir build
      cd build
      cmake \
          -DCMAKE_BUILD_TYPE=Release \
          -DCMAKE_INSTALL_PREFIX="/usr/local" \
          -DCMAKE_BUILD_TYPE=RelWithDebInfo \
      ..
      make
      sudo make install
      

    librosa

    librosa は, 音声,音楽の機能をもった Python のパッケージである. 主な機能としては,音源分離(music source separation),スペクトログラム, 音声ファイルの読み込み,テンポ(tempo)の推定がある.

    文献

    McFee, Brian, Colin Raffel, Dawen Liang, Daniel PW Ellis, Matt McVicar, Eric Battenberg, and Oriol Nieto. “librosa: Audio and music signal analysis in python.” In Proceedings of the 14th python in science conference, pp. 18-25. 2015.

    関連する外部ページ

    関連項目short-time Fourier transform, 音声, 音楽, sound, 音データ(sound data)

    Google Colaboratory で,パワースペクトログラムの表示(librosa を使用)

    次のプログラムは Google Colaboratory で動く(コードセルを作り,実行する).

    次のプログラムは,librosa に付属の音声データである trumpet について,パワースペクトログラムを表示する. 次のプログラムでは,横軸は時間,縦軸は線形スケール(linear scale)で表された周波数である パワースペクトログラムを表示する. stft は short-time Fourier transform を行う. そして,その振幅により色をプロットする.

    ここのプログラムのソースコードは, http://librosa.org/doc/main/auto_examples/plot_display.html#sphx-glr-auto-examples-plot-display-py のものを使用(ISC ライセンス).

    import numpy as np
    %matplotlib inline
    import matplotlib.pyplot as plt
    import warnings
    warnings.filterwarnings('ignore')   # Suppress Matplotlib warnings
    
    import librosa
    import librosa.display
    
    y, sr = librosa.load(librosa.ex('trumpet'))
    D = librosa.stft(y)  # STFT of y
    S_db = librosa.amplitude_to_db(np.abs(D), ref=np.max)
    plt.figure()
    librosa.display.specshow(S_db, x_axis='time', y_axis='linear', sr=sr)
    plt.colorbar()
    

    [image]
    Windows での librosa のインストール

    librosa のインストールと動作確認(音声処理)(Python を使用)(Windows 上): 別ページ »で説明している.

    Ubuntu での librosa のインストール

    Ubuntu での librosa のインストールは,次のようなコマンドで行う.

    sudo apt -y install ffmpeg
    sudo pip3 install -U numba librosa
    

    インストールするバージョンを指定する場合には,次のように操作する. 「==」のあとはバージョン指定であり,使用したいバージョンを指定する.

    sudo apt -y install ffmpeg
    sudo pip3 install -U numba==0.48.0 librosa==0.7.0 
    

    ソースコードを使用してインストールする場合には次のように操作する.

    sudo apt -y install ffmpeg
    sudo pip3 install git+https://github.com/librosa/librosa
    

    LLD

    LLD は,LLVMのサブプロジェクトである.

    LLD は,高速に動作するリンカーの機能を持つ.

    【関連する外部ページ】

    サイト内の関連ページ

    関連項目LLVM

    LLaMA (Large Language Model Meta AI)

    LLaMA (Large Language Model Meta AI) は,Meta によって開発された大規模言語モデル (large language model) である. LLaMA には,パラメーター数が7B、13B、33B、65B(1Bは10億)の4つのバージョンがある.

    文献

    Hugo Touvron, Thibaut Lavril, Gautier Izacard, Xavier Martinet, Marie-Anne Lachaux, Timothée Lacroix, Baptiste Rozière, Naman Goyal, Eric Hambro, Faisal Azhar, Aurelien Rodriguez, Armand Joulin, Edouard Grave, Guillaume Lample, LLaMA: Open and Efficient Foundation Language Models, https://arxiv.org/abs/2302.13971v1

    関連する外部ページ

    関連項目大規模言語モデル

    LLDB

    LLDB は,LLVMのサブプロジェクトである.

    LLDB は,デバッガの機能を持つ.

    【関連する外部ページ】

    サイト内の関連ページ

    関連項目LLVM

    LLVM

    LLVM には,コンパイラ,ツールチェーンに関するさまざまなサブプロジェクトとして, LVM Core, Clang, LLD, LLDB, libc++ などのサブプロジェクトがある.

    サイト内の関連ページ

    【関連する外部ページ】

    関連項目Clang, libc++, LLD, LLDB

    Windows での LLVM のインストール

    Windows での LLVM のインストールには,複数の方法がある.次のいずれかによりインストールできる.

    Ubuntu での LLVM のインストール

    Ubuntu でインストールを行うには,次のコマンドを実行.

    sudo apt -y update
    sudo apt -y install llvm
    

    locate コマンド

    Linux では,locate コマンドを用いてファイル検索を行うことができる.

    LoRA

    LoRA大規模言語モデルの学習の手法の1つである. LoRA は, 大規模言語モデルの学習において,ランク分解行列のペアを用いた学習を特徴とする. 学習可能なパラメータの数を削減を可能にしている. 具体的には,ランク分解行列のペアを用いることで,元の重み行列を低ランクな行列の積として近似することができ,これによって,元の重み行列の次元数を削減し,学習可能なパラメータ数を削減することができる.

    関連項目大規模言語モデル

    LPIPS (Learned Perceptual Image Patch Similarity)

    画像の類似尺度.Richard Zhang らにより 2018年に提案された.

    公式ページには,次の Python プログラムのソースコードが掲載されている.

    import lpips
    loss_fn_alex = lpips.LPIPS(net='alex') # best forward scores
    loss_fn_vgg = lpips.LPIPS(net='vgg') # closer to "traditional" perceptual loss, when used for optimization
    
    import torch
    img0 = torch.zeros(1,3,64,64) # image should be RGB, IMPORTANT: normalized to [-1,1]
    img1 = torch.zeros(1,3,64,64)
    d = loss_fn_alex(img0, img1)
    

    このソースコードの Google Colaboratory での実行結果は次の通りである.

    [image]

    関連項目SSIM

    LReLU (Leaky rectified linear unit)

    LReLU (Leaky rectified linear unit) は,次の関数である.

    f(x) = x (x>=0), alpha * x (x<0)

    LReLUは,活性化関数としてよく使用されるもののうちの1つである. 活性化関数は,ニューロンの入力の合計から,そのニューロンの活性度の値を決めるためのもの. (他には,ReLUシグモイド関数ステップ関数ソフトマックス関数などがある.

    KerasLReLU を使うときは,次のように書く.

    Keras のプログラム】

    m.add(LeakyReLU(alpha=0.01)
    

    LS3D-W データセット

    LS3D-W データセットは,3次元の顔ランドマーク (facial landmark)のデータセット.

    これは,AFLW,300VW,iBUG 300-W,FDDB の顔画像から生成されたデータセットである.

    利用には, https://www.adrianbulat.com/face-alignment での申請を必要とする.

    生成手順については,次の文献に記載されている

    Bulat, Adrian and Tzimiropoulos, Georgios, International Conference on Computer Vision, 2017, https://openaccess.thecvf.com/content_ICCV_2017/papers/Bulat_How_Far_Are_ICCV_2017_paper.pdf

    関連項目顔ランドマーク (facial landmark)

    LSTM (Long Short-Term Memory)

    LSTM 層を含むようなニューラルネットワークは,次の特徴を持つ

    関連項目Applications of Deep Neural Networks, ディープラーニング, リカレントニューラルネットワーク

    LSTM 層(Long Short-Term Memory layer)

    LSTM 層では,内部に「状態」を維持する. 状態は,ニューロンの動作のたびに変化するものである. (ふつうのニューロンでは,入力の値から出力が計算される.「状態」という考え方はない). LSTM 層のニューロンは,今の入力,1つ前の時間の入力,1つ前の時間での状態から出力を求める.

    LSUN (Large-scale Scene UNderstanding Challenge) データセット

    LSUN (Large-scale Scene UNderstanding Challenge) データセット は, ラベル付きの画像データセットである. 機械学習での画像分類や画像生成の学習や検証に利用できるデータセット.

    【関連情報】

    関連項目顔のデータベース

    LVIS データセット

    シーン解析(scene parsing)インスタンス・セグメンテーション (instance segmentation)のデータセット

    URL: https://www.lvisdataset.org/

    関連項目インスタンス・セグメンテーション (instance segmentation), オープンデータ, シーン解析(scene parsing)

    MagickWand

    MagickWand プログラムの実行

    1. MagickWand のサイトから wand.c を入手.

      このプログラムは,サムネイル画像を生成するプログラム.

    2. コンパイル

      以下のコマンドを実行.

      gcc `MagickWand-config --cflags --cppflags` -o wand.exe wand.c `MagickWand-config --ldflags --libs`
      

      または

      gcc -I/usr/include/ImageMagick -o wand.exe wand.c -L/usr/lib -L/usr/X11R6/lib -lMagickWand -lMagickCore -lfreetype -lz
      
    3. 実行

      wand.c は,画像ファイルから,サムネイル(縮小画像)を作るプログラム.

      次のコマンドにより実行.

      ./wand.exe <画像ファイル名> <サムネイル・ファイル名>
      

    関連項目ImageMagick

    mallorbc の whisper_mic

    Whisper でのマイクの使用を可能にする. 利用可能な言語モデルは,tiny,base,small,medium,large

    関連項目Whisper

    mAP id="

    機械学習による物体検出では, 「mAP」は,「mean average precision」の意味である.

    Mapillary Vistas Dataset (MVD)

    ストリート(街角)の25,000 枚の画像. インスタンスレベルのアノテーション, 124 のセマンティッククラス.

    次の URL で公開されているデータセット(オープンデータ)である.

    URL: https://www.mapillary.com/dataset/vistas

    関連項目セマンティック・セグメンテーション (semantic segmentation), インスタンス・セグメンテーション (instance segmentation)

    Mask R-CNN

    セグメンテーション,物体検出,キーポイント検出等に使用されるモデル.

    FPN (Feature Pyramid Network), ResNeXt101ResNeXt50ResNet101ResNet50 を使用.

    COCO データセットで学習済みのモデル,Jupyter ノートブック (Jupyter Notebook) のデモ demo.ipynb が公開されている.

    関連項目Detectron2, MMDetection, PANet (Path Aggregation Network), 物体検出, セグメンテーション (segmentation), keypoint detection

    付属の Jupyter ノートブック (Jupyter Notebook) のデモ

    Jupyter ノートブック (Jupyter Notebook) のデモが付属している.主なものは次の通り. 動作させるには,Mask R-CNN のインストールが終わっていること(下に記載). 学習: train_shapes.ipynb 仕組み: inspect_model.ipynb 重みの視覚化: inspect_weights.ipynb

    Windows での Mask R-CNN のインストール
    1. Git のインストール: 別項目で説明している.

      Git の公式ページ: https://git-scm.com/

    2. コマンドプロンプトを管理者として開き次のコマンドを実行する.
      cd %LOCALAPPDATA%
      rmdir /s /q Mask_RCNN
      git clone --recursive https://github.com/matterport/Mask_RCNN
      cd Mask_RCNN
      python -m pip install -U -r requirements.txt
      python setup.py install
      
    Ubuntu での Mask R-CNN のインストール
    1. Ubuntu でインストールを行うには,次のコマンドを実行.
      sudo apt -y update
      sudo apt -y install git
      
      cd /usr/local
      sudo rm -rf Mask_RCNN
      sudo git clone --recursive https://github.com/matterport/Mask_RCNN
      sudo chown -R $USER Mask_RCNN
      
      # システム Python の環境とは別の Python の仮想環境システム Python を使用)を作成
      sudo apt -y update
      sudo apt -y install python3-venv
      python3 -m venv ~/a
      source ~/a/bin/activate
      
      cd /usr/local/Mask_RCNN
      sudo pip3 install -U -r requirements.txt
      sudo pip3 list
      python setup.py install
      

    matplotlib

    matplotlib は,オープンソースの Python のプロットライブラリ.

    matplotlib を用いた散布図の描画は,別ページ »で説明している.

    matplotlib を用いたグラフ描画の例は次の通り.

    import numpy as np
    %matplotlib inline
    import matplotlib.pyplot as plt
    import warnings
    warnings.filterwarnings('ignore')   # Suppress Matplotlib warnings
    
    x = np.linspace(0, 6, 100)
    plt.style.use('ggplot')
    plt.plot(x, np.sin(x))
    

    [image]

    matplotlib を用いて,OpenCV のカラー画像を表示する例は次の通り.

    import cv2
    %matplotlib inline
    import matplotlib.pyplot as plt
    import warnings
    warnings.filterwarnings('ignore')   # Suppress Matplotlib warnings
    
    bgr = cv2.imread("126.png")
    plt.style.use('default')
    plt.imshow(cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB))
    plt.show()
    

    [image]

    普通に Matplotlib を用いてOpenCV 画像の表示を表示すると,小さく表示される.

    「plt.style.use('default')」の実行により,Matplotlib での OpenCV 画像の表示が大きくなる.

    [image]

    サイト内の関連ページMatplotlib(Python のまとめページ内)

    関連項目display

    Windows での matplotlib のインストール

    Windows での matplotlib, seaborn のインストールは, コマンドプロンプトを管理者として開き そのコマンドプロンプトで,次のコマンドを実行することで行う.

    python -m pip install -U matplotlib seaborn
    
    Ubuntu での matplotlib のインストール

    Ubuntu での matplotlib, seaborn のインストールは, 次のコマンドを実行することで行う.

    sudo apt -y update
    sudo apt -y install python3-matplotlib python3-seaborn
    

    Max-Margin 物体検出 (Max-Margin Object Detection)

    画像からの物体検出 のための学習法である. 当時の,従来の,単純な物体検出 法よりも高速であり, 他の種々の物体検出 法よりも精度が劣らないとされている. サブサンプリングを行わずに,サブウインドウ(画像分類のために使用されるもの)の全体での最適化を行うことを特徴としている.

    関連項目物体検出

    MeCab

    MeCab は,形態素解析の機能を持ったソフトウェア.

    Windows での MeCab のインストール

    公式ページからダウンロードしてインストールする.その詳細は,別ページ »で説明している.

    Merkaartor

    Merkaartor は, OpenStreetMap の編集ソフトウェア. OpenStreetMap,ESRI Shape データ,Bing,Spatialite を扱う機能がある. Windows 版,Linux 版,Mac OS X 版もある.ソースコードは公開されている.

    サイト内の関連ページ

    【関連する外部ページ】

    Merkaartor の公式ページ: http://merkaartor.be

    GitHub のページ: https://github.com/openstreetmap/merkaartor/

    MeshLab

    MeshLab は, 3次元データ(3次元点群データや,メッシュデータ)について表示, 簡易編集, データの間引き, 形式変換, 張り合わせ, 分割, 解析などが行えるソフトウェア

    URL: http://meshlab.sourceforge.net/

    関連項目メッシュ簡略化 (Mesh Simplification) , メッシュ平滑化 (Mesh Smoothing)

    Windows での MeshLab のインストール

    Windows での MeshLab のインストールには,複数の方法がある.次のいずれかによりインストールできる.

    Ubuntu での MeshLab のインストール

    Ubuntu でのインストール: 別ページ »で説明している.

    Meshroom

    Meshroomフォトグラメトリ のソフトウェアである. Structure from Motion を,GUI を用いて簡単に行うことができる. 動作画面の一部は次の通りである. カメラの撮影位置と,オブジェクトの3次元形状が表示されている.

    [image]

    meshroom の URL (ここから Meshroom をダウンロード可能): https://alicevision.org/

    関連項目3次元再構成 (3D reconstruction), OpenMVG, OpenMMLab, Structure from Motion (SfM)

    Metis

    Windows での Metis のインストール

    Windows での Metis のインストール: 別ページ »で説明している. Ubuntu での Metis のインストール: 別ページ »で説明している.

    SuiteSparse 5.4.0,Metis 5.1.0 の非公式ビルド: suitesparse.zip

    私がビルドしたもの,非公式,無保証, https://github.com/jlblancoc/suitesparse-metis-for-windows/releases で公開されているソースコードを改変せずにビルドした. Windows 10, Visual Build Tools for Visual Studio 2022 を用いてビルドした. BSD ライセンスによる.

    zip ファイルは C:\ 直下で展開し,C:\suitesparse での利用を想定.

    MhLiao の DB

    テキスト検知 (text detection), テキスト認識 (text recognition) の機能を持つ.

    文献

    Liao, Minghui and Wan, Zhaoyi and Yao, Cong and Chen, Kai and Bai, Xiang, Real-time Scene Text Detection with Differentiable Binarization, Proc. AAAI, 2020.

    関連項目】 テキスト検知 (text detection), テキスト認識 (text recognition)

    Google Colaboratory でのインストール

    次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する).

    %cd /content
    !rm -rf DB
    !git clone https://github.com/MhLiao/DB.git
    %cd DB
    !pip3 install -r requirement.txt
    %cd assets/ops/dcn/
    !python3 setup.py build_ext --inplace
    

    MIT Scene Parsing Benchmark

    ADE20K データセット から派生した, シーン解析(scene parsing) のデータと, オブジェクトのパーツ (object parts) のセグメンテーションのデータ.

    次の URL で公開されているデータセット(オープンデータ)である.

    http://sceneparsing.csail.mit.edu/

    【関連情報】

    関連項目ADE20K データセット, CASILVision, セマンティック・セグメンテーション (semantic segmentation), シーン解析(scene parsing)インスタンス・セグメンテーション (instance segmentation)

    Windows でのダウンロードと展開

    c:\date 下にダウンロード,展開する.

    Windows では,コマンドプロン プトを管理者として実行し, 次のコマンドを実行する.

    mkdir c:\data
    cd c:\data
    curl -O http://data.csail.mit.edu/places/ADEchallenge/ADEChallengeData2016.zip
    rmdir /s /q ADEChallengeData2016
    powershell -command "Expand-Archive -DestinationPath . -Path ADEChallengeData2016.zip"
    

    ファイルの配置は次のようになる.

    ADEChallengeData2016/
      annotations/
      images/
      objectInfo150.txt
      sceneCategories.txt
    

    MiVOS

    MiVOSは、対話型のビデオオブジェクトセグメンテーション(interactive video object segmentation)の新しい手法として提案されている。このシステムはユーザーのインタラクションを取り入れつつ、特定のフレームでのセグメンテーション結果を他のフレームに効果的に伝搬させることができる。インタラクションと伝搬を分離するため、MiVOSはInteraction-to-Mask、Propagation、そしてDifference-Aware Fusionの3つの主要モジュールを採用している。2021年発表。

    文献

    Rethinking Space-Time Networks with Improved Memory Coverage for Efficient Video Object Segmentation, Cheng, Ho Kei and Tai, Yu-Wing and Tang, Chi-Keung, NeurIPS, also arXiv:2106.05210v2, 2021.

    https://arxiv.org/pdf/2106.05210v2.pdf

    Modular Interactive Video Object Segmentation: Interaction-to-Mask, Propagation and Difference-Aware Fusion, Cheng, Ho Kei and Tai, Yu-Wing and Tang, Chi-Keung, CVPR, also, arXiv:2103.07941v3, 2021.

    https://arxiv.org/pdf/2103.07941v3.pdf

    サイト内の関連ページ

    サイト内の関連ページ

    関連する外部ページ

    mixamo

    キャラクタと動きのアセットを公開しているサイト.fbx形式でダウンロードできる.

    URL: https://www.mixamo.com

    【関連用語】 3次元コンピュータグラフィックス, human pose, human motion

    MMAction2

    MMAction2 は, OpenMMLab の構成物で,動作認識 (action recognition)の機能を提供する.

    関連項目AVA, MMCV, OpenMMLab, PoseC3D, Spatio-Temporal Action Recognition, Temporal Segment Networks (TSN), スケルトンベースの動作認識 (skelton-based action recognition), 動作認識 (action recognition)

    Google Colaboratory で MMAction2 による動作認識 (action recognition),スケルトンベースの動作認識,Spatio-Temporal Action Recognition の実行

    次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する).

    1. Google Colaboratory で,ランタイムのタイプを GPU に設定する.
    2. MMCV 1.7.1 のインストール

      インストール手順は, https://mmcv.readthedocs.io/en/latest/get_started/installation.html に記載の手順による

      MMTracking が MMVC 1.6.2 に依存している (2023年4月時点). MMTracking の利用を想定して MMCV 1.6.2 をインストールする.

      !python -c "import torch; print(torch.__version__)"
      !apt remove python3-pycocotools
      !pip uninstall -y pycocotools
      !pip install mmpycocotools
      !apt install -y python3-terminaltables
      !apt install -y python3-opencv
      !pip install mmcv-full==1.6.2
      !python3 -c "from mmcv.ops import get_compiling_cuda_version, get_compiler_version; print(get_compiling_cuda_version(), get_compiler_version())"
      
    3. MIM, MMClassification, MMSegmentation, MMDetection, MMTracking, MMPose のインストール.MMPose のインストール後は numpy, scipy の更新も行う.

      https://github.com/open-mmlab/mmpose/blob/master/docs/en/install.md#install-mmposeに記載の手順による.

      MMCV 1.6.2 をインストールしたので,MMDetection は 2系列になる(3系列は動かない)(2023年4月時点).

      !python -m pip install -U openmim opencv-python
      !python -m pip install -U mmcv-full==1.6.2
      !python -m pip install -U git+https://github.com/open-mmlab/mmclassification.git
      !python -m pip install -U mmdet==2.28.2
      !python -m pip install -U git+https://github.com/open-mmlab/mmsegmentation.git
      !python -m pip install -U git+https://github.com/open-mmlab/mmtracking.git
      !python -m pip install -U git+https://github.com/open-mmlab/mmpose.git
      !apt -y install python3-numpy
      !apt -y install python3-scipy
      !python -c "import mmcls; print(mmcls.__version__)"
      !python -c "import mmdet; print(mmdet.__version__)"
      !python -c "import mmseg; print(mmseg.__version__)"
      !python -c "import mmtrack; print(mmtrack.__version__)"
      !python -c "import mmpose; print(mmpose.__version__)"
      
      !pip3 install git+https://github.com/votchallenge/toolkit.git
      

      [image]
    4. MMAction2 のインストール
      !mim install mmaction2 -f https://github.com/open-mmlab/mmaction2.git
      !pip3 show mmaction2
      
      %cd /content
      !rm -rf mmaction2
      !git clone https://github.com/open-mmlab/mmaction2.git
      %cd mmaction2
      !pip3 install -r requirements/optional.txt
      

      [image]
    5. MMAction2 の学習済みモデルのダウンロード

      Temporal Segment Networks (TSN), ResNet50, ImageNet, Kinetics-400 のものをダウンロード.

      MMAction2 の Temporal Segment Networks (TSN) の説明ページ: https://github.com/open-mmlab/mmaction2/blob/master/configs/recognition/tsn/README.md

      !curl -O https://download.openmmlab.com/mmaction/recognition/tsn/tsn_r50_1x1x3_100e_kinetics400_rgb/tsn_r50_1x1x3_100e_kinetics400_rgb_20200614-e508be42.pth
      !mkdir checkpoints
      !mv tsn_r50_1x1x3_100e_kinetics400_rgb_20200614-e508be42.pth checkpoints
      

      [image]
    6. Temporal Segment Networks (TSN) による動作認識 (action recognition)(MMAction2 を使用)

      公式のチュートリアル: https://github.com/open-mmlab/mmaction2/blob/master/demo/mmaction2_tutorial.ipynb に記載のプログラムを使用

      このプログラムは,Temporal Segment Networks (TSN), ResNet50, ImageNet, Kinetics-400 を使用

      import torch
      from mmaction.apis import inference_recognizer, init_recognizer
      
      # Choose to use a config and initialize the recognizer
      config = 'configs/recognition/tsn/tsn_r50_video_inference_1x1x3_100e_kinetics400_rgb.py'
      # Setup a checkpoint file to load
      checkpoint = 'checkpoints/tsn_r50_1x1x3_100e_kinetics400_rgb_20200614-e508be42.pth'
      
      # Initialize the recognizer
      device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
      model = init_recognizer(config, checkpoint, device=device)
      
      # Use the recognizer to do inference
      video = 'demo/demo.mp4'
      label = 'tools/data/kinetics/label_map_k400.txt'
      results = inference_recognizer(model, video)
      
      labels = open(label).readlines()
      labels = [x.strip() for x in labels]
      results = [(labels[k[0]], k[1]) for k in results]
      
      # Let's show the results
      for result in results:
          print(f'{result[0]}: ', result[1])
      

      [image]
    7. MMAction2 の学習済みモデルのダウンロード

      PoseC3D, SlowOnly-R50, NTU120_XSub のものをダウンロード.

      MMAction2 の PoseC3D の説明ページ: https://github.com/open-mmlab/mmaction2/blob/master/configs/skeleton/posec3d/README.md

      !curl -O https://download.openmmlab.com/mmaction/skeleton/posec3d/slowonly_r50_u48_240e_ntu120_xsub_keypoint/slowonly_r50_u48_240e_ntu120_xsub_keypoint-6736b03f.pth
      !mkdir checkpoints
      !mv slowonly_r50_u48_240e_ntu120_xsub_keypoint-6736b03f.pth checkpoints
      

      [image]
    8. PoseC3D によるスケルトンベースの動作認識 (skelton-based action recognition)(MMAction2 を使用)

      MMAction2 の公式のデモのドキュメント: https://github.com/open-mmlab/mmaction2/blob/master/demo/README.md#skeleton-based-action-recognition-demo に記載のプログラムを使用

      このプログラムは, 人物検出(human detection) に Faster RCNN を使用. 姿勢推定(pose estimation) に HRNetw32 を使用. スケルトンベースの動作認識 (skelton-based action recognition)に,PoseC3D, SlowOnly-R50, NTU120_XSub を使用.

      !python3 demo/demo_skeleton.py demo/ntu_sample.avi demo/skeleton_demo.mp4 \
          --config configs/skeleton/posec3d/slowonly_r50_u48_240e_ntu120_xsub_keypoint.py \
          --checkpoint checkpoints/slowonly_r50_u48_240e_ntu120_xsub_keypoint-6736b03f.pth \
          --det-config demo/faster_rcnn_r50_fpn_2x_coco.py \
          --det-checkpoint http://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_2x_coco/faster_rcnn_r50_fpn_2x_coco_bbox_mAP-0.384_20200504_210434-a5d8aa15.pth \
          --det-score-thr 0.9 \
          --pose-config demo/hrnet_w32_coco_256x192.py \
          --pose-checkpoint https://download.openmmlab.com/mmpose/top_down/hrnet/hrnet_w32_coco_256x192-c78dce93_20200708.pth \
          --label-map tools/data/skeleton/label_map_ntu120.txt
      

      [image]

      mmaction/demo/skeleton_demo.mp4 を確認

      [image]
    9. MMAction2 の学習済みモデルのダウンロード

      AVA, OmniSource, ResNet101 のものをダウンロード.

      MMAction2 の AVA の説明ページ: https://github.com/open-mmlab/mmaction2/blob/master/configs/detection/ava/README.md

      !curl -O https://download.openmmlab.com/mmaction/detection/ava/slowonly_omnisource_pretrained_r101_8x8x1_20e_ava_rgb/slowonly_omnisource_pretrained_r101_8x8x1_20e_ava_rgb_20201217-16378594.pth
      !mkdir checkpoints
      !mv slowonly_omnisource_pretrained_r101_8x8x1_20e_ava_rgb_20201217-16378594.pth checkpoints
      

      [image]
    10. AVA による Spatio-Temporal Action Recognition (MMAction2 を使用)

      MMAction2 の公式のデモのドキュメント: https://github.com/open-mmlab/mmaction2/blob/master/demo/README.md#skeleton-based-action-recognition-demo に記載のプログラムを使用

      このプログラムは, 人物検出(human detection) に Faster RCNN を使用. 動作認識 (action recognition)に,SlowOnly-8x8-R101 を使用. 8フレームごとに予測を行い,4フレームごとに1フレームを出力する.

      !python3 demo/demo_spatiotemporal_det.py --video demo/demo.mp4 \
          --config configs/detection/ava/slowonly_omnisource_pretrained_r101_8x8x1_20e_ava_rgb.py \
          --checkpoint checkpoints/slowonly_omnisource_pretrained_r101_8x8x1_20e_ava_rgb_20201217-16378594.pth \
          --det-config demo/faster_rcnn_r50_fpn_2x_coco.py \
          --det-checkpoint http://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_2x_coco/faster_rcnn_r50_fpn_2x_coco_bbox_mAP-0.384_20200504_210434-a5d8aa15.pth \
          --det-score-thr 0.9 \
          --action-score-thr 0.5 \
          --label-map tools/data/ava/label_map.txt \
          --predict-stepsize 8 \
          --output-stepsize 4 \
          --output-fps 6
      

      [image]

      mmaction/demo/stdet_demo.mp4 を確認

      [image]

    MMPretrain (MMClassification)

    MMPretrain (MMClassification) は, OpenMMLab の構成物で, 画像分類のツールボックスとベンチマークの機能を提供する.

    文献

    MMClassification Contributors, OpenMMLab's Image Classification Toolbox and Benchmark, https://github.com/open-mmlab/mmclassification, 2020.

    サイト内の関連ページ

    画像分類の実行(MMPretrain,PyTorch,Python を使用)(Windows 上)

    関連する外部ページ

    関連項目OpenMMLab, MMCV, MMFewShot

    Google Colaboratory で,MMClassification による画像分類の実行

    次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する).

    1. MIM のインストール
      !pip3 install git+https://github.com/open-mmlab/mim.git
      
    2. MMCV, MMClassification のインストール.

      https://mmclassification.readthedocs.io/en/latest/install.html の記載の手順による

      %cd /content
      !rm -rf mmclassification
      !git clone https://github.com/open-mmlab/mmclassification.git
      %cd mmclassification
      !git checkout dev
      !mim install -e .
      !pip3 show mmcls
      

      [image]
    3. MMClassification の学習済みモデルのダウンロード

      ResNet50, ImageNet-1k のものをダウンロード.

      MMClassification の ResNet の説明ページ: https://github.com/open-mmlab/mmclassification/tree/master/configs/resnet

      !curl -O https://download.openmmlab.com/mmclassification/v0/resnet/resnet50_8xb32_in1k_20210831-ea4938fc.pth
      !mkdir checkpoints
      !mv resnet50_8xb32_in1k_20210831-ea4938fc.pth checkpoints
      

      [image]
    4. ResNet50による画像分類の実行(MMClassification を使用)

      このプログラムは,ResNet50, ImageNet-1k を使用.

      import torch
      from mmcls.apis import inference_model, init_model, show_result_pyplot
      
      fimg = 'demo/demo.JPEG'
      fconfig = 'configs/resnet/resnet50_8xb32_in1k.py'
      fcheckpoint = 'checkpoints/resnet50_8xb32_in1k_20210831-ea4938fc.pth'
      
      device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
      model = init_model(fconfig, fcheckpoint, device=device)
      result = inference_model(model, fimg)
      print(result)
      show_result_pyplot(model, fimg, result)
      

      [image]
    Windows で,MMClassification のインストールと,画像分類の実行

    MMClassification のインストールと動作確認(画像分類)(PyTorch,Python を使用): 別ページ »で説明している.

    MMCV

    MMCV は, OpenMMLab の構成物で,基礎的な機能を提供する.

    文献

    MMCV Contributors, MMCV: OpenMMLab Computer Vision Foundation, https://github.com/open-mmlab/mmcv, 2018.

    関連する外部ページ

    関連項目OpenMMLab, MMAction2, MMClassification MMDetection, MMFewShot, MMFlow, MMGen, MMPose, MMSegmentation, MMSegmentation3D, MMSelfSup, MMTracking

    Google Colaboratory での MMCV のインストール

    次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する).

    1. Google Colaboratory で,ランタイムのタイプを GPU に設定する.
    2. まず,PyTorch のバージョンを確認

      PyTorch は,ディープラーニングのフレームワークの 機能を持つ Pythonのパッケージ

      次のプログラム実行により,PyTorch のバージョンが「1.10.0+cu111」のように表示される.

      import torch
      print(torch.__version__)
      
    3. NVIDIA CUDA ツールキット のバージョンを確認 (2)NVIDIA CUDA ツールキット のバージョンを確認 NVIDIA CUDA ツールキット は,NVIDIA社が提供している GPU 用のツールキットである.GPU を用いた演算のプログラム作成や動作のための各種機能を備えている.ディープラーニングでも利用されている.

      次のプログラム実行により,NVIDIA CUDA ツールキットのバージョンが「cu111」のように表示される.

      import torch
      CUDA_VERSION = torch.__version__.split("+")[-1]
      print(CUDA_VERSION)
      

      [image]
    4. PyTorch のバージョンを確認
      import torch
      TORCH_VERSION = ".".join(torch.__version__.split(".")[:2])
      print(TORCH_VERSION)
      

      [image]
    5. MMCV 1.7.1 のインストール

      インストール手順は, https://mmcv.readthedocs.io/en/latest/get_started/installation.html に記載の手順による

      MMTracking が MMVC 1.6.2 に依存している (2023年4月時点). MMTracking の利用を想定して MMCV 1.6.2 をインストールする.

      !python -c "import torch; print(torch.__version__)"
      !apt remove python3-pycocotools
      !pip uninstall -y pycocotools
      !pip install mmpycocotools
      !apt install -y python3-terminaltables
      !apt install -y python3-opencv
      !pip install mmcv-full==1.6.2
      !python3 -c "from mmcv.ops import get_compiling_cuda_version, get_compiler_version; print(get_compiling_cuda_version(), get_compiler_version())"
      
    Windows での MMCV のインストール

    MMCV のインストールと動作確認(画像表示など)(PyTorch,Python を使用): 別ページ »で説明している.

    Ubuntu での MMCV のインストール

    MMCV 1.7.1 のインストール

    インストール手順は, https://mmcv.readthedocs.io/en/latest/get_started/installation.html に記載の手順による

    MMTracking が MMVC 1.6.2 に依存している (2023年4月時点). MMTracking の利用を想定して MMCV 1.6.2 をインストールする.

    sudo apt install -y python3-terminaltables
    sudo apt install -y python3-opencv
    python3 -m pip uninstall mmcv mmcv-full
    python3 -m pip install mmcv==1.6.2
    

    MMDetection

    MMDetection は, OpenMMLab の構成物で,物体検出インスタンス・セグメンテーション (instance segmentation), パノプティック・セグメンテーション (panoptic segmentation) の機能を提供する.

    文献

    Chen, Kai and Wang, Jiaqi and Pang, Jiangmiao and Cao, Yuhang and Xiong, Yu and Li, Xiaoxiao and Sun, Shuyang and Feng, Wansen and Liu, Ziwei and Xu, Jiarui and Zhang, Zheng and Cheng, Dazhi and Zhu, Chenchen and Cheng, Tianheng and Zhao, Qijie and Li, Buyu and Lu, Xin and Zhu, Rui and Wu, Yue and Dai, Jifeng and Wang, Jingdong and Shi, Jianping and Ouyang, Wanli and Loy, Chen Change and Lin, Dahua, MMDetection: Open MMLab Detection Toolbox and Benchmark, arXiv:1906.07155, 2019.

    サイト内の関連ページ

    物体検出の実行(MMDetection,PyTorch,Python を使用)(Windows 上)

    関連する外部ページ

    関連項目DETR, Deformable DETR, Mask R-CNN, MMCV, MMFewShot, MMPose, MMSegmentation, MMSegmentation3D, MMSelfSup, MMTracking, OpenMMLab, RetinaNet, Seesaw Loss, SSD, YOLOv3, YOLOv4, YOLOX, インスタンス・セグメンテーション (instance segmentation), パノプティック・セグメンテーション (panoptic segmentation) 物体検出

    Google Colaboratory で,MMDetection による物体検出とセグメンテーションの実行

    次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する).

    1. MIM のインストール
      !pip3 install git+https://github.com/open-mmlab/mim.git
      
    2. MMCV, MMDetection のインストール.

      https://github.com/open-mmlab/mmdetection/blob/master/docs/en/get_started.md に記載の手順による

      
      !mim install mmdet
      !pip3 show mmdet
      

      [image]
    3. MMDetection のソースコード等のダウンロード

      あとで使用する

      %cd /content
      !rm -rf mmdetection
      !git clone https://github.com/open-mmlab/mmdetection.git
      %cd mmdetection
      

      [image]
    4. MMDetection の学習済みモデルのダウンロード

      Mask R-CNN, FPN (Feature Pyramid Network), Lr schd = 3x のものをダウンロード.

      MMDetectionMask R-CNN の説明ページ: https://github.com/open-mmlab/mmdetection/tree/master/configs/mask_rcnn

      !curl -O https://download.openmmlab.com/mmdetection/v2.0/mask_rcnn/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco_bbox_mAP-0.408__segm_mAP-0.37_20200504_163245-42aa3d00.pth
      !mkdir checkpoints
      !mv mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco_bbox_mAP-0.408__segm_mAP-0.37_20200504_163245-42aa3d00.pth checkpoints
      

      [image]
    5. Mask R-CNN による 物体検出とセグメンテーションの実行(MMDetectionを使用)

      MMDetection の訓練,検証,推論の公式チュートリアル: https://github.com/open-mmlab/mmdetection/blob/master/demo/MMDet_Tutorial.ipynb に記載のプログラムを使用

      このプログラムは,Mask R-CNN, FPN (Feature Pyramid Network), Lr schd = 3x を使用.

      import torch
      from mmdet.apis import inference_detector, init_detector, show_result_pyplot
      
      fimg = 'demo/demo.jpg'
      fconfig = 'configs/mask_rcnn/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco.py'
      fcheckpoint = 'checkpoints/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco_bbox_mAP-0.408__segm_mAP-0.37_20200504_163245-42aa3d00.pth'
      
      device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
      model = init_detector(fconfig, fcheckpoint, device=device)
      result = inference_detector(model, fimg)
      print(result)
      show_result_pyplot(model, fimg, result, score_thr=0.3) 
      

      [image]
    Windows で,MMDetection のインストールと,物体検出の実行

    MMDetection のインストールと動作確認(物体検出)(PyTorch,Python を使用): 別ページ »で説明している.

    Ubuntu での MMDetection のインストール
    1. インストール

      「git checkout v0.14.0」は,バージョン 2.14.0 を指定している. これは,https://mmdetection3d.readthedocs.io/en/latest/get_started.html での2021/08 時点の説明による.将来はバージョン番号が変わる可能性があり,このページを確認してから,インストールを行うこと.

      Ubuntu でインストールを行うには,次のコマンドを実行.

      sudo apt -y update
      sudo apt -y install git
      
      cd /usr/local
      sudo git clone https://github.com/open-mmlab/mmdetection.git
      sudo chown -R $USER mmdetection
      cd mmdetection
      git checkout v2.14.0
      sudo pip3 install -r requirements\build.txt
      python3 setup.py develop
      pip3 install instaboostfast
      # for panoptic segmentation
      pip3 install git+https://github.com/cocodataset/panopticapi.git
      # for LVIS dataset
      pip3  install git+https://github.com/lvis-dataset/lvis-api.git
      
    2. 動作確認

      Ubuntu の場合は, mmcv のドキュメント: https://mmcv.readthedocs.io/en/latest/ の手順がそのまま使えそうである.

    MMEditing

    MMEditing は, OpenMMLab の構成物で, イメージ・インペインティング(image inpainting),画像のノイズ除去 (画像のノイズ除去 (image restoration)), イメージ・マッティング (image matting), 超解像 (super resolution), 画像生成の機能を持つ.

    関連項目MMCV, OpenMMLab, SRCNN, ESRGAN, EDvR, BasicVSR image inpainting, 画像のノイズ除去 (image restoration), イメージ・マッティング (image matting), 超解像 (super resolution), generation

    Google Colaboratory で MMEditing の SRCNN, ESRGAN, EDVR, BasicVSR による超解像 (super resolution) の実行

    次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する).

    1. Google Colaboratory で,ランタイムのタイプを GPU に設定する.
    2. まず,PyTorch のバージョンを確認

      PyTorch は,ディープラーニングのフレームワークの 機能を持つ Pythonのパッケージ

      次のプログラム実行により,PyTorch のバージョンが「1.10.0+cu111」のように表示される.

      import torch
      print(torch.__version__)
      
    3. NVIDIA CUDA ツールキット のバージョンを確認 (2)**NVIDIA CUDA ツールキット のバージョン**を確認 NVIDIA CUDA ツールキット は,NVIDIA社が提供している GPU 用のツールキットである.GPU を用いた演算のプログラム作成や動作のための各種機能を備えている.ディープラーニングでも利用されている.

      次のプログラム実行により,NVIDIA CUDA ツールキットのバージョンが「cu111」のように表示される.

      import torch
      CUDA_VERSION = torch.__version__.split("+")[-1]
      print(CUDA_VERSION)
      

      [image]
    4. PyTorch のバージョンを確認
      import torch
      TORCH_VERSION = ".".join(torch.__version__.split(".")[:2])
      print(TORCH_VERSION)
      

      [image]
    5. MMCV 1.7.1 のインストール

      インストール手順は, https://mmcv.readthedocs.io/en/latest/get_started/installation.html に記載の手順による

      MMTracking が MMVC 1.6.2 に依存している (2023年4月時点). MMTracking の利用を想定して MMCV 1.6.2 をインストールする.

      !python -c "import torch; print(torch.__version__)"
      !apt remove python3-pycocotools
      !pip uninstall -y pycocotools
      !pip install mmpycocotools
      !apt install -y python3-terminaltables
      !apt install -y python3-opencv
      !pip install mmcv-full==1.6.2
      !python3 -c "from mmcv.ops import get_compiling_cuda_version, get_compiler_version; print(get_compiling_cuda_version(), get_compiler_version())"
      
    6. MIM, MMEditing のインストール
      !python -m pip install -U openmim opencv-python
      
      %cd /content
      !rm -rf mmediting
      !git clone https://github.com/open-mmlab/mmediting.git
      %cd mmediting
      !pip3 install -r requirements/build.txt
      !pip3 install .
      

      [image]
    7. MMEditing のデモファイルのダウンロード
      %cd /content/mmediting
      !curl -O https://download.openmmlab.com/mmediting/demo_files.zip 
      !rm -rf demo_files
      !unzip demo_files 
      

      [image]
    8. 超解像 (super resolution) の実行
      • SRCNN による画像の超解像 (super resolution) の実行

        学習済みモデルを使用.

        MMEditing の SRCNN の説明ページ: https://github.com/open-mmlab/mmediting/blob/master/configs/restorers/srcnn/README.md

        コマンドの説明: https://github.com/open-mmlab/mmediting/blob/master/docs/en/getting_started.md

        !python3 demo/restoration_demo.py ./configs/restorers/srcnn/srcnn_x4k915_g1_1000k_div2k.py https://download.openmmlab.com/mmediting/restorers/srcnn/srcnn_x4k915_1x16_1000k_div2k_20200608-4186f232.pth ./demo_files/lq_images/bird.png ./outputs/bird_SRCNN.png
        
        from PIL import Image
        Image.open('./demo_files/lq_images/bird.png').show()
        Image.open('./outputs/bird_SRCNN.png').show()
        

        [image]
      • ESRGAN による画像の超解像 (super resolution) の実行

        学習済みモデルを使用.

        MMEditing の ESRGAN の説明ページ: https://github.com/open-mmlab/mmediting/blob/master/configs/restorers/esrgan/README.md

        コマンドの説明: https://github.com/open-mmlab/mmediting/blob/master/docs/en/getting_started.md

        !python3 demo/restoration_demo.py ./configs/restorers/esrgan/esrgan_x4c64b23g32_g1_400k_div2k.py https://download.openmmlab.com/mmediting/restorers/esrgan/esrgan_x4c64b23g32_1x16_400k_div2k_20200508-f8ccaf3b.pth ./demo_files/lq_images/bird.png ./outputs/bird_ESRGAN.png
        
        from PIL import Image
        Image.open('./demo_files/lq_images/bird.png').show()
        Image.open('./outputs/bird_ESRGAN.png').show()
        

        [image]
      • EDVR による連続画像の超解像 (super resolution) の実行

        学習済みモデルを使用.

        MMEditing の EDVR の説明ページ: https://github.com/open-mmlab/mmediting/blob/master/configs/restorers/edvr/README.md

        コマンドの説明: https://github.com/open-mmlab/mmediting/blob/master/docs/en/getting_started.md

        !python3 demo/restoration_video_demo.py ./configs/restorers/edvr/edvrm_wotsa_x4_g8_600k_reds.py https://download.openmmlab.com/mmediting/restorers/edvr/edvrm_wotsa_x4_8x4_600k_reds_20200522-0570e567.pth demo_files/lq_sequences/city/ ./outputs/city_EDVR --window_size=5
        
        from PIL import Image
        Image.open('./demo_files/lq_sequences/city/00000000.png').show()
        Image.open('./outputs/city_EDVR/00000000.png').show()
        Image.open('./demo_files/lq_sequences/city/00000001.png').show()
        Image.open('./outputs/city_EDVR/00000001.png').show()
        Image.open('./demo_files/lq_sequences/city/00000002.png').show()
        Image.open('./outputs/city_EDVR/00000002.png').show()
        Image.open('./demo_files/lq_sequences/city/00000003.png').show()
        Image.open('./outputs/city_EDVR/00000003.png').show()
        Image.open('./demo_files/lq_sequences/city/00000004.png').show()
        Image.open('./outputs/city_EDVR/00000004.png').show()
        Image.open('./demo_files/lq_sequences/city/00000005.png').show()
        Image.open('./outputs/city_EDVR/00000005.png').show()
        

        [image]

        [image]
      • BasicVSR (Recurrent framework) の実行

        学習済みモデルを使用.

        MMEditing の EDVR の説明ページ: https://github.com/open-mmlab/mmediting/blob/master/configs/restorers/edvr/README.md

        コマンドの説明: https://github.com/open-mmlab/mmediting/blob/master/docs/en/getting_started.md

        !python3 demo/restoration_video_demo.py ./configs/restorers/basicvsr/basicvsr_reds4.py https://download.openmmlab.com/mmediting/restorers/basicvsr/basicvsr_reds4_20120409-0e599677.pth demo_files/lq_sequences/city/ ./outputs/city_BasicVSR
        
        from PIL import Image
        Image.open('./demo_files/lq_sequences/city/00000000.png').show()
        Image.open('./outputs/city_BasicVSR/00000000.png').show()
        Image.open('./demo_files/lq_sequences/city/00000001.png').show()
        Image.open('./outputs/city_BasicVSR/00000001.png').show()
        Image.open('./demo_files/lq_sequences/city/00000002.png').show()
        Image.open('./outputs/city_BasicVSR/00000002.png').show()
        Image.open('./demo_files/lq_sequences/city/00000003.png').show()
        Image.open('./outputs/city_BasicVSR/00000003.png').show()
        Image.open('./demo_files/lq_sequences/city/00000004.png').show()
        Image.open('./outputs/city_BasicVSR/00000004.png').show()
        Image.open('./demo_files/lq_sequences/city/00000005.png').show()
        Image.open('./outputs/city_BasicVSR/00000005.png').show()
        

        [image]

        [image]
    9. image inpainting の実行
    10. image matting の実行

    demos URL: https://github.com/open-mmlab/mmediting/blob/master/docs/en/getting_started.md

    !python3 demo/generation_demo.py configs/example_config.py work_dirs/example_exp/example_model_20200202.pth demo/demo.jpg demo/demo_out.jpg

    !python3 demo/generation_demo.py configs/example_config.py work_dirs/example_exp/example_model_20200202.pth demo/demo.jpg demo/demo_out.jpg --unpaired_path demo/demo_unpaired.jpg

    MMFewShot

    MMFewShot は, OpenMMLab の構成物で, Few Shot Classification, Few Shot Detection の機能を提供する.

    文献

    mmfewshot Contributors, OpenMMLab Few Shot Learning Toolbox and Benchmark, https://github.com/open-mmlab/mmfewshot, 2021.

    関連する外部ページ

    関連項目】 Few Shot Detection, OpenMMLab, MMClassification, MMCV, MMDetection,

    Google Colaboratory で,MMFewShot による Few Shot Detection の実行

    次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する).

    1. Google Colaboratory で,ランタイムのタイプを GPU に設定する.
    2. MIM のインストール
      !pip3 install git+https://github.com/open-mmlab/mim.git
      
    3. MMCV, MMDetection, MMClassification のインストール.

      https://mmclassification.readthedocs.io/en/latest/install.html, https://github.com/open-mmlab/mmdetection/blob/master/docs/en/get_started.md に記載の手順による

      
      !mim install mmdet
      !pip3 show mmdet
      cd /content
      !rm -rf mmclassification
      !git clone https://github.com/open-mmlab/mmclassification.git
      %cd mmclassification
      !git checkout dev
      !mim install -e .
      !pip3 show mmcls
      

      [image]
    4. MMFewShot のインストール

      https://github.com/open-mmlab/mmfewshot/blob/main/docs/en/install.md に記載の手順による.

      %cd /content
      !rm -rf mmfewshot
      !git clone https://github.com/open-mmlab/mmfewshot.git
      %cd mmfewshot
      !pip3 install -r requirements/build.txt
      !python3 setup.py develop
      !pip3 show mmfewshot
      

      [image]
    5. Few Shot Detection の実行
      %cd /content/mmfewshot
      import os
      from mmdet.apis import show_result_pyplot
      from mmfewshot.detection.apis import (inference_detector, init_detector, process_support_images)
      %matplotlib inline
      import matplotlib.pyplot as plt
      import torch
      import torchvision.models as models
      from IPython.display import display
      
      fconfig = 'configs/detection/attention_rpn/coco/attention-rpn_r50_c4_4xb2_coco_base-training.py'
      fcheckpoint = 'https://download.openmmlab.com/mmfewshot/detection/attention_rpn/coco/attention-rpn_r50_c4_4xb2_coco_base-training_20211102_003348-da28cdfd.pth'
      device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
      fsupport_images_dir = 'demo/demo_detection_images/support_images'
      
      model = init_detector(fconfig,fcheckpoint, device=device)
      
      files = os.listdir(fsupport_images_dir)
      support_images = [
          os.path.join(fsupport_images_dir, file) for file in files
      ]
      classes = [file.split('.')[0] for file in files]
      support_labels = [[file.split('.')[0]] for file in files]
      print("support_images")
      display(support_images)
      print("classes")
      display(classes)
      print("support_labels")
      display(support_labels)
      process_support_images(model, support_images, support_labels, classes=classes)
      
      # single image
      fimage = 'demo/demo_detection_images/query_images/demo_query.jpg'
      fscore_thr = 0.3
      result = inference_detector(model, fimage)
      show_result_pyplot(model, fimage, result, score_thr=fscore_thr)
      

      [image]
    Windows で,MMFewShot のインストールと,物体検出の実行

    MMCV 1.6.0, MMDetection 2.25.0,MMFewShot のインストールと動作確認(画像分類,物体検出)(PyTorch,Python を使用): 別ページ »で説明している.

    MMFlow

    MMFlow は, OpenMMLab の構成物で,オプティカルフローの機能を提供する.

    文献

    MMFlow Contributors, MMFlow: OpenMMLab Optical Flow Toolbox and Benchmark, https://github.com/open-mmlab/mmflow, 2021.

    関連する外部ページ

    関連項目OpenMMLab, MMCV, optical flow

    Windows で,MMFlow のインストールとオプティカルフローの実行

    MMFlow のインストールと動作確認(オプティカルフロー)(PyTorch,Python を使用): 別ページ »で説明している.

    Google Colaboratory で MMFlow によるオプティカルフローの算出

    次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する).

    1. Google Colaboratory で,ランタイムのタイプを GPU に設定する.
    2. まず,PyTorch のバージョンを確認

      PyTorch は,ディープラーニングのフレームワークの 機能を持つ Pythonのパッケージ

      次のプログラム実行により,PyTorch のバージョンが「1.10.0+cu111」のように表示される.

      import torch
      print(torch.__version__)
      
    3. NVIDIA CUDA ツールキット のバージョンを確認 (2)**NVIDIA CUDA ツールキット のバージョン**を確認 NVIDIA CUDA ツールキット は,NVIDIA社が提供している GPU 用のツールキットである.GPU を用いた演算のプログラム作成や動作のための各種機能を備えている.ディープラーニングでも利用されている.

      次のプログラム実行により,NVIDIA CUDA ツールキットのバージョンが「cu111」のように表示される.

      import torch
      CUDA_VERSION = torch.__version__.split("+")[-1]
      print(CUDA_VERSION)
      

      [image]
    4. PyTorch のバージョンを確認
      import torch
      TORCH_VERSION = ".".join(torch.__version__.split(".")[:2])
      print(TORCH_VERSION)
      

      [image]
    5. MMFlow のインストール
      !rm -rf mmflow
      !git clone https://github.com/open-mmlab/mmflow.git
      %cd mmflow
      !pip3 install -r requirements/build.txt
      !pip3 install .
      

      [image]
    6. 動画ファイルに対して,オプティカルフローを算出

      学習済みモデルを使用.

      !curl -O https://download.openmmlab.com/mmflow/raft/raft_8x2_100k_mixed_368x768.pth
      !python3 demo/video_demo.py demo/demo.mp4 \
          configs/raft/raft_8x2_100k_mixed_368x768.py \
          raft_8x2_100k_mixed_368x768.pth \
          raft_demo.mp4 --gt demo/demo_gt.mp4
      

      [image]

      結果として raft_demo_gt.mp4 ができるので,ダウンロードして,表示して確認する.

    MMGen

    Google Colaboratory で MMGEN による StyleGAN の実行

    次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する).

    1. Google Colaboratory で,ランタイムのタイプを GPU に設定する.
    2. まず,PyTorch のバージョンを確認

      PyTorch は,ディープラーニングのフレームワークの 機能を持つ Pythonのパッケージ

      次のプログラム実行により,PyTorch のバージョンが「1.10.0+cu111」のように表示される.

      import torch
      print(torch.__version__)
      
    3. NVIDIA CUDA ツールキット のバージョンを確認 (2)**NVIDIA CUDA ツールキット のバージョン**を確認 NVIDIA CUDA ツールキット は,NVIDIA社が提供している GPU 用のツールキットである.GPU を用いた演算のプログラム作成や動作のための各種機能を備えている.ディープラーニングでも利用されている.

      次のプログラム実行により,NVIDIA CUDA ツールキットのバージョンが「cu111」のように表示される.

      import torch
      CUDA_VERSION = torch.__version__.split("+")[-1]
      print(CUDA_VERSION)
      

      [image]
    4. PyTorch のバージョンを確認
      import torch
      TORCH_VERSION = ".".join(torch.__version__.split(".")[:2])
      print(TORCH_VERSION)
      

      [image]
    5. MMCV 1.7.1 のインストール

      インストール手順は, https://mmcv.readthedocs.io/en/latest/get_started/installation.html に記載の手順による

      MMTracking が MMVC 1.6.2 に依存している (2023年4月時点). MMTracking の利用を想定して MMCV 1.6.2 をインストールする.

      !python -c "import torch; print(torch.__version__)"
      !apt remove python3-pycocotools
      !pip uninstall -y pycocotools
      !pip install mmpycocotools
      !apt install -y python3-terminaltables
      !apt install -y python3-opencv
      !pip install mmcv-full==1.6.2
      !python3 -c "from mmcv.ops import get_compiling_cuda_version, get_compiler_version; print(get_compiling_cuda_version(), get_compiler_version())"
      
    6. MIM, MMGen のインストール
      !python -m pip install -U openmim opencv-python
      
      !rm -rf mmgeneration
      !git clone https://github.com/open-mmlab/mmgeneration.git
      %cd mmgeneration
      !pip3 install -r requirements/build.txt
      !pip3 install .
      

      [image]
    7. StyleGAN を実行

      https://github.com/open-mmlab/mmgeneration/blob/master/docs/en/get_started.md に記載のプログラムを使用

      学習済みモデルを使用.

      from mmgen.apis import init_model, sample_uncoditional_model
      
      config_file = 'configs/styleganv2/stylegan2_c2_lsun-church_256_b4x8_800k.py'
      # you can download this checkpoint in advance and use a local file path.
      checkpoint_file = 'https://download.openmmlab.com/mmgen/stylegan2/official_weights/stylegan2-church-config-f-official_20210327_172657-1d42b7d1.pth'
      device = 'cuda:0'
      # init a generatvie
      model = init_model(config_file, checkpoint_file, device=device)
      # sample images
      fake_imgs = sample_uncoditional_model(model, 4)
      
      import numpy as np
      import matplotlib.pyplot as plt
      plt.style.use('default')
      for i in fake_imgs:
          plt.imshow(np.stack([i[2], i[1], i[0]], axis=2))
          plt.show()
      

      [image]

    MMPose

    MMPose は, OpenMMLab の構成物で,2次元の姿勢推定,3次元の姿勢推定の機能を提供する.

    関連項目OpenMMLab, MMCV, MMDetection, MMTracking, 物体検出 2次元の姿勢推定, 姿勢推定, 人体の姿勢推定, 手の姿勢推定,

    Google Colaboratory で,MMPose による姿勢推定の実行

    次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する).

    1. Google Colaboratory で,ランタイムのタイプを GPU に設定する.
    2. MMCV 1.7.1 のインストール

      インストール手順は, https://mmcv.readthedocs.io/en/latest/get_started/installation.html に記載の手順による

      MMTracking が MMVC 1.6.2 に依存している (2023年4月時点). MMTracking の利用を想定して MMCV 1.6.2 をインストールする.

      !python -c "import torch; print(torch.__version__)"
      !apt remove python3-pycocotools
      !pip uninstall -y pycocotools
      !pip install mmpycocotools
      !apt install -y python3-terminaltables
      !apt install -y python3-opencv
      !pip install mmcv-full==1.6.2
      !python3 -c "from mmcv.ops import get_compiling_cuda_version, get_compiler_version; print(get_compiling_cuda_version(), get_compiler_version())"
      
    3. MIM, MMClassification, MMSegmentation, MMDetection, MMTracking, MMPose のインストール.MMPose のインストール後は numpy, scipy の更新も行う.

      https://github.com/open-mmlab/mmpose/blob/master/docs/en/install.md#install-mmposeに記載の手順による.

      MMCV 1.6.2 をインストールしたので,MMDetection は 2系列になる(3系列は動かない)(2023年4月時点).

      !python -m pip install -U openmim opencv-python
      !python -m pip install -U mmcv-full==1.6.2
      !python -m pip install -U git+https://github.com/open-mmlab/mmclassification.git
      !python -m pip install -U mmdet==2.28.2
      !python -m pip install -U git+https://github.com/open-mmlab/mmsegmentation.git
      !python -m pip install -U git+https://github.com/open-mmlab/mmtracking.git
      !python -m pip install -U git+https://github.com/open-mmlab/mmpose.git
      !apt -y install python3-numpy
      !apt -y install python3-scipy
      !python -c "import mmcls; print(mmcls.__version__)"
      !python -c "import mmdet; print(mmdet.__version__)"
      !python -c "import mmseg; print(mmseg.__version__)"
      !python -c "import mmtrack; print(mmtrack.__version__)"
      !python -c "import mmpose; print(mmpose.__version__)"
      
      !pip3 install git+https://github.com/votchallenge/toolkit.git
      

      [image]
    4. 姿勢推定の実行

      公式のデモプログラム(https://github.com/open-mmlab/mmpose/blob/master/demo/docs/2d_human_pose_demo.md)を使用.

      • 人体の2次元姿勢推定

        公式ページの https://github.com/open-mmlab/mmpose/blob/master/demo/docs/2d_human_pose_demo.md で説明されているプログラムを使用.

        人体の検出 (human detection) に,MMDetection を使用し, 姿勢推定に,MMPoseを使用.

        !python3 demo/top_down_img_demo_with_mmdet.py \
            demo/mmdetection_cfg/faster_rcnn_r50_fpn_coco.py \
            https://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_1x_coco/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth \
            configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/coco/hrnet_w48_coco_256x192.py \
            https://download.openmmlab.com/mmpose/top_down/hrnet/hrnet_w48_coco_256x192-b9e0b3ab_20200708.pth \
            --img-root tests/data/coco/ \
            --img 000000000785.jpg \
            --out-img-root vis_results
        
        from PIL import Image
        Image.open('./vis_results/vis_000000000785.jpg').show()
        
        !python3 demo/top_down_img_demo_with_mmdet.py \
            demo/mmdetection_cfg/faster_rcnn_r50_fpn_coco.py \
            https://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_1x_coco/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth \
            configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/coco/hrnet_w48_coco_256x192.py \
            https://download.openmmlab.com/mmpose/top_down/hrnet/hrnet_w48_coco_256x192-b9e0b3ab_20200708.pth \
            --img-root tests/data/coco/ \
            --img 000000040083.jpg \
            --out-img-root vis_results
        
        from PIL import Image
        Image.open('./vis_results/vis_000000040083.jpg').show()
        
        !python3 demo/top_down_img_demo_with_mmdet.py \
            demo/mmdetection_cfg/faster_rcnn_r50_fpn_coco.py \
            https://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_1x_coco/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth \
            configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/coco/hrnet_w48_coco_256x192.py \
            https://download.openmmlab.com/mmpose/top_down/hrnet/hrnet_w48_coco_256x192-b9e0b3ab_20200708.pth \
            --img-root tests/data/coco/ \
            --img 000000196141.jpg \
            --out-img-root vis_results
        
        from PIL import Image
        Image.open('./vis_results/vis_000000196141.jpg').show()
        
        !python3 demo/top_down_img_demo_with_mmdet.py \
            demo/mmdetection_cfg/faster_rcnn_r50_fpn_coco.py \
            https://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_1x_coco/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth \
            configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/coco/hrnet_w48_coco_256x192.py \
            https://download.openmmlab.com/mmpose/top_down/hrnet/hrnet_w48_coco_256x192-b9e0b3ab_20200708.pth \
            --img-root tests/data/coco/ \
            --img 000000197388.jpg \
            --out-img-root vis_results
        
        from PIL import Image
        Image.open('./vis_results/vis_000000197388.jpg').show()
        

        [image]

        [image]
      • 全身の2次元姿勢推定

        公式ページの https://github.com/open-mmlab/mmpose/blob/master/demo/docs/2d_wholebody_pose_demo.md で説明されているプログラムを使用.

        人体の検出 (human detection) に,MMDetection を使用し, 姿勢推定に,MMPoseを使用.

        1つ上の結果(人体の2次元姿勢推定)と比べて,顔の部分に違いがある.

        !python3 demo/top_down_img_demo_with_mmdet.py \
            demo/mmdetection_cfg/faster_rcnn_r50_fpn_coco.py \
            https://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_1x_coco/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth \
            configs/wholebody/2d_kpt_sview_rgb_img/topdown_heatmap/coco-wholebody/hrnet_w48_coco_wholebody_384x288_dark_plus.py \
            https://download.openmmlab.com/mmpose/top_down/hrnet/hrnet_w48_coco_wholebody_384x288_dark-f5726563_20200918.pth \
            --img-root tests/data/coco/ \
            --img 000000000785.jpg \
            --out-img-root vis_results
        
        from PIL import Image
        Image.open('./vis_results/vis_000000000785.jpg').show()
        
        !python3 demo/top_down_img_demo_with_mmdet.py \
            demo/mmdetection_cfg/faster_rcnn_r50_fpn_coco.py \
            https://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_1x_coco/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth \
            configs/wholebody/2d_kpt_sview_rgb_img/topdown_heatmap/coco-wholebody/hrnet_w48_coco_wholebody_384x288_dark_plus.py \
            https://download.openmmlab.com/mmpose/top_down/hrnet/hrnet_w48_coco_wholebody_384x288_dark-f5726563_20200918.pth \
            --img-root tests/data/coco/ \
            --img 000000040083.jpg \
            --out-img-root vis_results
        
        from PIL import Image
        Image.open('./vis_results/vis_000000040083.jpg').show()
        
        !python3 demo/top_down_img_demo_with_mmdet.py \
            demo/mmdetection_cfg/faster_rcnn_r50_fpn_coco.py \
            https://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_1x_coco/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth \
            configs/wholebody/2d_kpt_sview_rgb_img/topdown_heatmap/coco-wholebody/hrnet_w48_coco_wholebody_384x288_dark_plus.py \
            https://download.openmmlab.com/mmpose/top_down/hrnet/hrnet_w48_coco_wholebody_384x288_dark-f5726563_20200918.pth \
            --img-root tests/data/coco/ \
            --img 000000196141.jpg \
            --out-img-root vis_results
        
        from PIL import Image
        Image.open('./vis_results/vis_000000196141.jpg').show()
        
        !python3 demo/top_down_img_demo_with_mmdet.py \
            demo/mmdetection_cfg/faster_rcnn_r50_fpn_coco.py \
            https://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_1x_coco/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth \
            configs/wholebody/2d_kpt_sview_rgb_img/topdown_heatmap/coco-wholebody/hrnet_w48_coco_wholebody_384x288_dark_plus.py \
            https://download.openmmlab.com/mmpose/top_down/hrnet/hrnet_w48_coco_wholebody_384x288_dark-f5726563_20200918.pth \
            --img-root tests/data/coco/ \
            --img 000000197388.jpg \
            --out-img-root vis_results
        
        from PIL import Image
        Image.open('./vis_results/vis_000000197388.jpg').show()
        

        [image]

        [image]
      • 手の2次元姿勢推定

        公式ページの https://github.com/open-mmlab/mmpose/blob/master/demo/docs/2d_hand_demo.md で説明されているプログラムを使用.

        人体の検出 (human detection) に,MMDetection を使用し, 姿勢推定に,MMPoseを使用.

        !python3 demo/top_down_img_demo_with_mmdet.py demo/mmdetection_cfg/cascade_rcnn_x101_64x4d_fpn_1class.py \
            https://download.openmmlab.com/mmpose/mmdet_pretrained/cascade_rcnn_x101_64x4d_fpn_20e_onehand10k-dac19597_20201030.pth \
            configs/hand/2d_kpt_sview_rgb_img/topdown_heatmap/onehand10k/res50_onehand10k_256x256.py \
            https://download.openmmlab.com/mmpose/top_down/resnet/res50_onehand10k_256x256-e67998f6_20200813.pth \
            --img-root tests/data/onehand10k/ \
            --img 1402.jpg \
            --out-img-root vis_results
        
        from PIL import Image
        Image.open('./vis_results/vis_1402.jpg').show()
        
        !python3 demo/top_down_img_demo_with_mmdet.py demo/mmdetection_cfg/cascade_rcnn_x101_64x4d_fpn_1class.py \
            https://download.openmmlab.com/mmpose/mmdet_pretrained/cascade_rcnn_x101_64x4d_fpn_20e_onehand10k-dac19597_20201030.pth \
            configs/hand/2d_kpt_sview_rgb_img/topdown_heatmap/onehand10k/res50_onehand10k_256x256.py \
            https://download.openmmlab.com/mmpose/top_down/resnet/res50_onehand10k_256x256-e67998f6_20200813.pth \
            --img-root tests/data/onehand10k/ \
            --img 784.jpg \
            --out-img-root vis_results
        
        from PIL import Image
        Image.open('./vis_results/vis_784.jpg').show()
        
        !python3 demo/top_down_img_demo_with_mmdet.py demo/mmdetection_cfg/cascade_rcnn_x101_64x4d_fpn_1class.py \
            https://download.openmmlab.com/mmpose/mmdet_pretrained/cascade_rcnn_x101_64x4d_fpn_20e_onehand10k-dac19597_20201030.pth \
            configs/hand/2d_kpt_sview_rgb_img/topdown_heatmap/onehand10k/res50_onehand10k_256x256.py \
            https://download.openmmlab.com/mmpose/top_down/resnet/res50_onehand10k_256x256-e67998f6_20200813.pth \
            --img-root tests/data/onehand10k/ \
            --img 9.jpg \
            --out-img-root vis_results
        
        from PIL import Image
        Image.open('./vis_results/vis_9.jpg').show()
        

        [image]

        [image]

        [image]
      • 顔のランドマーク検出

        公式ページの https://github.com/open-mmlab/mmpose/blob/master/demo/docs/2d_face_demo.md で説明されているプログラムを使用.

        顔検出 に,Dlib と ageitgey/face_recognition (https://github.com/ageitgey/face_recognition) を使用. 顔のランドマーク検出に,MMPoseを使用.

        
        

        [image]

        [image]
      • 人体の3次元姿勢推定

        公式ページの https://github.com/open-mmlab/mmpose/blob/master/demo/docs/3d_human_pose_demo.md で説明されているプログラムを使用.

        !python3 demo/body3d_two_stage_video_demo.py \
            demo/mmdetection_cfg/faster_rcnn_r50_fpn_coco.py \
            https://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_1x_coco/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth \
            configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/coco/hrnet_w48_coco_256x192.py \
            https://download.openmmlab.com/mmpose/top_down/hrnet/hrnet_w48_coco_256x192-b9e0b3ab_20200708.pth \
            configs/body/3d_kpt_sview_rgb_vid/video_pose_lift/h36m/videopose3d_h36m_243frames_fullconv_supervised_cpn_ft.py \
            https://download.openmmlab.com/mmpose/body3d/videopose/videopose_h36m_243frames_fullconv_supervised_cpn_ft-88f5abbb_20210527.pth \
            --video-path demo/resources/demo.mp4 \
            --out-video-root vis_results \
            --rebase-keypoint-height
        

        [image]
    Windows で,MMPose のインストールと人体の姿勢推定の実行

    MMPose のインストールと動作確認(姿勢推定,関節角度の推定)(PyTorch,Python を使用)(Windows 上): 別ページ »で説明している.

    MMSegmentation

    MMSegmentation は, OpenMMLab の構成物で,セグメンテーションの機能を提供する.

    文献

    MMSegmentation Contributors, MMSegmentation: OpenMMLab Semantic Segmentation Toolbox and Benchmark, https://github.com/open-mmlab/mmsegmentation, 2020.

    サイト内の関連ページ

    セマンティック・セグメンテーションの実行(MMSegmentation,PyTorch,Python を使用)(Windows 上)

    関連する外部ページ

    関連項目OpenMMLab, MMCV, MMSelfSup

    Google Colaboratory でセマンティック・セグメンテーションの実行(MMSegmentation, DeepLabv3 を使用)

    次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する).

    1. Google Colaboratory で,ランタイムのタイプを GPU に設定する.
    2. まず,PyTorch のバージョンを確認

      PyTorch は,ディープラーニングのフレームワークの 機能を持つ Pythonのパッケージ

      次のプログラム実行により,PyTorch のバージョンが「1.10.0+cu111」のように表示される.

      import torch
      print(torch.__version__)
      
    3. NVIDIA CUDA ツールキット のバージョンを確認 (2)**NVIDIA CUDA ツールキット のバージョン**を確認 NVIDIA CUDA ツールキット は,NVIDIA社が提供している GPU 用のツールキットである.GPU を用いた演算のプログラム作成や動作のための各種機能を備えている.ディープラーニングでも利用されている.

      次のプログラム実行により,NVIDIA CUDA ツールキットのバージョンが「cu111」のように表示される.

      import torch
      CUDA_VERSION = torch.__version__.split("+")[-1]
      print(CUDA_VERSION)
      

      [image]
    4. PyTorch のバージョンを確認
      import torch
      TORCH_VERSION = ".".join(torch.__version__.split(".")[:2])
      print(TORCH_VERSION)
      

      [image]
    5. MMCV 1.7.1 のインストール

      インストール手順は, https://mmcv.readthedocs.io/en/latest/get_started/installation.html に記載の手順による

      MMTracking が MMVC 1.6.2 に依存している (2023年4月時点). MMTracking の利用を想定して MMCV 1.6.2 をインストールする.

      !python -c "import torch; print(torch.__version__)"
      !apt remove python3-pycocotools
      !pip uninstall -y pycocotools
      !pip install mmpycocotools
      !apt install -y python3-terminaltables
      !apt install -y python3-opencv
      !pip install mmcv-full==1.6.2
      !python3 -c "from mmcv.ops import get_compiling_cuda_version, get_compiler_version; print(get_compiling_cuda_version(), get_compiler_version())"
      
    6. MIM, MMDetection, MMSegmentation のインストール

      MMCV 1.7.1 をインストールしたので,MMDetection は 2系列になる(3系列は動かない)(2023年4月時点).

      !python -m pip install -U openmim opencv-python
      !python -m pip install -U mmcv-full==1.7.1
      !python -m pip install -U mmdet==2.28.2
      !python -m pip install -U git+https://github.com/open-mmlab/mmsegmentation.git
      !python -c "import mmdet; print(mmdet.__version__)"
      !python -c "import mmseg; print(mmseg.__version__)"
      
    7. セマンティック・セグメンテーションの実行(MMSegmentation, Cityscapes データセットで学習済みのDeepLabv3+ を使用)

      次のプログラムは,MMSegmentation の機能を利用して,DeepLabv3+ を用いたセマンティック・セグメンテーションを行う.

      セマンティック・セグメンテーションの結果として得られる クラスが,色分けで表示される.

      import torch
      from mmseg.apis import inference_segmentor, init_segmentor, show_result_pyplot
      import mmcv
      
      fimg = 'demo/demo.png'
      # DeepLabv3
      fconfig = 'configs/deeplabv3/deeplabv3_r101-d8_fp16_512x1024_80k_cityscapes.py'
      fcheckpoint = 'https://download.openmmlab.com/mmsegmentation/v0.5/deeplabv3/deeplabv3_r101-d8_fp16_512x1024_80k_cityscapes/deeplabv3_r101-d8_fp16_512x1024_80k_cityscapes_20200717_230920-774d9cec.pth'
      # DeepLabv3+
      fconfig = 'configs/deeplabv3plus/deeplabv3plus_r101-d8_fp16_512x1024_80k_cityscapes.py'
      fcheckpoint = 'https://download.openmmlab.com/mmsegmentation/v0.5/deeplabv3plus/deeplabv3plus_r101-d8_fp16_512x1024_80k_cityscapes/deeplabv3plus_r101-d8_fp16_512x1024_80k_cityscapes_20200717_230920-f1104f4b.pth'
      # OCRNet
      #fconfig = 'configs/ocrnet/ocrnet_hr48_512x1024_40k_cityscapes.py'
      #fcheckpoint = 'https://download.openmmlab.com/mmsegmentation/v0.5/ocrnet/ocrnet_hr48_512x1024_40k_cityscapes/ocrnet_hr48_512x1024_40k_cityscapes_20200601_033336-55b32491.pth'
      # SegFormer
      #fconfig = 'configs/segformer/segformer_mit-b2_8x1_1024x1024_160k_cityscapes.py'
      #fcheckpoint = 'https://download.openmmlab.com/mmsegmentation/v0.5/segformer/segformer_mit-b2_8x1_1024x1024_160k_cityscapes/segformer_mit-b2_8x1_1024x1024_160k_cityscapes_20211207_134205-6096669a.pth'
      
      device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
      model = init_segmentor(fconfig, fcheckpoint, device=device)
      result = inference_segmentor(model, fimg)
      print(result)
      show_result_pyplot(model, fimg, result, opacity=0.5)
      

      [image]
    セマンティック・セグメンテーションの実行(MMSegmentation,PyTorch,Python を使用)(Windows 上)

    別ページ »で説明している.

    Ubuntu での MMSegmentation の実行
    1. インストール

      「git checkout v0.14.1」は,バージョン 0.14.1 を指定している. これは,https://mmdetection3d.readthedocs.io/en/latest/get_started.html での2021/08 時点の説明による.将来はバージョン番号が変わる可能性があり,このページを確認してから,インストールを行うこと.

      Ubuntu でインストールを行うには,次のコマンドを実行.

      sudo apt -y update
      sudo apt -y install git
      
      cd /usr/local
      sudo git clone https://github.com/open-mmlab/mmsegmentation.git
      sudo chown -R $USER mmsegmentation
      cd mmsegmentation
      git checkout v0.14.1
      python3 setup.py develop
      
    2. 動作確認

      Ubuntu の場合は, MMCV のドキュメント: https://mmsegmentation.readthedocs.io/en/latest/get_started.html#verification の手順がそのまま使えそうである.

    MMSegmentation3D

    Google Colaboratory でのインストールは,次のような手順になるようである(未確認).

    %cd /content
    !rm -rf mmdetection3d.git
    !git clone https://github.com/open-mmlab/mmdetection3d.git
    %cd mmdetection3d
    !pip3 install importlib-metadata==4.2
    !python3 setup.py develop
    !apt install -y python3-numba
    %cd mmdetection3d
    !python3 demo/pcd_demo.py demo/data/kitti/kitti_000008.bin configs/second/hv_second_secfpn_6x8_80e_kitti-3d-car.py checkpoints/hv_second_secfpn_6x8_80e_kitti-3d-car_20200620_230238-393f000c.pth
    
    関連項目OpenMMLab, MMCV, MMDetection, 物体検出

    MMSelfSup

    MMSelfSup は, OpenMMLab の構成物で, Self-Supervised Representation Learning の機能を提供する.

    関連項目MMCV, MMDetection, MMSegmentation, OpenMMLab, Self-Supervised Representation Learning, 物体検出

    Google Colaboratory で,MMSelfSup のインストール

    次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する).

    MMSelfSup のインストール(公式ページ): https://github.com/open-mmlab/mmselfsup/blob/master/docs/en/install.md

    1. Google Colaboratory で,ランタイムのタイプを GPU に設定する.
    2. MIM のインストール
      !pip3 install git+https://github.com/open-mmlab/mim.git
      
    3. MMCV, MMDetection のインストール.

      https://github.com/open-mmlab/mmdetection/blob/master/docs/en/get_started.md に記載の手順による

      
      !mim install mmdet
      !pip3 show mmdet
      

      [image]
    4. MMSegmentation のインストール

      次のプログラム実行により,MMSegmentation がインストールされる.

      !rm -rf mmsegmentation.git
      !git clone https://github.com/open-mmlab/mmsegmentation.git
      %cd mmsegmentation
      !python3 setup.py develop
      

      [image]
    5. MMSelfSup のインストール
      %cd /content
      rm -rf mmselfsup
      !git clone https://github.com/open-mmlab/mmselfsup.git
      %cd mmselfsup
      !python3 setup.py develop
      

      [image]
    6. インストールできたことの確認

      公式ページ https://github.com/open-mmlab/mmselfsup/blob/master/docs/en/install.md に記載のプログラムを実行してみる.

      エラーメッセージが出なければ OK.

      import torch
      
      from mmselfsup.models import build_algorithm
      
      model_config = dict(
          type='Classification',
          backbone=dict(
              type='ResNet',
              depth=50,
              in_channels=3,
              num_stages=4,
              strides=(1, 2, 2, 2),
              dilations=(1, 1, 1, 1),
              out_indices=[4],  # 0: conv-1, x: stage-x
              norm_cfg=dict(type='BN'),
              frozen_stages=-1),
          head=dict(
              type='ClsHead', with_avg_pool=True, in_channels=2048,
              num_classes=1000))
      
      model = build_algorithm(model_config).cuda()
      
      image = torch.randn((1, 3, 224, 224)).cuda()
      label = torch.tensor([1]).cuda()
      
      loss = model.forward_train(image, label)
      print(loss)
      

      [image]

    MMTracking

    MMTracking は, OpenMMLab の構成物で,トラッキング・ビジョンの機能を提供する.

    関連項目OpenMMLab, MMCV, MMDetection, MMPose, 物体検出

    Google Colaboratory で,MMTracking によるトラッキングの実行

    次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する).

    1. Google Colaboratory で,ランタイムのタイプを GPU に設定する.
    2. MIM のインストール
      !pip3 install git+https://github.com/open-mmlab/mim.git
      
    3. MMCV, MMDetection のインストール.

      https://github.com/open-mmlab/mmdetection/blob/master/docs/en/get_started.md に記載の手順による

      !mim install mmdet
      !pip3 show mmdet
      

      [image]
    4. MMTracking のインストール
      !rm -rf mmtracking
      !git clone https://github.com/open-mmlab/mmtracking.git
      %cd mmtracking
      !pip3 install -r requirements/build.txt
      !pip3 install . 
      !pip3 show mmtrack
      !pip3 install git+https://github.com/votchallenge/toolkit.git
      

      [image]
    5. トラッキングの実行
      !python3 demo/demo_mot_vis.py configs/mot/deepsort/sort_faster-rcnn_fpn_4e_mot17-private.py --input demo/demo.mp4 --output mot.mp4
      

      [image]
    6. 結果の確認

      mot.mp4 というファイルができるので,ダウンロードして表示

      [image]
    Windows で,MMTracking のインストール

    MMTracking のインストールと動作確認(トラッキングビジョン)(PyTorch,Python,MMCV,MMDetection を使用)(Windows 上): 別ページ »で説明している.

    MNIST データセット

    MNIST データセットは,公開されているデータセット(オープンデータ)である.

    0 から 9 までの 10 種類の手書き文字についての, モノクロ画像と,各画像に付いた「0から9までの数値」のラベルから構成されるデータセットである.

    文献

    Y. Lecun, L. Bottou, Y. Bengio and P. Haffner, Gradient-based learning applied to document recognition, vol. 86, no. 11, pp. 2278-2324, 1998.

    サイト内の関連ページ

    関連する外部ページ

    関連項目Keras に付属のデータセット, Fashion MNIST データセット, TensorFlow データセット, オープンデータ, 画像分類

    MobileFaceNets

    顔検証 (face verification) を,その当時の従来の mobile networks よりも高速で高精度で実行できるとされている.

    InsightFace などで実装されている.

    関連項目InsightFace, 顔検証 (face verification), 顔に関する処理

    MobileNetV2

    MobileNet は,separable convolution を特徴としている.ResNet の高速化が達成できたとされている.

    MobileNetV2 は,conv 1x1, depthsise conv, conv 1x1 を特徴としている.高速化が達成できたとされている.

    MobileNetV2 は,ディープラーニングでの画像分類などの高速化,精度向上のため Depthwise Separable Convolution という考え方が導入されていることが特徴である.

    物体検出セマンティック・セグメンテーションなどでのバックボーンでの利用も行われている.

    KerasMobileNetV2 を用いて MobileNetV2 を作成するプログラムは次のようになる. 「weights=None」を指定することにより,最初,重みをランダムに設定する.

    Keras のプログラム】

    Keras の応用のページ: https://keras.io/ja/applications/

    from tensorflow.keras.applications.mobilenet_v3 import MobileNetV3
    m = MobileNetV3(input_shape=INPUT_SHAPE, weights=None, classes=NUM_CLASSES)
    

    サイト内の関連ページ

    関連項目画像分類, モデル

    MobileNetV3

    物体検出セマンティック・セグメンテーションなどでのバックボーンでの利用も行われている.

    関連項目: 画像分類

    関連項目モデル, 画像分類

    PyTorch, torchvision の MobileNetV3 large 学習済みモデルのロード,画像分類のテスト実行

    Google Colab あるいはパソコン(Windows あるいは Linux)を使用.

    1. 前準備

      前準備として,Python のインストール: 別項目で説明している., PyTorch のインストール を行う.

      Google Colaboratory では, Python, PyTorch はインストール済みなので,インストール操作は不要.

      次に,pip を用いて,pillow のインストールを行う.

      pip install -U pillow
      
    2. ImageNet データセット で学習済みのMobileNetV3 モデルのロード

      PyTorch, torchvision のモデルについては: https://pytorch.org/vision/stable/models.html に説明がある.

      import torch
      import torchvision.models as models
      device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
      m = models.mobilenet_v3_large(pretrained=True).to(device)
      
    3. 画像分類したい画像ファイルのダウンロードとロードと確認表示
      from PIL import Image
      import requests
      from IPython.display import display
      
      # ダウンロードとロード
      url = 'https://github.com/pytorch/hub/raw/master/images/dog.jpg'
      response = requests.get(url)
      img = Image.open(requests.get(url, stream=True).raw)
      
      # 確認表示
      display(img)
      

      [image]
    4. 画像の前処理.PyTorch で扱えるようにするため.
      from PIL import Image
      from torchvision import transforms
      img = Image.open(filename)
      preprocess = transforms.Compose([
          transforms.Resize(256),
          transforms.CenterCrop(224),
          transforms.ToTensor(),
          transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
      ])
      input_tensor = preprocess(img)
      input_batch = input_tensor.unsqueeze(0)
      
    5. 推論 (inference) の実行

      「m.eval()」は,推論を行うときのためのもの.これを行わないと訓練(学習)が行われる.

      import torch
      if torch.cuda.is_available():
          input_batch = input_batch.to('cuda')
      
      m.eval()
      with torch.no_grad():
          output = m(input_batch)
      
    6. 結果の表示
      import urllib
      url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt")
      try: urllib.URLopener().retrieve(url, filename)
      except: urllib.request.urlretrieve(url, filename)
      
      with open("imagenet_classes.txt", "r") as f:
          categories = [s.strip() for s in f.readlines()]
      
      # The output has unnormalized scores. To get probabilities, you can run a softmax on it.
      probabilities = torch.nn.functional.softmax(output[0], dim=0)
      print(probabilities)
      
      top5_prob, top5_catid = torch.topk(probabilities, 5)
      for i in range(top5_prob.size(0)):
          print(categories[top5_catid[i]], top5_prob[i].item())
      

      Google Colaboratory での結果

      [image]

      Windows での結果

      [image]

      Linux での結果

      [image]

    MongoDB

    MongoDB は,ドキュメントデータモデルの機能をもつデータベース管理システム

    サイト内の関連ページ

    関連する外部ページ

    MPII Human Pose データセット

    MPII Human Pose データセット は, 人体全身の画像と姿勢のデータセットである. ディープラーニングにより姿勢推定を行うためのデータとして利用できる.

    40,000人以上の人間を含む約25,000枚の画像が含まれている. (28,000 が訓練データ,11,000 が検証データである). 画像のアノテーションが行われている. 410 種類の人間の活動を網羅している. 各画像については,活動名のラベルが付いている. 画像はYouTubeの動画から抽出されたものである. テストデータセットでは,体のオクルージョン,胴体や頭の3次元での向きなど, より豊富なアノテーションが行われている.

    次の URL で公開されているデータセット(オープンデータ)である.

    URL: http://human-pose.mpi-inf.mpg.de/

    ライセンス: BSD ライセンス.利用条件等は,利用者で確認すること.

    【関連情報】

    次により c:\data\mpii にダウンロードされる.アノテーションファイルもダウンロードされる.
    mkdir c:\data
    mkdir c:\data\mpii
    cd c:\data\mpii
    curl -O https://datasets.d2.mpi-inf.mpg.de/andriluka14cvpr/mpii_human_pose_v1_u12_2.zip
    powershell -command "Expand-Archive -DestinationPath . -Path mpii_human_pose_v1_u12_2.zip"
    curl -O https://datasets.d2.mpi-inf.mpg.de/andriluka14cvpr/mpii_human_pose_v1.tar.gz
    "c:\Program Files\7-Zip\7z.exe" x mpii_human_pose_v1.tar.gz
    mkdir images
    cd images
    "c:\Program Files\7-Zip\7z.exe" x ..\mpii_human_pose_v1.tar
    

    Mykhaylo Andriluka and Leonid Pishchulin and Peter Gehler and Schiele, Bernt, 2D Human Pose Estimation: New Benchmark and State of the Art Analysis, IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2014, https://openaccess.thecvf.com/content_cvpr_2014/papers/Andriluka_2D_Human_Pose_2014_CVPR_paper.pdf

    MS1M データセット

    MS-Celeb-1M データセット を洗浄 (clean) したデータ. 画像サイズは 112x112. RetinaFace を用いて推定された,5点の顔ランドマーク (facial landmark)が付いている.

    人物数は 94,682 (94,682 identities), 画像数は 6,464,018 枚 (6,464,018 images)

    次の URL で公開されているデータセット(オープンデータ)である.

    https://github.com/EB-Dodo/C-MS-Celeb

    関連項目InsightFace, MS-Celeb-1M データセット, RetinaFace, 顔のデータベース, 顔ランドマーク (facial landmark), 顔検出 (face detection)

    MS-Celeb-1M データセット

    MS-Celeb-1M は,顔のデータセット. このデータセットは,公開が撤回されている.

    人物数は約 100,000 (100K identities), 画像数は約 8,000,000 枚 (8M images)

    関連項目C-MS-Celeb Cleaned データセットInsightFace, 顔のデータベース, 顔検出 (face detection)

    MUCT 顔データベース

    MUCT 顔データベースは,3755名の顔のデータベース.手作業で 76個の顔ランドマーク (facial landmark)が付けらている.

    MUCT 顔データベースは次の URL で公開されているデータセット(オープンデータ)である.

    URL: https://www.cs.columbia.edu/CAVE/software/curet/html/about.php

    URL: http://www.milbo.org/muct/index.html

    S. Milborrow and J. Morkel and F. Nicolls, The MUCT Landmarked Face Database, Pattern Recognition Association of South Africa, 2010.

    次の手順でダウンロードできる.
    1. Git のインストール: 別項目で説明している.

      Git の公式ページ: https://git-scm.com/

    2. ダウンロード操作
      git clone https://github.com/StephenMilborrow/muct
      

    関連項目顔のデータベース, 顔ランドマーク (facial landmark)

    Multi-PIE の 顔の 68 ランドマーク

    顔の 68 ランドマーク は,顔ランドマーク (facial landmark)の一種であり,68 組の数値で構成されている.68 組のそれぞれは,(x, y) 座標値である.

    関連項目顔の 68 ランドマーク の検出, 顔ランドマーク (facial landmark)

    Multi View Stereo (MVS)

    Multi View Stereo は,オブジェクトの特徴点である低密度の3次元点群と,オブジェクトを周囲から撮影した多数の画像から,高密度の3次元点群を生成する. 色付き3次元点群を生成する場合もある.「Dense Recontruction」ともいう.

    meshroomOpenMVS などのソフトウェアがある. Ubuntu での OpenMVS のインストールは 別ページ »で説明している.

    【関連用語】 3次元再構成 (3D reconstruction), meshroom, OpenMVS, Structure from Motion

    MusicGen

    MusicGen は, 単一ステージのトランスフォーマー言語モデル(transformer language model)を特徴とする。 フレシェオーディオ距離 (FAD)、クルバック・ライブラーダイバージェンス (KL)、CLAPスコア (CLAP)という客観的指標ならびに、 全体的な品質および(ii)テキスト入力への関連性の主観的指標について、 baselines for text-to-music generation: Riffusion [Forsgren and Martiros] and Mousai [Schneider et al., 2023]をベースラインとして 評価が行われている。

    文献

    Jade Copet and Felix Kreuk and Itai Gat and Tal Remez and David Kant and Gabriel Synnaeve and Yossi Adi and Alexandre Défossez, Simple and Controllable Music Generation, arXiv preprint arXiv:2306.05284, 2023.

    https://arxiv.org/pdf/2306.05284v1.pdf

    サイト内の関連ページ

    MusicGen のインストールと動作確認(作曲)(Python,PyTorch を使用)(Windows 上)

    関連する外部ページ

    サイト内の関連ページ

    関連する外部ページ

    Windows でのメッセージで,「Could not locate zlibwapi.dll. Please make sure it is in your library path!」と表示されたときの対処

    ZLIB DLL をインストールする.

    NVIDIA ドライバ,NVIDIA CUDA ツールキット, NVIDIA cuDNN のインストールの要点と注意点
    Windows での NVIDIA CUDA ツールキット,NVIDIA cuDNN のインストール

    NVIDIA CUDA ツールキットのインストールは,公式ページからインストール用のプログラムをダウンロードして実行. NVIDIA cuDNN は,公式ページから ZIP ファイルをダウンロード,展開(解凍)し,パスを通す.

    サイト内の関連ページ

    関連 Web ページ

    NVIDIA CUDA ツールキット,NVIDIA cuDNN のインストール(Ubuntu 上)

    Ubuntu でのインストールは,次のページで説明している.

    NVIDIA CUDA ツールキット のバージョンは何でも良いと言う場合には,apt を用いて,次の操作でインストールすることができる. Ubuntu 20.04 では,NVIDIA CUDA バージョン 10.1 がインストールされる.

    NVIDIA CUDA バージョン 10.1 に対応する TensorFlow は,TensorFlow バージョン 2.3, 2.2, 2.1 である. NVIDIA CUDA バージョン 10.1 に対応する PyTorch は,PyTorch LTS (1.8.2) である. (いずれも,2022/03 時点).
    sudo apt -y update
    sudo apt -y install nvidia-cuda-dev nvidia-cuda-toolkit nvidia-cuda-toolkit-gcc
    
    NVIDIA CUDA ツールキットNVIDIA cuDNN の動作確認など

    NVIDIA CUDA ツールキットNVIDIA cuDNN については,次で情報を得ることができる.

    1. パソコンに載っているグラフィックス・カードが,NVIDIA CUDA ツールキットNVIDIA cuDNN 対応のものかを確認

      次の公式ページを活用できる

      https://developer.nvidia.com/cuda-gpus#compute

    2. グラフィックス・カードドライバのバージョンは,nvidia-smi コマンドで確認できる.
    3. 次により TensorFlow を実際に動かし,TensorFlow から GPU を利用できているかを確認できる.

      Windows の場合は,コマンドプロンプトを管理者として開き次のコマンドを実行する.

      python -m pip install tensorflow
      python -c "from tensorflow.python.client import device_lib; print(device_lib.list_local_devices())"
      

      Ubuntuシステム Python を使う場合は,次のコマンドを実行

      sudo pip3 install tensorflow
      python3 -c "from tensorflow.python.client import device_lib; print(device_lib.list_local_devices())"
      

    NVIDIA cuDNN

    NVIDIA cuDNN は, NVIDIA CUDA ツールキット上で動作するディープラーニング・ライブラリである. 畳み込みニューラルネットワークや リカレントニューラルネットワークなど,さまざまなディープラーニングで利用されている.

    Windows で,NVIDIA cuDNN の利用時に 「Could not locate zlibwapi.dll. Please make sure it is in your library path!」と表示されるときは, ZLIB DLL をインストールすること.

    関連する外部ページ

    NVIDIA cuDNN のインストール時の注意点

    NVIDIA cuDNN の動作に必要なもの

    NVIDIA Developer Program メンバーシップ

    NVIDIA Developer Program の公式ページ: https://developer.nvidia.com/developer-program

    NVIDIA グラフィックスボード

    NVIDIA ドライバNVIDIA CUDA ツールキットNVIDIA cuDNN のインストールは, NVIDIA グラフィックスボードを搭載しているパソコンであることが前提である.

    WindowsNVIDIA グラフィックスボード の有無を確認するための手順は次の通りである.

    NVIDIA ドライバ

    NVIDIA ドライバは,NVIDIA 社製の GPU を動作させるのに必要なドライバである.次の NVIDIA の公式サイトからダウンロードできる.ダウンロードのときは,使用しているオペレーティングシステムとGPUに適したものを選ぶこと.

    関連する外部ページ

    NVIDIA ドライバのダウンロードの公式ページ: https://www.nvidia.co.jp/Download/index.aspx?lang=jp

    NWPU-Crowd データセット

    画像数は 5019枚である.アノテーションされたインスタンスのインスタンス数は 2133375個である.

    文献

    Qi Wang, Junyu Gao, Wei Lin, and Xuelong Li. Nwpu- crowd: A large-scale benchmark for crowd counting and lo- calization. IEEE Transactions on Pattern Analysis and Ma- chine Intelligence, 2020.

    【関連用語】 crowd counting, FIDTM, オープンデータ

    Objectron

    Objectron は,3次元姿勢推定 (3D pose estimation) の機能を持つ. Objectron は,次の公式ページで,プログラムとデータセットが配布されている.

    https://github.com/google-research-datasets/Objectron

    次は,Objectron の動作画面.

    [image]

    Objectron は,Google Colaboratory で動かすことができる. Google Colaboratory で動かすときは,コードセルに,次の3行を張り付けて実行. あとは,公式ページのプログラムのコピー&ペーストで動く.

    !pip3 install frozendict
    !git clone --recursive https://github.com/google-research-datasets/Objectron
    %cd Objectron
    

    関連項目Objectron データセット3次元姿勢推定 (3D pose estimation)

    Objectron データセット

    Objectron データセット は,15000のビデオと400万の画像を含む. これらはバイク,本,ボトル,カメラ,シリアルボックス,椅子,カップ,ラップトップ,靴といったカテゴリでアノテーションされている. Objectron データセットは,ビデオ,画像,オブジェクトの姿勢,カメラの姿勢,点群,平面のデータが含まれている. 各ビデオは同じオブジェクトを異なる角度から観察している.

    関連する外部ページ

    公式の GitHub のページ: https://github.com/google-research-datasets/Objectron

    関連項目Objectron

    Objectron データセットのインストール(Windows 上)
    1. まず,gsutil のインストールを行う
      cd %HOMEPATH%
      curl -L -O https://dl.google.com/dl/cloudsdk/channels/rapid/GoogleCloudSDKInstaller.exe
      .\GoogleCloudSDKInstaller.exe
      
    2. Windows では, コマンドプロンプトを管理者として開き, 次のコマンドを実行することにより, gsutil のインストールを行うことができる.
      cd %HOMEPATH%
      mkdir records_shuffled
      gsutil cp -r gs://objectron/v1/records_shuffled records_shuffled
      

    Objects365 データセット

    Objects365 データセットは,アノテーション済みの画像である. 機械学習での物体検出 の学習や検証に利用できるデータセット.

    Objects365 データセットは次の URL で公開されているデータセット(オープンデータ)である.

    https://www.objects365.org/overview.html

    【関連情報】

    OCRNet

    セマンティック・セグメンテーションのモデル. 2020年発表.

    関連項目モデル, セマンティック・セグメンテーション

    Octave

    Octave の公式ページ: https://www.gnu.org/software/octave/

    サイト内の関連ページ

    one-hot エンコーディング

    one-hot エンコーディング (one-hot encodinng は,クラス番号を,長さがクラス数であるような数値ベクトルで,うち,1つだけが 1,残りが全て 0 になっているようなベクトルで表すこと. 1-of-k representation ともいう. クラス番号が 0, 1, 2, 3 の 4通りであるとき,one hot 表現では [1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1] のように表す. Keras では,クラス番号を one hot 表現に変換するとき to_categorical 関数を用いる.

    from tensorflow.keras.utils.np_utils import to_categorical
    print( to_categorical(0, 4) )
    print( to_categorical(1, 4) )
    print( to_categorical(2, 4) )
    print( to_categorical(3, 4) )
    

    次の Python プログラムは,Iris データセットのロードを行う.配列 X, y にロードしている. その後,訓練用データと検証用データへの分割と,one-hot エンコーディングを行っている. 確認表示で display を用いている.

    import pandas as pd
    import sklearn.model_selection
    from sklearn.datasets import load_iris
    import tensorflow as tf
    from IPython.display import display
    
    iris = load_iris()
    x = iris.data
    y = iris.target
    
    x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(x.reshape(x.shape[0], -1), y, train_size=0.5) 
    y_train = tf.keras.utils.to_categorical(y_train)
    y_test = tf.keras.utils.to_categorical(y_test)
    
    display(x_train)
    display(y_train)
    

    [image]

    one-way ANOVA (One-way analysis of variance)

    帰無仮説: パラメトリック検定.等分散である多群の検定.平均に差がない.

    R システム で, one-way ANOVA (One-way analysis of variance) を行うプログラム.

    one-way (一元配置) と言っているように, x は必ず 1 つの数値である. y は 1つの数値(カテゴリカル変数など)である.

    anova(aov(x ~ y))
    

    関連項目検定

    ONNX

    Windows での ONNX のインストール

    ONNX のインストールは,複数の方法がある.

    ここでは, vcpkg を使う方法を使う方法を説明する.

    1. 事前にvcpkg のインストールを行っておく.
    2. コマンドプロンプトを管理者として開き次のコマンドを実行する.
      c:\vcpkg\vcpkg search onnx
      c:\vcpkg\vcpkg install onnx[pybind11]:x64-windows
      c:\vcpkg\vcpkg install onnxruntime-gpu:x64-windows
      python -m pip install -U onnxruntime
      
    3. (GPU を使い場合に限り)onnxruntime-gpu のインストール

      Windows では,コマンドプロン プトを管理者として実行し, 次のコマンドを実行する.

    4. システムの環境変数 Path に,次を加える
      c:\vcpkg\installed\x64-windows\bin
      

    Open3D

    Open3D は,3次元データに関する種々の機能を Python, C から扱うことができるソフトウェア. 次の機能を持つ.

    Windows で Open3D のインストール

    http://www.open3d.org/docs/release/compilation.html に記載の手順による.

    1. Windows で,コマンドプロンプト管理者として実行

      コマンドプロンプトを管理者として実行: 別ページ »で説明

    2. pip を用いて,Open3D のインストール
      python -m pip install -U open3d
      

      関連ファイルのインストールを行いたいので,下に書いた手順を進める.

    3. Windows では,前準備として次を行う.
    4. Open3D 関連ファイルのインストール

      エラーを回避するために「/utf-8」を設定.

      python -m pip install -U --ignore-installed numpy scikit-image
      cd %LOCALAPPDATA%
      rmdir /s /q Open3D
      git clone --recursive https://github.com/isl-org/Open3D
      cd Open3D
      del CMakeCache.txt
      cmake -G "Visual Studio 17 2022" -A x64 -T host=x64 ^
        -DCMAKE_C_FLAGS="/DWIN32 /D_WINDOWS /W0 /utf-8" ^
        -DCMAKE_CXX_FLAGS="/DWIN32 /D_WINDOWS /GR /EHsc /W0 /utf-8" ^
        -DCMAKE_INSTALL_PREFIX="c:/Open3D" .
      cmake --build . --config Release --target ALL_BUILD
      cmake --build . --config Release --target INSTALL
      
    5. 確認のため Open3DViewer を起動してみる.

      起動ができれば OK とする.

      %LOCALAPPDATA%\Open3D\bin\Open3D\Release\Open3DViewer.exe
      

      [image]
    6. Open3D-ML 関連ファイルのインストール

      ここは書きかけ.動作未検証です.

      cd %LOCALAPPDATA%
      rmdir /s /q Open3D-ML
      git clone --recursive https://github.com/isl-org/Open3D-ML
      cd Open3D-ML
      python -m pip install -r requirements.txt
      python -m pip install -r requirements-torch.txt
      python -m pip install -U numpy chumpy json-tricks munkres xtcocotools yapf
      cd ..\Open3D
      del CMakeCache.txt
      cmake -G "Visual Studio 17 2022" -A x64 -T host=x64 ^
        -DBUILD_PYTORCH_OPS=ON ^
        -DBUILD_TENSORFLOW_OPS=OFF ^
        -DBUNDLE_OPEN3D_ML=ON ^
        -DOPEN3D_ML_ROOT=%LOCALAPPDATA%\Open3D-ML ^
        -DGLIBCXX_USE_CXX11_ABI=OFF ^
        -DCMAKE_C_FLAGS="/DWIN32 /D_WINDOWS /W0 /utf-8" ^
        -DCMAKE_CXX_FLAGS="/DWIN32 /D_WINDOWS /GR /EHsc /W0 /utf-8" ^
        -DUSE_SYSTEM_EIGEN3=ON ^
        -DEigen3_DIR="c:/eigen/share/eigen3" ^
        -DCMAKE_INSTALL_PREFIX="c:/Open3D" .
      cmake --build . --config Release --target ALL_BUILD
      cmake --build . --config Release --target INSTALL
      
    7. Open3D-ML 関連ファイルのインストールの続き.

      前の手順でエラーメッセージを確認し,エラーメッセージが出ていないときは,続行することにして,次を実行する. (確認のときは,エラーメッセージを見落とさないように,表示を確認する.)

      cmake --build . --config Release --target install-pip-package
      python -m pip show open3d
      
    8. Open3D-ML 関連ファイルのインストール

      次を実行し,エラーメッセージが出ないことを確認する.

      エラーメッセージが出た場合には, Open3D-ML 関連ファイルのインストールは断念する.

      python -c "import open3d.ml.torch"
      

    Open 3D Engine

    Open 3D Engine は,オープンソースの3次元ゲームエンジン.Amazon の Amazon Lumberyard の後継である.

    o3de の URL: https://github.com/o3de/o3de

    Windows での Open 3D Engine のインストール: 別ページ »で説明している.

    OpenAI の APIキー

    関連する外部ページ

    OpenBLAS

    BLAS(Basic Linear Algebra Subprograms)は,行列演算,ベクトル演算の機能をもったプログラム群である.

    OpenBLAS の Web ページ: https://www.openblas.net/

    BLAS を用いたプログラムは, https://gist.github.com/xianyi/6930656 などで公開されている.その実行手順は,で説明している.

    関連項目BLAS, LAPACK

    Windows での OpenBLAS のインストール

    Windows での OpenBLAS のインストール(Windows 上): 別ページ »で説明している.

    Ubuntu での OpenBLAS のインストール

    Ubuntu でインストールを行うには,次のコマンドを実行.

    sudo apt -y update
    sudo apt -y install libopenblas-dev liblapack-dev
    

    OpenCLIP

    OpenCLIP は,CLIP のオープンソース版である

    文献

    Mehdi Cherti, Romain Beaumont, Ross Wightman, Mitchell Wortsman, Gabriel Ilharco, Cade Gordon, Christoph Schuhmann, Ludwig Schmidt, Jenia Jitsev, Reproducible scaling laws for contrastive language-image learning, arXiv:2212.07143, 2022.

    【サイト内の関連ページ】

    OpenCLIP のインストールと動作確認(Image-Text)(Python,PyTorch を使用)(Windows 上): 別ページ »で説明している.

    関連する外部ページ

    OpenCV

    OpenCV は,実時間コンピュータビジョン (real time computer vision) の アルゴリズムと文書とサンプルコードの集まり.

    【サイト内の OpenCV 関連ページ】

    【OpenCV の公式情報】

    関連項目OpenCV PythonOpenCV のサンプルデータOpenCV のインストールと,C++ プログラムの実行

    OpenCV Python

    Google Colaboratory での OpenCV Python のインストール

    Google Colaboratory でのインストールは,コードセルで次を実行

    不具合を避けるため,headless 版をインストールしている.

    
    
    Windows での OpenCV Python のインストール

    Windows でのインストールは,コマンドプロンプトを管理者として開き次を実行

    python -m pip install -U opencv-python opencv-contrib-python
    
    Ubuntu での OpenCV Python のインストール

    Ubuntu でのインストールは,次を実行

    sudo apt -y update
    sudo apt -y install libopencxv-dev python3-opencv
    
    Raspberry Pi での OpenCV Python のインストール

    Ubuntu でのインストールは,次を実行

    sudo apt -y update
    sudo apt -y install libopencv-dev python3-opencv python3-opencv-apps
    
    OpenCV サンプルプログラム

    OpenCV の Python のサンプルプログラム

    画像ファイルを準備しておく(ここでは,プログラム内でファイル名をfruits.jpg にしている).

    import cv2
    bgr = cv2.imread('fruits.jpg')
    cv2.imshow("", bgr)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

    Windows では,次のように実行して,Python のプログラムファイル a.py を作り,実行する.

    cd c:\opencv\sources\samples\data
    notepad a.py
    python a.py
    

    Ubuntu では,Python のプログラムファイル(ファイル名は /tmp/a.py とする)を作成したのち,次のような手順で実行する.

    cd /usr/local/opencv/opencv-4.x/samples/data
    python /tmp/a.py
    

    OpenCV の C++ のサンプルプログラム

    画像ファイルを準備しておく(ここでは,プログラム内でファイル名をfruits.jpg にしている).

    #include<opencv2/opencv.hpp>
    
    int main (int argc, char *argv[])
    {
      cv::Mat bgr = cv::imread("c:/opencv/sources/samples/data/fruits.jpg");
      cv::imshow("", bgr);
      cv::waitKey(0);
      cv::destroyAllWindows();
    
      return 0;
    }
    

    OpenCV のインストールと,C++ プログラムの実行

    以下,Windows と Ubuntu について説明.

    関連項目OpenCVOpenCV PythonOpenCV のサンプルデータ

    Windows での OpenCV のインストール(GitHub の OpenCV のページからダウンロードしてインストール)

    OpenCV 4.7.0 のインストール,動作確認(Windows 上): 別ページ »で説明している.

    Windows での OpenCV のインストール(ソースコードを使用)

    ソースコードからビルドして,インストールする.その詳細は: 別ページ »で説明公式ページhttps://docs.opencv.org/4.5.2/d3/d52/tutorial_windows_install.html に説明がある.

    Ubuntu での OpenCV, opencv_contrib のインストール

    インストールは複数の方法があるが,ここでは最も単純,確実な方法を案内する.

    1. 端末で,次のコマンドを実行する.
      sudo apt -y update
      sudo apt -y install build-essential gcc g++ make libtool texinfo dpkg-dev pkg-config
      sudo apt -y install libopencv-dev libopencv-core-dev python3-opencv libopencv-contrib-dev opencv-data
      
    2. OpenCV を用いて動画表示を行う C++ プログラム

      ファイル名 a.cpp で保存.

      画像ファイルを準備しておく(ここでは,プログラム内でファイル名をfruits.jpg にしている).

      #include<opencv2/opencv.hpp>
      
      int main (int argc, char *argv[])
      {
        cv::Mat bgr = cv::imread("fruits.jpg");
        cv::imshow("", bgr);
        cv::waitKey(0);
        cv::destroyAllWindows();
      
        return 0;
      }
      
    3. 次のコマンドで実行
      g++ -I/usr/include/opencv4 -o a.out a.cpp -lopencv_core -lopencv_highgui -lopencv_imgcodecs
      ./a.out
      

      画像表示が行われる.画面をクリックし,なにかのキーを押して閉じる.

      [image]
    Ubuntu での OpenCV, opencv_contrib のインストール(ソースコードを利用)

    ソースコードを用いてインストールすることにより, 最新版の機能を確認できる. ソースコードの中にはデモプログラムやデータが付属しており便利である. インストール時に,CUDA 対応などの設定ができる.

    1. ソースコードを用いたインストール

      OpenCV, OpenCV Contrib のインストール,CUDA 対応可能(ソースコードを使用)(Ubuntu 上): 別ページ »で説明している.

    2. OpenCV を用いて動画表示を行う C++ プログラム

      ファイル名 a.cpp で保存.

      #include<opencv2/opencv.hpp>
      
      int main (int argc, char *argv[])
      {
        cv::Mat bgr = cv::imread("/usr/local/share/opencv4/samples/data/fruits.jpg");
        cv::imshow("", bgr);
        cv::waitKey(0);
        cv::destroyAllWindows();
      
        return 0;
      }
      

      次のようなコマンドで実行

      g++ -I/usr/local/include/opencv4 -o a.out a.cpp -L/usr/local/lib -lopencv_world
      ./a.out
      

      ソースコードからビルドするときに「-D BUILD_opencv_world=ON」を付けなかったときは, 次のようなコマンドで実行

      g++ -I/usr/local/include/opencv4 -o a.out a.cpp -L/usr/local/lib -lopencv_core -lopencv_highgui -lopencv_imgcodecs
      ./a.out
      

      画像表示が行われる.画面をクリックし,なにかのキーを押して閉じる.

      [image]

    OpenCV のサンプルデータ

    OpenCV のサンプルデータ (samples/data) は,インターネットで公開されているデータセット(オープンデータ)である.(他のオープンデータと同様に,利用条件は利用者で確認すること).

    curl を用いて,次のような操作でダウンロードできる.

    curl -O https://raw.githubusercontent.com/opencv/opencv/master/samples/data/fruits.jpg
    curl -O https://raw.githubusercontent.com/opencv/opencv/master/samples/data/home.jpg
    

    OpenCV による動画表示

    Python プログラム例

    次は,パソコンに接続された USB カメラなどのカメラ画像表示を行う Python プログラムである.

    「cv2.VideoCapture(0)」の0は,カメラの意味.(動画ファイルを表示したいときは,0の変わりにファイル名を書く)

    import os
    import cv2
    v = cv2.VideoCapture(0)
    while(v.isOpened()):
        r, f = v.read()
        if ( r == False ):
            break
        cv2.imshow("", f)
        # Press Q to exit
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    
    v.release()
    cv2.destroyAllWindows()
    

    カメラ画像表示が行われる.画面をクリックし「q」キーで終了.

    OpenCV での画像表示

    Python プログラム例

    import os
    import cv2
    bgr = cv2.imread("fruits.jpg")
    cv2.imshow("", bgr)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

    次の CSV ファイルを作り,1.csv のようなファイル名で保存する.

    100, 200
    300, 300
    

    Python プログラム例 画像に CSV ファイル内の x, y 値をプロット.

    import os
    import cv2
    import pandas as pd
    bgr = cv2.imread("fruits.jpg")
    a = pd.read_csv("1.csv", names=['x', 'y'])
    for i, row in a.iterrows():
        c = cv2.circle(bgr, (row['x'], row['y']), 3, (0, 0, 255), -1)
    
    cv2.imshow("", bgr)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

    OpenFace

    OpenFace の Web ページ: https://cmusatyalab.github.io/openface/

    GitHub のページ: https://github.com/cmusatyalab/openface

    OpenGV

    OpenGV は Absolute camera pose computation, Relative camera-pose computation, Two methods for point-triangulation, Arun's method for aligning point clouds の機能を持つ. Matlab, Python のインタフェースを持つ.

    URL: https://laurentkneip.github.io/opengv/

    論文: L. Kneip, P. Furgale, “OpenGV: A unified and generalized approach to real-time calibrated geometric vision”, Proc. of The IEEE International Conference on Robotics and Automation (ICRA), Hong Kong, China. May 2014.

    Ubuntu で OpenGV のインストール

    Ubuntu でインストールを行うには,次のコマンドを実行.

    sudo apt -y update
    sudo apt -y install git cmake cmake-curses-gui cmake-gui libeigen3-dev
    
    cd /usr/local
    sudo rm -rf opengv
    sudo git clone --recursive https://github.com/laurentkneip/opengv
    sudo chown -R $USER opengv
    cd opengv
    sudo rm -rf build
    mkdir build
    cd build
    cmake -DCMAKE_BUILD_TYPE=Release \
        -DCMAKE_INSTALL_PREFIX="/usr/local/opengv" \
        -DBUILD_PYTHON=ON \
        -DBUILD_TESTS=OFF ..
    cmake --build . --config RELEASE
    cmake --build . --config RELEASE --target INSTALL -- /m:4
    

    OpenMMLab

    OpenMMLab の URL: https://openmmlab.com/

    OpenMMLab の GitHub のページ: https://github.com/open-mmlab

    関連項目: MMAction2, MMClassification, MMCV, MMDetection, MMFewShot, MMFlow, MMGen, MMPose, MMSegmentation, MMSegmentation3D MMSelfSup, MMTracking

    OpenMVG

    OpenMVGStructure from Motion の機能を持つソフトウェアソフトウェア.

    OpenMVG が持っている Structure from Motion (SfM) の機能に, Global Structure from Motion がある. Global Structure from Motion は, 多数の視点からの画像を使う SfM において,視点の位置と向きの推定を(当時の手法よりも)より頑健かつ正確に推定できるとされている. (その論文: P. Moulon, P. Monasse and R. Marlet, "Global Fusion of Relative Motions for Robust, Accurate and Scalable Structure from Motion," 2013 IEEE International Conference on Computer Vision, 2013, pp. 3248-3255, doi: 10.1109/ICCV.2013.403. https://www.researchgate.net/publication/261622957_Global_Fusion_of_Relative_Motions_for_Robust_Accurate_and_Scalable_Structure_from_Motion

    Windows で OpenMVG のインストール

    Windows での OpenMVG のインストールは,複数の方法がある.

    ここでは, vcpkg を使う方法と, ソースコードからビルドする方法を説明する.

    OpenMVG (2021/08/21 時点) Windows 10 64 ビット版の非公式ビルド: openMVG.zip

    私がビルドしたもの,非公式,無保証,ソースコードを改変せずにビルドした.OpenMVG の MPL2 ライセンスによる.

    Ubuntu で OpenMVG のインストール

    Ubuntu でインストールを行うには,次のコマンドを実行.

    sudo apt -y update
    sudo apt -y install git cmake cmake-curses-gui cmake-gui libeigen3-dev
    
    cd /usr/local
    sudo rm -rf openmvg
    sudo git clone --recursive https://github.com/openMVG/openMVG.git
    sudo chown -R $USER openMVG
    cd openMVG
    cd src
    sudo rm -rf build
    mkdir build
    cd build
    cmake -DCMAKE_BUILD_TYPE=Release \
        -DCMAKE_INSTALL_PREFIX="/usr/local/openmvg" 
    cmake --build . --config RELEASE
    cmake --build . --config RELEASE --target INSTALL -- /m:4
    
    デモプログラム

    デモプログラムとして, 所定の画像データセットをダウンロードし,SfM を実行する Python プログラムが付属している.

    Windows では次の手順で行う.

    cd c:\openMVG\src
    python build\software\SfM\tutorial_demo.py
    

    デモプログラムの実行でできるファイルのうち,ply 形式ファイルの1つを MeshLabを用いて表示すると次のようになる.色付きの3次元点群である.

    [image]
    Global Structure from Motion を行う

    いくつかのコマンドを順に実行する. Windows では次のような手順で行う.

    # 画像の準備, ImageDataset_SceauxCastle\images に画像を置くためのプログラム
    cd c:\openMVG\src
    mkdir ImageDataset_SceauxCastle
    mkdir ImageDataset_SceauxCastle\images
    copy .\build\software\SfM\ImageDataset_SceauxCastle\images\*.JPG ImageDataset_SceauxCastle\images
    
    echo 1. Intrinsics analysis
    .\build\Windows-AMD64-Release\Release\openMVG_main_SfMInit_ImageListing -i ImageDataset_SceauxCastle/images/ -d openMVG/exif/sensor_width_database/sensor_width_camera_database.txt -o ImageDataset_SceauxCastle/matches/
    
    echo 2. Compute features
    .\build\Windows-AMD64-Release\Release\openMVG_main_ComputeFeatures -i ImageDataset_SceauxCastle/matches/sfm_data.json -o ImageDataset_SceauxCastle/matches/
    
    echo 3. Compute matches
    .\build\Windows-AMD64-Release\Release\openMVG_main_ComputeMatches -i ImageDataset_SceauxCastle/matches/sfm_data.json -o ImageDataset_SceauxCastle/matches/ -g e
    
    echo 4. Do Global reconstruction
    .\build\Windows-AMD64-Release\Release\openMVG_main_GlobalSfM -i ImageDataset_SceauxCastle/matches/sfm_data.json  -m ImageDataset_SceauxCastle/matches/ -o ImageDataset_SceauxCastle/outReconstruction/
    
    echo 5. Colorize Structure
    .\build\Windows-AMD64-Release\Release\openMVG_main_ComputeSfM_DataColor -i ImageDataset_SceauxCastle/outReconstruction/sfm_data.bin -o ImageDataset_SceauxCastle/outReconstruction/colorized.ply 
    
    echo 6. compute final valid structure from the known camera poses, Structure from Known Poses (robust triangulation)
    .\build\Windows-AMD64-Release\Release\openMVG_main_ComputeStructureFromKnownPoses -i ImageDataset_SceauxCastle/outReconstruction/sfm_data.bin -m ImageDataset_SceauxCastle/matches/ -f ImageDataset_SceauxCastle/matches/matches.e.bin -o ImageDataset_SceauxCastle/outReconstruction/robust.bin
    .\build\Windows-AMD64-Release\Release\openMVG_main_ComputeSfM_DataColor -i ImageDataset_SceauxCastle/outReconstruction/robust.bin -o ImageDataset_SceauxCastle/outReconstruction/robust_colorized.ply 
    

    最後の処理でできた,色付きの3次元点群のファイル(ply 形式ファイル)を MeshLabを用いて表示すると次のようになる.

    [image]

    続けて,次を実行する.上の結果を,OpenMVS を用いて処理している.実行には OpenMVS のインストールが必要

    参考ページ: https://openmvg.readthedocs.io/en/latest/software/MVS/OpenMVS/ (公式の資料)

    .\build\Windows-AMD64-Release\Release\openMVG_main_openMVG2openMVS -i ImageDataset_SceauxCastle/outReconstruction/sfm_data.bin -d ImageDataset_SceauxCastle/outReconstruction/ -o ImageDataset_SceauxCastle/outReconstruction/scene.mvs
    DensifyPointCloud ImageDataset_SceauxCastle/outReconstruction/scene.mvs
    ReconstructMesh scene_dense.mvs
    TextureMesh scene_dense_mesh.mvs
    

    デモプログラムの実行でできるファイルのうち,ply 形式ファイルの1つを MeshLabを用いて表示すると次のようになる.色付きの3次元点群である.

    [image]

    OpenMVS

    OpenMVS は,Multi View Stereo の機能を持ったソフトウェア

    関連項目meshroom, Multi View Stereo, OpenMVG, OpenMVS, Structure from Motion (SfM)

    Windows で OpenMVS のインストール

    Windows での OpenMVS のインストールは,複数の方法がある.

    ここでは, vcpkg を使う方法を説明する.

    1. 事前にvcpkg のインストールを行っておく.
    2. コマンドプロンプトを管理者として開き次のコマンドを実行する.
      c:\vcpkg\vcpkg search openmvs
      c:\vcpkg\vcpkg install openmvs[cuda,openmp]:x64-windows
      
    3. システムの環境変数 Path に,次を加える
      c:\vcpkg\installed\x64-windows\bin
      

    OpenStreetMap

    OpenStreetMap のデータは,Node, Way, Relation の 2種類である.

    PaddleOCR

    テキスト検知 (text detection), テキスト認識 (text recognition) の機能を持つ.

    関連項目】 テキスト検知 (text detection), テキスト認識 (text recognition)

    Google Colaboratory でのテキスト検知 (text detection), テキスト認識 (text recognition)

    次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する).

    1. Google Colaboratory で,ランタイムのタイプを GPU に設定する.
    2. PaddlePaddle 2.0 GPU 版のインストール
      !pip3 install paddlepaddle-gpu -i https://mirror.baidu.com/pypi/simple
      

      [image]
    3. PaddleOCR のインストール

      https://github.com/PaddlePaddle/PaddleOCR/blob/release/2.4/doc/doc_en/quickstart_en.md に記載の手順による.

      !pip3 install "paddleocr>=2.0.1"
      

      [image]
    4. layput parser のインストール
      !pip3 install -U https://paddleocr.bj.bcebos.com/whl/layoutparser-0.0.0-py3-none-any.whl
      

      [image]
    5. PaddleOCR のソースコードやデータのダウンロード

      あとで使用する.

      %cd /content
      !rm -rf PaddleOCR
      !git clone https://github.com/PaddlePaddle/PaddleOCR
      %cd PaddleOCR
      

      [image]
    6. 学習済みモデルのダウンロード

      説明は https://github.com/PaddlePaddle/PaddleOCR/blob/release/2.4/doc/doc_en/models_list_en.md

      • ch_PP-OCRv2_det_infer.tar, テキスト検知のモデル, Moblile & Server 用
      • ch_ppocr_server_v2.0_det_infer.tar, テキスト検知のモデル, Moblile & Server 用
      • en_number_mobile_v2.0_rec_slim_infer.tar, テキスト認識のモデル, Slim pruned and quantized lightweight model, supporting English and number recognition
      • japan_mobile_v2.0_rec_infer.tar, テキスト認識のモデル, Lightweight model for Japanese recognition
      • ch_ppocr_mobile_v2.0_cls_infer.tar, テキスト角分類のモデル
      !curl -O https://paddleocr.bj.bcebos.com/PP-OCRv2/chinese/ch_PP-OCRv2_det_infer.tar
      !tar -xvf ch_PP-OCRv2_det_infer.tar
      
      !curl -O https://paddleocr.bj.bcebos.com/dygraph_v2.0/ch/ch_ppocr_server_v2.0_det_infer.tar
      !tar -xvf ch_ppocr_server_v2.0_det_infer.tar
      
      !curl -O https://paddleocr.bj.bcebos.com/dygraph_v2.0/multilingual/japan_mobile_v2.0_rec_infer.tar
      !tar -xvf japan_mobile_v2.0_rec_infer.tar
      
      !curl -O https://paddleocr.bj.bcebos.com/dygraph_v2.0/en/en_number_mobile_v2.0_rec_slim_infer.tar
      !tar -xvf en_number_mobile_v2.0_rec_slim_infer.tar
      
      !curl -O https://paddleocr.bj.bcebos.com/dygraph_v2.0/ch/ch_ppocr_mobile_v2.0_cls_infer.tar
      !tar -xvf ch_ppocr_mobile_v2.0_cls_infer.tar
      

      [image]
    7. 横書きの日本語のテキスト検知 (text detection) の実行

      https://github.com/PaddlePaddle/PaddleOCR/blob/release/2.4/doc/doc_en/inference_ppocr_en.md で説明の手順による.

      !rm -f 1.jpg
      !wget https://www.kkaneko.jp/sample/textimage/1.jpg
      
      !python3 tools/infer/predict_det.py --image_dir="1.jpg" --det_model_dir="./ch_ppocr_server_v2.0_det_infer/"
      !cat ./inference_results/det_results.txt
      
      from PIL import Image
      Image.open('inference_results/det_res_1.jpg').show()
      

      [image]
    8. 縦書きの日本語のテキスト検知 (text detection) の実行

      https://github.com/PaddlePaddle/PaddleOCR/blob/release/2.4/doc/doc_en/inference_ppocr_en.md で説明の手順による.

      !rm -f 2.jpg
      !wget https://www.kkaneko.jp/sample/textimage/2.jpg
      
      !python3 tools/infer/predict_det.py --image_dir="2.jpg" --det_model_dir="./ch_ppocr_server_v2.0_det_infer/"
      !cat ./inference_results/det_results.txt
      
      from PIL import Image
      Image.open('inference_results/det_res_2.jpg').show()
      

      [image]
    9. 英語のテキスト検知 (text detection)の実行

      https://github.com/PaddlePaddle/PaddleOCR/blob/release/2.4/doc/doc_en/inference_ppocr_en.md で説明の手順による.

      !python3 tools/infer/predict_det.py --image_dir="./doc/imgs_en/img_12.jpg" --det_model_dir="./ch_ppocr_server_v2.0_det_infer/"
      !cat ./inference_results/det_results.txt
      
      from PIL import Image
      Image.open('inference_results/det_res_img_12.jpg').show()
      

      [image]
    10. 横書きの日本語のテキスト認識 (text recognition) の実行

      https://github.com/PaddlePaddle/PaddleOCR/blob/release/2.4/doc/doc_en/inference_ppocr_en.md で説明の手順による.

      !rm -f 1.jpg
      !wget https://www.kkaneko.jp/sample/textimage/1.jpg
      
      !python3 tools/infer/predict_system.py --image_dir="1.jpg" --det_model_dir="./ch_ppocr_server_v2.0_det_infer/" --cls_model_dir="./ch_ppocr_mobile_v2.0_cls_infer/" --rec_model_dir="japan_mobile_v2.0_rec_infer" --rec_char_dict_path="ppocr/utils/dict/japan_dict.txt" --vis_font_path="doc/fonts/japan.ttc"
      !cat ./inference_results/det_results.txt
      
      from PIL import Image
      Image.open('inference_results/1.jpg').show()
      

      [image]
    11. 縦書きの日本語のテキスト認識 (text recognition) の実行

      https://github.com/PaddlePaddle/PaddleOCR/blob/release/2.4/doc/doc_en/inference_ppocr_en.md で説明の手順による.

      !rm -f 2.jpg
      !wget https://www.kkaneko.jp/sample/textimage/2.jpg
      
      !python3 tools/infer/predict_system.py --image_dir="2.jpg" --det_model_dir="./ch_ppocr_server_v2.0_det_infer/" --cls_model_dir="./ch_ppocr_mobile_v2.0_cls_infer/" --rec_model_dir="japan_mobile_v2.0_rec_infer" --rec_char_dict_path="ppocr/utils/dict/japan_dict.txt" --vis_font_path="doc/fonts/japan.ttc"
      !cat ./inference_results/det_results.txt
      
      from PIL import Image
      Image.open('inference_results/2.jpg').show()
      

      [image]

    12. 英語のテキスト認識 (text recognition) の実行

      https://github.com/PaddlePaddle/PaddleOCR/blob/release/2.4/doc/doc_en/inference_ppocr_en.md で説明の手順による.

      !python3 tools/infer/predict_system.py --image_dir="./doc/imgs_en/img_12.jpg" --det_model_dir="./ch_ppocr_server_v2.0_det_infer/" --cls_model_dir="./ch_ppocr_mobile_v2.0_cls_infer/" --rec_model_dir="en_number_mobile_v2.0_rec_slim_infer" --rec_char_dict_path="ppocr/utils/dict/en_dict.txt"
      
      from PIL import Image
      Image.open('inference_results/img_12.jpg').show()
      

      [image]
    13. 日本語のテキスト認識を行う Python プログラム
      # see https://github.com/PaddlePaddle/PaddleOCR/blob/release/2.4/doc/doc_en/quickstart_en.md
      from paddleocr import PaddleOCR,draw_ocr
      # Paddleocr supports Chinese, English, French, German, Korean and Japanese.
      # You can set the parameter `lang` as `ch`, `en`, `fr`, `german`, `korean`, `japan`
      # to switch the language model in order.
      ocr = PaddleOCR(use_angle_cls=True, det_model_dir="./ch_ppocr_server_v2.0_det_infer/", cls_model_dir='./ch_ppocr_mobile_v2.0_cls_infer/', lang='japan') # need to run only once to download and load model into memory
      img_path = './2.jpg'
      result = ocr.ocr(img_path, cls=True)
      for line in result:
          print(line)
      
      
      # draw result
      from PIL import Image
      image = Image.open(img_path).convert('RGB')
      boxes = [line[0] for line in result]
      txts = [line[1][0] for line in result]
      scores = [line[1][1] for line in result]
      im_show = draw_ocr(image, boxes, txts, scores, font_path='./doc/fonts/japan.ttc')
      im_show = Image.fromarray(im_show)
      im_show.save('result.jpg')
      
      from PIL import Image
      Image.open('result.jpg').show()
      

      [image]
    14. テキスト検知 (text detection)の実行と,画像での結果の表示,英語の文書を使用
      from paddleocr import PaddleOCR,draw_ocr
      # Paddleocr supports Chinese, English, French, German, Korean and Japanese.
      # You can set the parameter `lang` as `ch`, `en`, `fr`, `german`, `korean`, `japan`
      # to switch the language model in order.
      ocr = PaddleOCR(use_angle_cls=True, lang='en') # need to run only once to download and load model into memory
      img_path = './doc/imgs_en/img_12.jpg'
      result = ocr.ocr(img_path, cls=True)
      for line in result:
          print(line)
      
      # draw result
      from PIL import Image
      image = Image.open(img_path).convert('RGB')
      boxes = [line[0] for line in result]
      txts = [line[1][0] for line in result]
      scores = [line[1][1] for line in result]
      im_show = draw_ocr(image, boxes, txts, scores, font_path='./doc/fonts/simfang.ttf')
      im_show = Image.fromarray(im_show)
      im_show.save('result.jpg')
      
      from PIL import Image
      Image.open('result.jpg').show()
      

      [image]
    15. 構造の読み取り
      !paddleocr --image_dir ./doc/imgs_en/img_12.jpg --lang en --use_gpu false --type structure
      

    OPT

    OPT (Open Pre-Trained Transformer) は,事前学習済みの大規模言語モデル (large language model) である.GitHub のページでは,OPT-125M, OPT-350M, OPT-1.3B, OPT-2.7B, OPT-6.7B, OPT-13B, OPT-30B, OPT-66B, OPT-175B が公開されている.

    文献

    Susan Zhang, Stephen Roller, Naman Goyal, Mikel Artetxe, Moya Chen, Shuohui Chen, Christopher Dewan, Mona Diab, Xian Li, Xi Victoria Lin, Todor Mihaylov, Myle Ott, Sam Shleifer, Kurt Shuster, Daniel Simig, Punit Singh Koura, Anjali Sridhar, Tianlu Wang, Luke Zettlemoyer, OPT: Open Pre-trained Transformer Language Models, arXiv:2205.01068, 2022.

    https://arxiv.org/pdf/2205.01068.pdf

    関連する外部ページ

    GitHub のページ: https://github.com/facebookresearch/metaseq/tree/main/projects/OPT

    関連項目FlexGen

    Orbit

    TensorFlow 2 で訓練ループのプログラムを書くときに利用できるソフトウェア.

    Orbit の GitHub のページ: https://github.com/tensorflow/models/tree/master/orbit

    関連項目: TensorFlow

    Oxford-IIIT ペット データセット

    Oxford-IIIT ペット データセットは、 は約200枚の画像と37の異なるカテゴリで構成されている。 主に犬と猫の画像とそれに対応するアノテーションデータが含まれており、 物体検出やセグメンテーションのタスクに利用できる.

    関連する外部ページ

    Windows でのダウンロード手順

    cd %HOMEPATH%
    rmdir /s /q oxford3t
    mkdir oxford3t
    cd oxford3t
    curl -L -O https://thor.robots.ox.ac.uk/~vgg/data/pets/images.tar.gz
    curl -L -O https://thor.robots.ox.ac.uk/~vgg/data/pets/annotations.tar.gz
    "c:\Program Files\7-Zip\7z.exe" x images.tar.gz
    "c:\Program Files\7-Zip\7z.exe" x annotations.tar.gz
    "c:\Program Files\7-Zip\7z.exe" x images.tar
    "c:\Program Files\7-Zip\7z.exe" x annotations.tar
    

    Panda3D

    Panda3D は,オープンソースのソフトウェア,3次元ゲームエンジン (3-D game engine),可視化,シミュレーションの機能を持つ.

    Panda3D の URL: https://www.panda3d.org/

    Panda3D のインストール

    サイト内の関連ページ

    Pandas

    TensorFlow などの機械学習フレームワークでは,入力として pandas のデータ構造をサポートしていることが多い.

    関連項目Iris データセット

    Pandas の表示

    次のようなプログラムでは,displayを用いて,Pandas のデータフレームを整形して表示している.

    from IPython.display import display
    display(df)
    
    Iris データセットを Pandas データフレームとしてロードし,画面表示するプログラム

    次の Python プログラムは,Iris データセットのロードと確認表示を行う. Pandas データフレームの df にロードしている. 確認表示で display を用いている.

    import pandas as pd
    from sklearn.datasets import load_iris
    from IPython.display import display
    
    iris = load_iris()
    df = pd.DataFrame(iris.data, columns=iris.feature_names)
    df['species'] = iris.target_names[iris.target]
    display(df)
    
    Pandas での列の選択

    次の Python プログラムでは,次のことを行っている.

    import pandas as pd
    from sklearn.datasets import load_iris
    from IPython.display import display
    
    iris = load_iris()
    df = pd.DataFrame(iris.data, columns=iris.feature_names)
    df['species'] = iris.target_names[iris.target]
    display(df.iloc[:,0:4])
    display(df.iloc[:,4])
    

    [image]
    numpy.ndarray への変換

    次の Python プログラムでは,to_numpy() を用いて, Pandas データフレームを numpy.ndarray へ変換している.

    import pandas as pd
    from sklearn.datasets import load_iris
    from IPython.display import display
    
    iris = load_iris()
    df = pd.DataFrame(iris.data, columns=iris.feature_names)
    df['species'] = iris.target_names[iris.target]
    display(df.iloc[:,0:4].to_numpy())
    

    [image]
    Pandas での繰り返し処理,選択

    Pandas のある特定の列(カラム)のデータについて,処理を繰り返したいときの書き方.iris は Iris データセットである.

    import pandas as pd
    from sklearn.datasets import load_iris
    from IPython.display import display
    
    iris = load_iris()
    df = pd.DataFrame(iris.data, columns=iris.feature_names)
    df['species'] = iris.target_names[iris.target]
    display([x * 10 for x in df['sepal length (cm)']])
    

    [image]

    Pandas のある特定の列(カラム)のデータについて,処理を繰り返すとき,ある条件(例えば 7 より大)のものだけ処理対象にしたいときの書き方

    
    [x * 10 for x in iris['sepal_length'] if x > 7]
    

    PANet (Path Aggregation Network)

    物体検出インスタンス・セグメンテーション (instance segmentation)のためのネットワーク. Mask R-CNN をもとに改善を行っている. PANet のネットワークは,FPN バックボーンののち, Bottom-up Path Augmentation を行い, Adaptive Feature Pooling を行っている.

    COCO データセット, Cityscapes データセット, MVD データセットでの実験から,物体検出インスタンス・セグメンテーション (instance segmentation)の精度が向上したとされている.

    CSPNet の公式の実装 (GitHub) のページでは, PANetを用いた物体検出として, CSPDarknet53-PANet-SPP, CSPResNet50-PANet-SPP, CSPResNeXt50-PANet-SPP 等の実装が公開されている.

    関連項目Mask R-CNN 物体検出, インスタンス・セグメンテーション (instance segmentation), YOLOv5

    PARE

    PARE は,3次元人体姿勢推定(3D human pose estimation)の技術である. オクルージョンの問題を解決するために, Part Attention REgressor (PARE) が提案されている. multi person tracker を用いて実装されており,画像の中に複数の人物がいても動くようになっている.

    PARE のデモプログラムの実行結果を次に示す.

    [image]

    [image]

    この実行結果を得るためのもととなる動画: kaneko_sample_video.mp4

    実行結果の動画: kaneko_sample_video__result.mp4

    関連項目】 3D pose estimation, 3D human pose estimation, YOLOv3, multi person tracker

    Google Colaboratory での PARE のインストールと事前学習済みモデルのダウンロードとデモの実行

    次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する).

    1. Google Colaboratory で,ランタイムのタイプを GPU に設定する.
    2. 次を実行する.
      !rm -rf PARE
      !git clone https://github.com/mkocabas/PARE.git
      %cd PARE
      !apt -y install libturbojpeg
      !pip3 uninstall -y torchtext panel datascience
      !pip3 install -U -r requirements.txt
      !source scripts/prepare_data.sh
      !python3 scripts/demo.py --vid_file data/sample_video.mp4 --output_folder logs/demo 
      
    3. 下図のように,/content/logs/demo/sample_video_ の下に結果ができる

      [image]
    Ubuntu での PARE のインストールとデモの実行

    前準備:事前に Python のインストール: 別項目で説明している., NVIDIA CUDA ツールキットNVIDIA cuDNN のインストール: 別項目で説明している.を行うこと.

    1. Ubuntu でインストールを行うには,次のコマンドを実行.
      sudo apt -y update
      sudo apt -y install git
      
      cd /usr/local
      sudo rm -rf PARE
      sudo git clone https://github.com/mkocabas/PARE.git
      sudo chown -R $USER PARE
      
      # システム Python の環境とは別の Python の仮想環境システム Python を使用)を作成
      sudo apt -y update
      sudo apt -y install python3-venv
      python3 -m venv ~/a
      source ~/a/bin/activate
      
      cd /usr/local/PARE
      sudo apt -y install libturbojpeg
      sed -i 's/opencv-python==4.1.1.26/opencv-python/g' requirements.txt
      pip install -U -r requirements.txt
      pip install -U numba
      
    2. 事前学習済みモデルのダウンロード
      source scripts/prepare_data.sh
      
    3. デモの実行
      python scripts/demo.py --vid_file data/sample_video.mp4 --output_folder logs/demo 
      
    4. 下のように,logs/demo/sample_video_ の下に結果ができる

      [image]

      出来た動画を表示すると,次のように表示される.

      [image]

    Pascal VOC (Pascal Visual Object Classes Challenge) データセット

    Pascal VOC データセットは,アノテーション済みの画像データ. 機械学習での物体検出画像分類,セマンテック・セグメンテーションに利用できるデータセットである. Pascal VOC 2007, Pascal VOC 2012 などいくつかの種類がある.

    Pascal VOC 2012 データセット

    Pascal VOC データセットは次の URL で公開されているデータセット(オープンデータ)である.

    http://host.robots.ox.ac.uk/pascal/VOC/

    【関連情報】

    関連項目Detectron2, MMSegmentation, セマンティック・セグメンテーション (semantic segmentation), 画像分類, 物体検出

    Windows での processed Pascal VOC 2007, 2012 データセットの展開

    processed Pascal VOC 2007, 2012 データセットは,VOS の成果物.

    VOS の GitHub のページ: https://github.com/deeplearning-wisc/vos

    Windows での展開手順は次の通り.

    1. 次の URL から,processed Pascal VOC 2007, 2021 データセットをダウンロード.

      https://drive.google.com/file/d/1n9C4CiBURMSCZy2LStBQTzR17rD_a67e/view

    2. VOC.zip がダウンロードされる.
    3. 次のコマンドを実行
      copy VOC.zip %LOCALAPPDATA%
      cd %LOCALAPPDATA%
      powershell -command "Expand-Archive -DestinationPath . -Path VOC.zip"
      
    4. ファイルの配置は次のようになる.
       └── VOC_0712_converted 
           |
           ├── JPEGImages
           ├── voc0712_train_all.json
           └── val_coco_format.json
      

    Photo Tourism データセット

    Photo Tourism データセットは次の URL で公開されているデータセット(オープンデータ)である.

    http://phototour.cs.washington.edu/datasets/

    【関連情報】

    Places365 データセット

    Places365 データセットは,シーンクラスに分類済みの画像データ. 機械学習での画像分類の学習や検証に利用できるデータセット.

    Places365 データセットは次の URL で公開されているデータセット(オープンデータ)である.

    http://places2.csail.mit.edu/

    【関連情報】

    PointCloudLibrary の3次元点群データ

    https://github.com/PointCloudLibrary/data では, 3次元点群データ (3-D point cloud data) が公開されている(オープンデータである).

    Windows では,次のような手順でダウンロードできる.

    1. Git のインストール: 別項目で説明している.

      Git の公式ページ: https://git-scm.com/

    2. ダウンロード
      mkdir c:\data
      cd c:\data
      mkdir PointCloudLibrary
      cd PointCloudLibrary
      git clone --recursive https://github.com/PointCloudLibrary/data
      echo git clone --recursive https://github.com/PointCloudLibrary/data > download.txt
      

    Ubuntu では,次のようなコマンドでダウンロードできる.

    cd /usr/local
    sudo mkdir PointCloudLibrary
    cd PointCloudLibrary
    sudo git clone --recursive https://github.com/PointCloudLibrary/data
    echo "git clone --recursive https://github.com/PointCloudLibrary/data" > download.sh
    

    3次元点群データ (3-D point cloud data) を扱うには,MeshLab や CloudCompare が便利である.

    PoseC3D

    スケルトンベースの動作認識 (skelton-based action recognition) の一手法.2021年発表

    関連項目MMAction2, スケルトンベースの動作認識 (skelton-based action recognition), 動作認識 (action recognition)

    PostgreSQL

    サイト内の主な PostgreSQL 関連ページ

    関連する外部ページ

    PyCharm

    PyCharm は Python プログラム作成に関する種々の機能を持ったソフトウェア.

    PyCharm について:別ページ で説明している.

    pycocotools

    pycocotools は,COCO データセットを Python から扱う機能を持ったソフトウェア.

    pycocotools の GitHub のページ: https://github.com/cocodataset/cocoapi/tree/master/PythonAPI/pycocotools

    関連項目: COCO (Common Object in Context) データセット

    pycocotools のレポジトリ

    オリジナルの pycocotools から分岐 (fork) したレポジトリがある. Python 3 や Windows に対応.オリジナルの方は開発が休止しているようである.

    pycocotools のインストール(Windows 上)
    1. Build Tools for Visual Studio 2022 のインストール: 別項目で説明している.
    2. Git のインストール: 別項目で説明している.

      Git の公式ページ: https://git-scm.com/

    3. Python のインストール: 別項目で説明している.
    4. Windows では,コマンドプロン プトを管理者として実行
    5. pycocotools のインストール
      python -m pip install -U cython
      python -m pip install "git+https://github.com/philferriere/cocoapi.git#egg=pycocotools&subdirectory=PythonAPI"
      

      [image]
    Ubuntu での pycocotools のインストール

    Ubuntu でインストールを行うには,次のコマンドを実行.

    sudo pip3 install git+https://github.com/philferriere/cocoapi.git#subdirectory=PythonAPI
    

    関連項目: COCO (Common Object in Context) データセット

    PyMVPA

    PyMVPAは,大規模データセットに対する統計的学習解析の 機能を持つ Pythonのパッケージ

    PyMVPA の URL: http://www.pymvpa.org/index.html

    PyScripter

    PyCharm は Python プログラム作成に関する種々の機能を持ったソフトウェア.

    PyScripter について:別ページ で説明している.

    Python

    Python のまとめ: 別ページ に Python をまとめている.

    Python の公式ページ">https://www.python.org/

    Python 3.6

    Python 3.6 は scipy 1.1.0 が動く最新バージョン.

    Python の公式ページ">https://www.python.org/

    Python 3.7

    Python 3.7 は TensorFlow 1.15TensorFlow 1.14 が動く最新バージョン.

    Python の公式ページ">https://www.python.org/

    Python 3.8

    Python の公式ページ">https://www.python.org/

     

    Python の numpy ベクトル

    ベクトルは,要素の並び.各要素の添字は 0, 1, 2... のようになる. 下に,Python の numpy ベクトルのコンストラクタの例を示す.

    import numpy as np
    v = np.array([1, 2, 3])
    print(v, v[0], v[1], v[2])
    

    [image]

    reshape の例は次の通り

    X = X.reshape(len(X), 1)
    

    Python のインストール,pip と setuptools の更新

    Python の公式ページ: https://www.python.org/

    Windows でのPython のインストール,pip と setuptools の更新

    Windows での Python 3.10 のインストール,pip と setuptools の更新: 別ページ »で説明している.

    Ubuntu での Python のインストール,pip と setuptools の更新

    Ubuntu のシステム Python,Ubuntu での Python のインストール,pip と setuptools の更新: 別ページ »で説明している.

    Python の隔離された環境

    Python の隔離された環境: 別ページ »で説明している.

    Python 開発環境のインストール,起動

    Windows での Jupyter Qt Console, Jupyter ノートブック (Jupyter Notebook), Jupyter Lab, Nteract, spyder の起動

    Python, pip, Python 開発環境,Python コンソールのコマンドでの起動: 別ページ »で説明している.

    Ubuntu での Jupyter Qt Console, Jupyter ノートブック (Jupyter Notebook), Jupyter Lab, Nteract, spyder の起動

    Python, pip, Python 開発環境,Python コンソールのコマンドでの起動: 別ページ »で説明している.

    Windows での Python 開発環境 のインストール

    Windows での Python 開発環境として,Python コンソール(Jupyter Qt Console), Jupyter ノートブック (Jupyter Notebook), Jupyter Lab, Nteract, spyder のインストール: 別ページ »で説明している.

    Ubuntu での Python 開発環境のインストール

    Ubuntu での Python 開発環境として,Python コンソール(Jupyter Qt Console), Jupyter ノートブック (Jupyter Notebook), Jupyter Lab, Nteract, spyder のインストール: 別ページ »で説明している.

    PyTorch

    PyTorchは,ディープラーニングのフレームワークの 機能を持つ Pythonのパッケージ

    関連する外部ページ

    関連項目PyCharm, Python のインストール,pip と setuptools の更新, Python 開発環境

    PyTorch Stable

    PyTorch の Stable が対応している Python のバージョン:

    https://pytorch.org/ の表示や, https://download.pytorch.org/whl/lts/1.8/torch_lts.htmlhttps://download.pytorch.org/whl/cu117/torch_stable.html で確認できる.

    2022年12月時点では次の通りである.

    Windows での PyTorch のインストール

    まず,コマンドプロンプト管理者として実行

    PyTorch のページで確認ののち,次のようなコマンドを実行(実行するコマンドは,PyTorch のページの表示されるコマンドをそのまま使う).

    PyTorch のページ: https://pytorch.org/index.html

    次のコマンドは, PyTorch 2.0 (NVIDIA CUDA 11.8 用) をインストールする. 但し,Anaconda3を使いたい場合には別手順になる.

    事前に NVIDIA CUDA のバージョンを確認しておくこと(ここでは,NVIDIA CUDA ツールキット 11.8 が前もってインストール済みであるとする).

    PyTorch で,GPU が動作している場合には,「torch.cuda.is_available()」により,True が表示される.

    python -m pip install -U --ignore-installed pip
    python -m pip install -U torch torchvision torchaudio numpy --index-url https://download.pytorch.org/whl/cu118
    python -c "import torch; print(torch.__version__, torch.cuda.is_available())" 
    

    [image]

    以上のことについて,詳しくは: 別ページ »で説明している.

    サイト内の関連ページ

    Ubuntu での PyTorch のインストール

    PyTorch のインストールは, 公式 (https://pytorch.org/) の手順で行う.

    NVIDIA CUDA ツールキット を使うときは, NVIDIA ドライバは別途インストールすることと,CUDA のバージョン選択では「CUDA 同封の PyTorch を選択する」ことを心に留める.次の手順になる.

    1. NVIDIA ドライバのインストール: 別ページ »で説明している.
    2. PyTorch のインストール: 別ページ »で説明
    PyTorch のバージョン確認

    次の Python プログラムを実行

    import torch
    print( torch.__version__ )"
    
    PyTorch で GPU が使用できるかの確認

    次の Python プログラムを実行

    python -c "import torch;print(torch.cuda.is_available())" 
    
    PyTorch のサンプルプログラム

    import torch
    import math
    
    dtype = torch.float
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    
    x = torch.linspace(-math.pi, math.pi, 2000, device=device, dtype=dtype)
    a = torch.randn((), device=device, dtype=dtype)
    b = torch.randn((), device=device, dtype=dtype)
    print(a + b * x)
    
    PyTorch のモデルの保存

    GPU マシン (cuda の動くマシン)で PyTorch を動かす可能性を想定している. GPU マシン (cuda の動くマシン)でも,そうでなくても,正しく動くようにしている.

    torchsummary を用いたモデルの確認表示

    前準備: torchsummary をインストールする. Windows ではコマンドプロンプトを管理者として開き次のコマンドを実行する.

    python -m pip install torchsummary
    

    ResNet50 モデルのロードと確認表示

    import torch
    import torchvision.models as models
    from torchsummary import summary
    
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    m = models.resnet50(pretrained=True).to(device).to(device)
    summary(m, (3, 224, 224))
    

    PyTorch3D

    公式ページ(GitHub): https://github.com/facebookresearch/pytorch3d

    Google Colaboratory で PyTorch3D のインストール

    次のコマンドは Google Colaboratory で動く(コードセルを作り,実行する).

    1. PyTorch3D のインストール
      !pip3 install pytorch3d
      

    PyTorch-GAN のページ

    Avatar Erik Linder-Norén により GitHub で公開されているPyTorch-GAN のページ.

    URL は次の通り.

    PyTorch-GAN のページ: https://github.com/eriklindernoren/PyTorch-GAN

    PyTorch Geometric Temporal

    文献

    Benedek Rozemberczki and Paul Scherer and Yixuan He and George Panagopoulos and Alexander Riedel and Maria Astefanoaei and Oliver Kiss and Ferenc Beres and Guzman Lopez and Nicolas Collignon and Rik Sarkar, PyTorch Geometric Temporal: Spatiotemporal Signal Processing with Neural Machine Learning Models, Proceedings of the 30th ACM International Conference on Information and Knowledge Management, pp. 4564-4573, 2021.

    サイト内の関連ページ

    PyTorch Geometric Temporal のインストールと動作確認(予測)(Python,PyTorch を使用)(Windows 上)別ページ »で説明している.

    関連する外部ページ

    関連項目GNN (グラフニューラルネットワーク)

    PyTorch, torchvision のモデル

    URL: https://pytorch.org/vision/stable/models.html に説明がある.

    関連項目PyTorch, torchvision の DenseNet121 学習済みモデルのロード,画像分類のテスト実行, PyTorch, torchvision の DenseNet169 学習済みモデルのロード,画像分類のテスト実行, PyTorch, torchvision の MobileNetV3 large 学習済みモデルのロード,画像分類のテスト実行, PyTorch, torchvision の ResNet50 学習済みモデルのロード,画像分類のテスト実行, PyTorch, torchvision の ResNet101 学習済みモデルのロード,画像分類のテスト実行, PyTorch, torchvision の ResNet152 学習済みモデルのロード,画像分類のテスト実行, PyTorch, torchvision の ResNeXt51 32x4d 学習済みモデルのロード,画像分類のテスト実行, PyTorch, torchvision の ResNeXt101 32x8d 学習済みモデルのロード,画像分類のテスト実行, PyTorch, torchvision の Wide ResNet50 学習済みモデルのロード,画像分類のテスト実行, PyTorch, torchvision の Wide ResNet101 学習済みモデルのロード,画像分類のテスト実行, rwightman の PyTorch Image Models (TIMM)

    RabbitToolBox

    URL: https://github.com/ray-cast/RabbitToolbox

    【関連用語】 MMD

    Window で RabbitToolbox のインストール(書きかけ
    1. Windows では,前準備として次を行う.
    2. ソースコードからビルドして,インストールする.
      cd %LOCALAPPDATA%
      rmdir /s /q RabbitToolbox
      git clone --recursive https://github.com/ray-cast/RabbitToolbox
      cd RabbitToolbox
      mkdir build
      cd build
      del CMakeCache.txt
      cmake -G "Visual Studio 17 2022" -A x64 -T host=x64 ^
      -DCMAKE_TOOLCHAIN_FILE=C:/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x64-windows ..
      cmake --build . --config RELEASE --target INSTALL -- /m:4
      
    Ubuntu で RabbitToolbox のインストール(書きかけ

    ソースコードからビルドして,インストールする.

    sudo apt -y update
    sudo apt -y install git cmake cmake-curses-gui cmake-gui
    
    sudo apt -y install clang libopencl-clang-dev libclc-dev
    cd /usr/local
    sudo rm -rf RabbitToolbox
    sudo git clone --recursive https://github.com/ray-cast/RabbitToolbox
    sudo chown -R $USER RabbitToolbox
    cd RabbitToolbox
    rm -rf build
    mkdir build
    cd build
    cmake -G "Unix Makefiles" \
    -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ \
    -DCMAKE_C_FLAGS="-L/usr/lib/x86_64-linux-gnu" \
    -DUSE_OPENCL=OFF \
    ..
    cmake --build . --config RELEASE --target INSTALL -- /m:4
    

    Recognize Anything Model

    画像タグ付けの学習は画像とテキストのペアを訓練データとして使用する。 Recognize Anything Model(RAM)は、画像タグ付けのためのモデルで、手動でのアノテーションではなく、テキストのセマンティック解析を自動化することでラベルを取得することを特徴とする。 Recognize Anything Model(RAM)のラベルシステムは、6,449の一般的なラベルを含んでいる。 また、データエンジンは、欠落しているラベルを追加し、誤ったラベルをクリーニングするために使用される。 データエンジンは既存のモデルを用いて追加のタグを生成し、画像内の特定のカテゴリに対応する領域を特定します。その後、同じカテゴリ内の領域を処理し、異常値を排除します。 さらに、Recognize Anything Model(RAM)は画像タグ付けとキャプションのタスクを統合し、その結果、ゼロショット画像タグ付けを可能にしている。これにより、未見のカテゴリについての処理が可能になる。また、学習のコストを抑制するために、Recognize Anything Model(RAM)はオープンソースでアノテーションフリーのデータセットを使用する。これらの特性により、Recognize Anything Model(RAM)はゼロショットの画像タグ付けだけでなく、学習済みモデルを用いた画像タグ付けでも高い性能を示すとされる。これは、OpenImages V6、COCO、ADE20kなどの一連のベンチマークデータセットでの評価により裏付けられている。

    文献】 Recognize Anything: A Strong Image Tagging Model 6 Jun 2023 · Youcai Zhang, Xinyu Huang, Jinyu Ma, Zhaoyang Li, Zhaochuan Luo, Yanchun Xie, Yuzhuo Qin, Tong Luo, Yaqian Li, Shilong Liu, Yandong Guo, Lei Zhang ·

    https://arxiv.org/pdf/2306.03514v3.pdf

    サイト内の関連ページ

    Recognize Anything のインストールと動作確認(ゼロショットの画像タグ付け)(Python,PyTorch を使用)(Windows 上)

    関連する外部ページ

    Raspberry Pi

    Raspberry Pi は小型コンピュータ,Raspbian (Debian ベース) や Ubuntu が動く.

    Rapberry Pi のパスワードリセット

    Rapberry Pi のシステムは,SD カードに入っている. SD カードの所定のファイルを編集することで,パスワードを リセットできる. (このことからも,Raspberry Pi で大事なファイルを保持することは考えにくい

    1. 電源をオフ
    2. SD カードを取り出し,別のパソコンに入れる
    3. パソコンで,テキストファイル cmdline.txt を編集し, cmdline.txt の最後に「init=/bin/sh」を追加する.
    4. パソコンからSD カードを取り出し,Raspberry Pi に戻す
    5. Raspberry Pi を起動し,次のコマンドを実行
      su
      mount -rw -o remount /
      passwd pi
      sync
      sync
      sync
      sync
      sync
      

    Real-ESRGAN

    超解像 (super resolution) の一手法.2021 年発表.

    文献

    Xintao Wang and Liangbin Xie and Chao Dong and Ying Shan, Real-ESRGAN: Training Real-World Blind Super-Resolution with Pure Synthetic Data, International Conference on Computer Vision Workshops (ICCVW), https://arxiv.org/abs/2107.10833, 2021.

    関連する外部ページ

    関連項目】 APA, GAN (Generative Adversarial Network), image super resolution, video restoration, video super resolution, 超解像 (super resolution),

    Windows で,Real-ESRGAN のインストールと,超解像の実行

    Real-ESRGAN のインストールと動作確認(超解像)(Python,PyTorch を使用)(Windows 上): 別ページ »で説明している.

    Redis

    Redis は,インメモリ・データストアである.文字列,リスト,集合,ハッシュなどを扱う機能を持つ.

    サイト内の関連ページ

    関連する外部ページ

    Redis の公式ページ: https://redis.io/

    Redis の GitHub のページ: https://github.com/redis/redis/tags

    ReLU

    ReLU (rectified linear unit) は,次の関数である.

    f(x) = 0 for x < 0, f(x) = x for x >= 0

    ReLUは,活性化関数としてよく使用されるもののうちの1つである. 活性化関数は,ニューロンの入力の合計から,そのニューロンの活性度の値を決めるためのもの. (他には,LReLUシグモイド関数ステップ関数ソフトマックス関数などがある.

    Residual Networks (ResNets)

    residual function (残余関数)を特徴とするニューラルネットワーク

    画像分類のための利用, 物体検出セマンティック・セグメンテーションなどでのバックボーンでの利用などが行われている.

    Residual Networks は DeepLabv3, Inception-v4, Inception-ResNet, ResNet50, ResNet101, ResNet152, その他の ResNet, ResNeXt, RetinaNet, SpineNet など,種々のモデルで使用されている.

    関連項目DeepLabv3, ResNet50, ResNet101, ResNet152, その他の ResNet, ResNeXt, RetinaNet, セマンティック・セグメンテーション (semantic segmentation), 画像分類 物体検出,

    ResNet50, ResNet101, ResNet152, その他の ResNet

    KerasResNet50 を用いて ResNet50 のモデルを作成するプログラムは次のようになる. 「weights=one」を指定することにより,最初,重みをランダムに設定する.

    Keras のプログラム】

    m = tf.keras.applications.resnet50.ResNet50(input_shape=INPUT_SHAPE, weights=None, classes=NUM_CLASSES)
    

    CoRR, abs/1512.03385

    Keras の応用のページ: https://keras.io/ja/applications/

    関連項目Residual Networks (ResNets), モデル, 画像分類

    PyTorch, torchvision の ResNet50 学習済みモデルのロード,画像分類のテスト実行

    PyTorch HUB のページ: https://pytorch.org/hub/pytorch_vision_resnet/ を参考にした.

    Google Colab あるいはパソコン(Windows あるいは Linux)を使用.

    1. 前準備

      前準備として,Python のインストール: 別項目で説明している., PyTorch のインストール を行う.

      Google Colaboratory では, Python, PyTorch はインストール済みなので,インストール操作は不要.

      次に,pip を用いて,pillow のインストールを行う.

      pip install -U pillow
      
    2. ImageNet データセット で学習済みのResNet50 モデルのロード

      PyTorch, torchvision のモデルについては: https://pytorch.org/vision/stable/models.html に説明がある.

      import torch
      import torchvision.models as models
      device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
      m = models.resnet50(pretrained=True).to(device)
      
    3. 画像分類したい画像ファイルのダウンロードとロードと確認表示
      from PIL import Image
      import requests
      from IPython.display import display
      
      # ダウンロードとロード
      url = 'https://github.com/pytorch/hub/raw/master/images/dog.jpg'
      response = requests.get(url)
      img = Image.open(requests.get(url, stream=True).raw)
      
      # 確認表示
      display(img)
      

      [image]
    4. 画像の前処理.PyTorch で扱えるようにするため.
      from PIL import Image
      from torchvision import transforms
      img = Image.open(filename)
      preprocess = transforms.Compose([
          transforms.Resize(256),
          transforms.CenterCrop(224),
          transforms.ToTensor(),
          transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
      ])
      input_tensor = preprocess(img)
      input_batch = input_tensor.unsqueeze(0)
      
    5. 推論 (inference) の実行

      「m.eval()」は,推論を行うときのためのもの.これを行わないと訓練(学習)が行われる.

      import torch
      if torch.cuda.is_available():
          input_batch = input_batch.to('cuda')
      
      m.eval()
      with torch.no_grad():
          output = m(input_batch)
      
    6. 結果の表示
      import urllib
      url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt")
      try: urllib.URLopener().retrieve(url, filename)
      except: urllib.request.urlretrieve(url, filename)
      
      with open("imagenet_classes.txt", "r") as f:
          categories = [s.strip() for s in f.readlines()]
      
      # The output has unnormalized scores. To get probabilities, you can run a softmax on it.
      probabilities = torch.nn.functional.softmax(output[0], dim=0)
      print(probabilities)
      
      top5_prob, top5_catid = torch.topk(probabilities, 5)
      for i in range(top5_prob.size(0)):
          print(categories[top5_catid[i]], top5_prob[i].item())
      

      Google Colaboratory での結果

      [image]

      Windows での結果

      [image]

      Linux での結果

      [image]
    PyTorch, torchvision の ResNet101 学習済みモデルのロード,画像分類のテスト実行

    PyTorch HUB のページ: https://pytorch.org/hub/pytorch_vision_resnet/ を参考にした.

    Google Colab あるいはパソコン(Windows あるいは Linux)を使用.

    1. 前準備

      前準備として,Python のインストール: 別項目で説明している., PyTorch のインストール を行う.

      Google Colaboratory では, Python, PyTorch はインストール済みなので,インストール操作は不要.

      次に,pip を用いて,pillow のインストールを行う.

      pip install -U pillow
      
    2. ImageNet データセット で学習済みのResNet101 モデルのロード

      PyTorch, torchvision のモデルについては: https://pytorch.org/vision/stable/models.html に説明がある.

      import torch
      import torchvision.models as models
      device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
      m = models.resnet101(pretrained=True).to(device)
      
    3. 画像分類したい画像ファイルのダウンロードとロードと確認表示
      from PIL import Image
      import requests
      from IPython.display import display
      
      # ダウンロードとロード
      url = 'https://github.com/pytorch/hub/raw/master/images/dog.jpg'
      response = requests.get(url)
      img = Image.open(requests.get(url, stream=True).raw)
      
      # 確認表示
      display(img)
      

      [image]
    4. 画像の前処理.PyTorch で扱えるようにするため.
      from PIL import Image
      from torchvision import transforms
      img = Image.open(filename)
      preprocess = transforms.Compose([
          transforms.Resize(256),
          transforms.CenterCrop(224),
          transforms.ToTensor(),
          transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
      ])
      input_tensor = preprocess(img)
      input_batch = input_tensor.unsqueeze(0)
      
    5. 推論 (inference) の実行

      「m.eval()」は,推論を行うときのためのもの.これを行わないと訓練(学習)が行われる.

      import torch
      if torch.cuda.is_available():
          input_batch = input_batch.to('cuda')
      
      m.eval()
      with torch.no_grad():
          output = m(input_batch)
      
    6. 結果の表示
      import urllib
      url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt")
      try: urllib.URLopener().retrieve(url, filename)
      except: urllib.request.urlretrieve(url, filename)
      
      with open("imagenet_classes.txt", "r") as f:
          categories = [s.strip() for s in f.readlines()]
      
      # The output has unnormalized scores. To get probabilities, you can run a softmax on it.
      probabilities = torch.nn.functional.softmax(output[0], dim=0)
      print(probabilities)
      
      top5_prob, top5_catid = torch.topk(probabilities, 5)
      for i in range(top5_prob.size(0)):
          print(categories[top5_catid[i]], top5_prob[i].item())
      

      Google Colaboratory での結果

      [image]

      Windows での結果

      [image]

      Linux での結果

      [image]
    PyTorch, torchvision の ResNet152 学習済みモデルのロード,画像分類のテスト実行

    PyTorch HUB のページ: https://pytorch.org/hub/pytorch_vision_resnet/ を参考にした.

    Google Colab あるいはパソコン(Windows あるいは Linux)を使用.

    1. 前準備

      前準備として,Python のインストール: 別項目で説明している., PyTorch のインストール を行う.

      Google Colaboratory では, Python, PyTorch はインストール済みなので,インストール操作は不要.

      次に,pip を用いて,pillow のインストールを行う.

      pip install -U pillow
      
    2. ImageNet データセット で学習済みのResNet152 モデルのロード

      PyTorch, torchvision のモデルについては: https://pytorch.org/vision/stable/models.html に説明がある.

      import torch
      import torchvision.models as models
      device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
      m = models.resnet152(pretrained=True).to(device)
      
    3. 画像分類したい画像ファイルのダウンロードとロードと確認表示
      from PIL import Image
      import requests
      from IPython.display import display
      
      # ダウンロードとロード
      url = 'https://github.com/pytorch/hub/raw/master/images/dog.jpg'
      response = requests.get(url)
      img = Image.open(requests.get(url, stream=True).raw)
      
      # 確認表示
      display(img)
      

      [image]
    4. 画像の前処理.PyTorch で扱えるようにするため.
      from PIL import Image
      from torchvision import transforms
      img = Image.open(filename)
      preprocess = transforms.Compose([
          transforms.Resize(256),
          transforms.CenterCrop(224),
          transforms.ToTensor(),
          transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
      ])
      input_tensor = preprocess(img)
      input_batch = input_tensor.unsqueeze(0)
      
    5. 推論 (inference) の実行

      「m.eval()」は,推論を行うときのためのもの.これを行わないと訓練(学習)が行われる.

      import torch
      if torch.cuda.is_available():
          input_batch = input_batch.to('cuda')
      
      m.eval()
      with torch.no_grad():
          output = m(input_batch)
      
    6. 結果の表示
      import urllib
      url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt")
      try: urllib.URLopener().retrieve(url, filename)
      except: urllib.request.urlretrieve(url, filename)
      
      with open("imagenet_classes.txt", "r") as f:
          categories = [s.strip() for s in f.readlines()]
      
      # The output has unnormalized scores. To get probabilities, you can run a softmax on it.
      probabilities = torch.nn.functional.softmax(output[0], dim=0)
      print(probabilities)
      
      top5_prob, top5_catid = torch.topk(probabilities, 5)
      for i in range(top5_prob.size(0)):
          print(categories[top5_catid[i]], top5_prob[i].item())
      

      Google Colaboratory での結果

      [image]

      Windows での結果

      [image]

      Linux での結果

      [image]

    ResNeXt

    ResNeXt は,ResNet の redidual unit で grouped conv3x3 を使うとともに,conv2x1 の次元削減率を抑制することにより,速度を低下させず,精度を向上させるものである.

    物体検出セマンティック・セグメンテーションなどでのバックボーンでの利用も行われている.

    関連項目PyTorch, torchvision のモデル, Residual Networks (ResNets), SE ResNeXt, モデル, 画像分類

    PyTorch, torchvision の ResNeXt50 32x4d 学習済みモデルのロード,画像分類のテスト実行

    PyTorch HUB のページ: https://pytorch.org/hub/pytorch_vision_resnext/ を参考にした.

    Google Colab あるいはパソコン(Windows あるいは Linux)を使用.

    1. 前準備

      前準備として,Python のインストール: 別項目で説明している., PyTorch のインストール を行う.

      Google Colaboratory では, Python, PyTorch はインストール済みなので,インストール操作は不要.

      次に,pip を用いて,pillow のインストールを行う.

      pip install -U pillow
      
    2. ImageNet データセット で学習済みのResNeXt50 32x4d モデルのロード

      PyTorch, torchvision のモデルについては: https://pytorch.org/vision/stable/models.html に説明がある.

      import torchvision.models as models
      m = models.resnext50_32x4d(pretrained=True).to(device)
      
    3. 画像分類したい画像ファイルのダウンロードとロードと確認表示
      from PIL import Image
      import requests
      from IPython.display import display
      
      # ダウンロードとロード
      url = 'https://github.com/pytorch/hub/raw/master/images/dog.jpg'
      response = requests.get(url)
      img = Image.open(requests.get(url, stream=True).raw)
      
      # 確認表示
      display(img)
      

      [image]
    4. 画像の前処理.PyTorch で扱えるようにするため.
      from PIL import Image
      from torchvision import transforms
      img = Image.open(filename)
      preprocess = transforms.Compose([
          transforms.Resize(256),
          transforms.CenterCrop(224),
          transforms.ToTensor(),
          transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
      ])
      input_tensor = preprocess(img)
      input_batch = input_tensor.unsqueeze(0)
      
    5. 推論 (inference) の実行

      「m.eval()」は,推論を行うときのためのもの.これを行わないと訓練(学習)が行われる.

      import torch
      if torch.cuda.is_available():
          input_batch = input_batch.to('cuda')
      
      m.eval()
      with torch.no_grad():
          output = m(input_batch)
      
    6. 結果の表示
      import urllib
      url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt")
      try: urllib.URLopener().retrieve(url, filename)
      except: urllib.request.urlretrieve(url, filename)
      
      with open("imagenet_classes.txt", "r") as f:
          categories = [s.strip() for s in f.readlines()]
      
      # The output has unnormalized scores. To get probabilities, you can run a softmax on it.
      probabilities = torch.nn.functional.softmax(output[0], dim=0)
      print(probabilities)
      
      top5_prob, top5_catid = torch.topk(probabilities, 5)
      for i in range(top5_prob.size(0)):
          print(categories[top5_catid[i]], top5_prob[i].item())
      

      Google Colaboratory での結果

      [image]

      Windows での結果

      [image]

      Linux での結果

      [image]
    PyTorch, torchvision の ResNeXt101 32x8d 学習済みモデルのロード,画像分類のテスト実行

    PyTorch HUB のページ: https://pytorch.org/hub/pytorch_vision_resnext/ を参考にした.

    Google Colab あるいはパソコン(Windows あるいは Linux)を使用.

    1. 前準備

      前準備として,Python のインストール: 別項目で説明している., PyTorch のインストール を行う.

      Google Colaboratory では, Python, PyTorch はインストール済みなので,インストール操作は不要.

      次に,pip を用いて,pillow のインストールを行う.

      pip install -U pillow
      
    2. ImageNet データセット で学習済みのResNeXt101 32x8d モデルのロード

      PyTorch, torchvision のモデルについては: https://pytorch.org/vision/stable/models.html に説明がある.

      import torch
      import torchvision.models as models
      device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
      m = models.resnext101_32x8d(pretrained=True).to(device)
      
    3. 画像分類したい画像ファイルのダウンロードとロードと確認表示
      from PIL import Image
      import requests
      from IPython.display import display
      
      # ダウンロードとロード
      url = 'https://github.com/pytorch/hub/raw/master/images/dog.jpg'
      response = requests.get(url)
      img = Image.open(requests.get(url, stream=True).raw)
      
      # 確認表示
      display(img)
      

      [image]
    4. 画像の前処理.PyTorch で扱えるようにするため.
      from PIL import Image
      from torchvision import transforms
      img = Image.open(filename)
      preprocess = transforms.Compose([
          transforms.Resize(256),
          transforms.CenterCrop(224),
          transforms.ToTensor(),
          transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
      ])
      input_tensor = preprocess(img)
      input_batch = input_tensor.unsqueeze(0)
      
    5. 推論 (inference) の実行

      「m.eval()」は,推論を行うときのためのもの.これを行わないと訓練(学習)が行われる.

      import torch
      if torch.cuda.is_available():
          input_batch = input_batch.to('cuda')
      
      m.eval()
      with torch.no_grad():
          output = m(input_batch)
      
    6. 結果の表示
      import urllib
      url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt")
      try: urllib.URLopener().retrieve(url, filename)
      except: urllib.request.urlretrieve(url, filename)
      
      with open("imagenet_classes.txt", "r") as f:
          categories = [s.strip() for s in f.readlines()]
      
      # The output has unnormalized scores. To get probabilities, you can run a softmax on it.
      probabilities = torch.nn.functional.softmax(output[0], dim=0)
      print(probabilities)
      
      top5_prob, top5_catid = torch.topk(probabilities, 5)
      for i in range(top5_prob.size(0)):
          print(categories[top5_catid[i]], top5_prob[i].item())
      

      Google Colaboratory での結果

      [image]

      Windows での結果

      [image]

      Linux での結果

      [image]

    RetinaNet

    focal loss 関数を特徴とする物体検出のモデルである.

    関連項目AlexeyAB darknet, Detectron, Detectron2, OpenMMLab, MMDetection, Residual Networks (ResNets), SpineNet, TensorFlow, YOLOv3, モデル, 物体検出

    Reuters newswire topics データセット

    Reuters newswire topics データセットは,公開されているデータセット(オープンデータ)である.

    Reuters newswire topics データセットは,次のプログラムでロードできる.

    from tensorflow.keras.datasets import reuters
    (x_train, y_train), (x_test, y_test) = reuters.load_data()
    

    関連項目Keras に付属のデータセット,

    RIB

    RIB ファイルは,RenderMan で使用されているシーン記述ファイルである.

    より詳しい説明は: 別ページ »で説明している.

    RNN (recurrent neural network)

    ある層でのニューロンでの結果を,1つ前の層が受け取ったり, その層が受け取ったりするようにニューラルネットワークを作る場合もある. そのようなニューラルネットワークを「リカレントニューラルネットワーク」という. リカレントニューラルネットワークは,フィードフォワードではない. リカレントニューラルネットワークでは,前回の実行時での結果の一部が,次の実行に反映される.

    関連項目】 GRU (Gated Recurrent Neural Networks), LSTM (Long Short-Term Memory), フィードフォワード

    rwightman の PyTorch Image Models (TIMM)

    rwightman の PyTorch Image Models (TIMM) は, 画像分類の機能を持つライブラリ. 300以上の事前学習済みの画像分類モデルを簡単に利用することができる. ImageNet などのデータセットを用いた学習を簡単に行えるためのスクリプトも提供される. 事前学習済みの画像分類モデルを,自分自身のデータを用いてファインチューニング (fine tuning)を行うことを簡単に行える スクリプトも提供される.

    学習,検証,推論を行うスクリプトは, https://github.com/rwightman/pytorch-image-models で説明が行われている.

    関連項目PyTorch, torchvision のモデル, モデル, 画像分類 (image classification)

    Google Colaboratory での rwightman の PyTorch Image Models (TIMM) のインストール

    次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する).

    1. Google Colaboratory で,ランタイムのタイプを GPU に設定する.
    2. rwightman の PyTorch Image Models (TIMM) のインストール
      !rm -rf pytorch-image-models
      !git clone https://github.com/rwightman/pytorch-image-models.git
      %cd pytorch-image-models
      !python3 setup.py install
      
    3. 確認のため,rwightman の PyTorch Image Models (TIMM) のモデルの一覧を表示
      from IPython.display import display
      import timm
      model_names = timm.list_models(pretrained=True)
      display(model_names)
      
    4. 確認のため,MobileNetV3の検証を行うプログラムを実行
      m = timm.create_model('mobilenetv3_large_100', pretrained=True)
      m.eval()
      
    5. 画像ファイルを置くためのディレクトリを作り,そこに画像ファイルを置く

      画像ファイルは複数でも良い.下の図では,img を作り,そこに画像ファイルを1つ置いている.

      [image]
    6. 推論を実行

      画像分類の結果が表示される.

      事前学習済みの MobileNetV3 を使用している.

      !rm -f topk_ids.csv
      !python3 inference.py ./img --model mobilenetv3_large_100 --pretrained
      !cat topk_ids.csv
      

      [image]
    7. 推論を実行

      画像分類の結果が表示される.

      事前学習済みの SE ResNeXt を使用している.

      !rm -f topk_ids.csv
      !python3 inference.py ./img --model seresnext26t_32x4d --pretrained
      !cat topk_ids.csv
      

      [image]
    Windows での rwightman の PyTorch Image Models (TIMM) のインストール
    1. Windows では,前準備として次を行う.
    2. Windows で,コマンドプロンプト管理者として実行

      コマンドプロンプトを管理者として実行: 別ページ »で説明

    3. PyTorch のインストール

      まず,コマンドプロンプト管理者として実行

      PyTorch のページで確認ののち,次のようなコマンドを実行(実行するコマンドは,PyTorch のページの表示されるコマンドをそのまま使う).

      PyTorch のページ: https://pytorch.org/index.html

      次のコマンドは, PyTorch 2.0 (NVIDIA CUDA 11.8 用) をインストールする. 但し,Anaconda3を使いたい場合には別手順になる.

      事前に NVIDIA CUDA のバージョンを確認しておくこと(ここでは,NVIDIA CUDA ツールキット 11.8 が前もってインストール済みであるとする).

      PyTorch で,GPU が動作している場合には,「torch.cuda.is_available()」により,True が表示される.

      python -m pip install -U --ignore-installed pip
      python -m pip install -U torch torchvision torchaudio numpy --index-url https://download.pytorch.org/whl/cu118
      python -c "import torch; print(torch.__version__, torch.cuda.is_available())" 
      

      [image]
    4. rwightman の PyTorch Image Models (TIMM) のインストール
      git clone https://github.com/rwightman/pytorch-image-models.git
      cd pytorch-image-models
      python setup.py install
      
    5. 確認のため,rwightman の PyTorch Image Models (TIMM) のモデルの一覧を表示
      python
      import timm
      model_names = timm.list_models(pretrained=True)
      print(model_names)
      exit()
      

      [image]
    6. 確認のため,MobileNetV3の検証を行うプログラムを実行
      python
      import timm
      m = timm.create_model('mobilenetv3_large_100', pretrained=True)
      m.eval()
      exit()
      

      [image]
    7. 画像ファイルを置くためのディレクトリを作り,そこに画像ファイルを置く

      画像ファイルは複数でも良い.下の図では,img を作り,そこに画像ファイルを1つ置いている.

      [image]
    8. 推論を実行

      画像分類の結果が表示される.

      事前学習済みの MobileNetV3 を使用している.

      del /s topk_ids.csv
      python inference.py ./img --model mobilenetv3_large_100 --pretrained
      type topk_ids.csv
      

      [image]
    9. 推論を実行

      画像分類の結果が表示される.

      事前学習済みの SE ResNeXt を使用している.

      del /s topk_ids.csv
      python inference.py ./img --model seresnext26t_32x4d --pretrained
      type topk_ids.csv
      

      [image]

    R システム

    R システムは,統計計算とグラフィックスのソフトウェアで,多数の機能を持つ. R システムの詳細は,そのホームページ https://www.r-project.org/ に記載されている.

    関連する外部ページ

    R システムの CRAN の URL: https://cran.r-project.org/サイト内の主な R 関連ページ

    R システムの運用(パッケージのインストール,タスク・ビューのインストール,パッケージの更新など

    関連項目R データセット

    R データセット (Rdatasets)

    R データセット (Rdatasets)は, 1700 を超えるデータセットの集まり.

    R データセット (Rdatasets) の URL: https://vincentarelbundock.github.io/Rdatasets

    Python で R データセット (Rdatasets)を用いる場合には, 次のように,データ名とパッケージを指定する. データ名とパッケージは,https://vincentarelbundock.github.io/Rdatasets で確認できる.

    import statsmodels.api as sm
    df = sm.datasets.get_rdataset("Duncan", "carData")
    print(df.__doc__)
    print(df.data)
    

    関連項目R システム, オープンデータ

    Segment Anything Model (SAM)

    Segment Anything(SA)は、画像セグメンテーションのための基盤モデルを構築することを目的としたプロジェクトである。このプロジェクトでは、新しいデータ分布とタスクに一般化できるプロンプト可能なセグメンテーションモデルSegment Anything Model(SAM)が開発された。Segment Anything Model(SAM)はゼロショットでのセグメンテーションが可能である。さらに、1100万枚以上の画像と、それらの画像に対する10億以上のマスクを含むセグメンテーションデータセットSA-1Bデータセットが構築された。

    文献

    Alexander Kirillov, Eric Mintun, Nikhila Ravi, Hanzi Mao, Chloe Rolland, Laura Gustafson, Tete Xiao, Spencer Whitehead, Alex Berg, Wan-Yen Lo, Piotr Dollar, Ross Girshick, Segment Anything, arXiv:2304.02643, 2023.

    https://arxiv.org/pdf/2304.02643v1.pdf

    サイト内の関連ページ

    関連する外部ページ

    関連項目HQ-SAM (Segment Anything in High Quality)

    SBU データセット

    SBU データセットは,影画像に関するデータセットである. 機械学習での影検出の学習や検証に利用できるデータセット

    SBU データセットは,次の URL で公開されているデータセット(オープンデータ)である.

    SBU データセット の URL: https://www3.cs.stonybrook.edu/~cvl/projects/shadow_noisy_label/index.html

    【関連情報】

    scikit-learn

    scikit-learnは,分類,会期,クラスタリング,次元削減,Model selection などの機械学習の 機能を持つ Pythonのパッケージ

    scikit-learn の URL: https://scikit-learn.org/stable/

    オープンソースの Python の機械学習プラットフォーム.URL は次のとおりである.

    SCRFD (Sample and Computation Redistribution for Face Detection)

    SCRFD顔検出の手法である. TinaFace に対しては,画像が低解像度のとき速く処理できない,そして,一般の物体認識法である RetinaNet をベースに設計されているために,顔検出 (face detection)に用いるには冗長であったり,最適化しつくし切れていない という見解が示されているようである. WIDER FACE データセット の HARD レベルの顔は,78.83% の顔が 32x32 画素よりも小さいということも示されている. SCRFD では,探索空間の削減のために, sample redistribution と computation redistribution を 2段階で行う方法が提案されている. WIDER FACE データセット による実験結果では,TinaFace を精度と性能で上回るとされている.

    関連項目InsightFace, RetinaNet, TinaFace, 顔検出 (face detection)

    Google Colaboratory で SCRFD のインストール

    InsightFaceSCRFD のインストールは, 次のページで説明されている.

    https://github.com/deepinsight/insightface/tree/master/detection/scrfd

    このページの手順によりインストールを行う.

    次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する).

    1. Google Colaboratory で,ランタイムのタイプを GPU に設定する.
    2. まず,PyTorch のバージョンを確認

      PyTorch は,ディープラーニングのフレームワークの 機能を持つ Pythonのパッケージ

      次のプログラム実行により,PyTorch のバージョンが「1.10.0+cu111」のように表示される.

      import torch
      print(torch.__version__)
      
    3. NVIDIA CUDA ツールキット のバージョンを確認 (2)**NVIDIA CUDA ツールキット のバージョン**を確認 NVIDIA CUDA ツールキット は,NVIDIA社が提供している GPU 用のツールキットである.GPU を用いた演算のプログラム作成や動作のための各種機能を備えている.ディープラーニングでも利用されている.

      次のプログラム実行により,NVIDIA CUDA ツールキットのバージョンが「cu111」のように表示される.

      import torch
      CUDA_VERSION = torch.__version__.split("+")[-1]
      print(CUDA_VERSION)
      

      [image]
    4. PyTorch のバージョンを確認
      import torch
      TORCH_VERSION = ".".join(torch.__version__.split(".")[:2])
      print(TORCH_VERSION)
      

      [image]
    5. MMCV のインストール

      https://mmcv.readthedocs.io/en/latest/get_started/installation.html に記載の手順による

      NVIDIA CUDA ツールキット 11.1, PyTorch 1.10 の場合には,次のようになる

      cu111/torch1.10」のところは, NVIDIA CUDA ツールキット のバージョン, PyTorch のバージョンに合わせる

      バージョンについては,公式のページ https://github.com/open-mmlab/mmcv に説明がある.

      !apt remove python3-pycocotools
      !pip3 uninstall -y pycocotools
      !pip3 install mmpycocotools
      !apt install -y python3-terminaltables
      !apt install -y python3-opencv
      
      !pip3 install mmcv-full==1.3.3 -f https://download.openmmlab.com/mmcv/dist/cu111/torch1.10/index.html
      

      [image]
    6. SCRFD のインストール
      !git clone --recursive https://github.com/deepinsight/insightface
      %cd insightface/detection/scrfd
      !pip3 install dask==2022.01.0
      !pip3 install -r requirements/build.txt
      !export CUDA_HOME='/usr/local/cuda'
      !python3 setup.py develop
      

      [image]

    SDL

    SDL は,「Simple DirectMedia Layer」の略で, 次の機能などを持つ.

    3次元グラフィックス・カードは,OpenGL を経由して使用する. SDL は,種々の OS (Linux, WInodws, MacOS, FreeBSD などなど)で動く. SDL は C 言語で書かれ,C++ からも使える.Java, Perl, PHP, Python 等等の種々の言語からも使える.

    【関連する外部ページ】

    SDL の公式ページ: https://www.libsdl.org/

    Windows での SDL のインストール

    Windows での SDL のインストール: 別ページ »で説明している.

    Eigen 3.4 の非公式ビルド: sdl.zip

    私がビルドしたもの,非公式,無保証, 公式サイト https://github.com/libsdl-org/SDL で公開されているソースコードを改変せずにビルドした. Windows 10, Visual Build Tools for Visual Studio 2022 を用いてビルドした. SDL のライセンスによる.

    zip ファイルは C:\ 直下で展開し,C:\eigen での利用を想定.

    SDL_image

    SDL_image は, BMP, JPEG, PNG, PNM などの画像ファイルを扱う機能を持ったライブラリ.

    GitHub のページ: https://github.com/libsdl-org/SDL_image

    Windows での SDL2 のインストール: 別ページ »で説明している.

    Ubuntu では,次のコマンドでインストール.

    sudo apt -y install libsdl2-dev libsdl2-image-dev
    

    Stable Diffusion XL (SDXL)

    Stable Diffusion XL (SDXL) は,Stability AIによって開発されたDiffusionベースの image-to-text の画像生成モデルである. SDXLはStable Diffusion with Larger UNet Backboneの略称である.

    SDXLは,以前のStable Diffusionモデルと比較して,UNetバックボーンのサイズが3倍に増加している.この増加は,アテンションブロック数の増加とクロスアテンションコンテキストの拡大によるものである.また,SDXLはリファインメントモデルを導入している.このリファインメントモデルは,SDXLによって生成された画像の視覚的な精度を向上させるために使用される.

    文献

    Dustin Podell, Zion English, Kyle Lacey, Andreas Blattmann, Tim Dockhorn, Jonas Müller, Joe Penna, Robin Rombach: SDXL: Improving Latent Diffusion Models for High-Resolution Image Synthesis. CoRR abs/2307.01952, 2023.

    https://arxiv.org/pdf/2307.01952v1.pdf

    サイト内の関連ページ

    関連する外部ページ

    Seesaw Loss

    セグメンテーション, 物体検出の一手法.2021 年に発表.

    関連項目MMDetection, 物体検出, セグメンテーション

    SegFormer

    セマンティック・セグメンテーションのモデル. 2021年発表.

    関連項目モデル, セマンティック・セグメンテーション

    SE ResNeXt

    SE ResNeXt は, ResNeXt" からの派生であり, チャンネル単位での特徴の再キャリブレーションを可能にするための squeeze-and-excitation ブロックを特色とする.

    関連項目PyTorch, torchvision のモデル, Residual Networks (ResNets), ResNeXt", モデル, 画像分類

    Self-Instruct

    Self-Instruct は,大規模言語モデルにおいて,事前学習されたモデルが指示に従う能力を調整するためのフレームワークである. 大規模言語モデルの自己学習では,大量のテキストデータを入力としてモデルをトレーニングし,生成されたテキストを再びモデルの入力として使用することが一般的である. Self-Instruct では,モデルが生成したテキストを正確な指示に変換し,それを再びモデルの入力として使用することで,自己学習の精度を向上させる.

    文献

    Yizhong Wang, Yeganeh Kordi, Swaroop Mishra, Alisa Liu, Noah A. Smith, Daniel Khashabi, Hannaneh Hajishirzi, Self-Instruct: Aligning Language Model with Self Generated Instructions, arXiv preprint arXiv:2212.10560, 2022.

    https://arxiv.org/abs/2212.10560

    関連する外部ページ

    関連項目Stanford Alpaca大規模言語モデル

    ShanghaiTech データセット

    ShanghaiTech データセットは,Part A と Part B がある. あわせて,画像数は 1198枚である.

    文献

    Yingying Zhang, Desen Zhou, Siqin Chen, Shenghua Gao, and Yi Ma. Single-image crowd counting via multi-column convolutional neural network. In CVPR, 2016

    【関連用語】 crowd counting, FIDTM, オープンデータ

    Shap-E

    Shap-e は、テクスチャ付きメッシュ (textured mesh)や neural radient fields としてレンダリングできる出力を生成 する能力を特徴とする。 Point-E との比較では、高速、高品質の生成が可能であるとされている。

    文献

    Heewoo Jun, Alex Nichol, Shap-E: Generating Conditional 3D Implicit Functions, https://arxiv.org/abs/2305.02463, 2023.

    https://arxiv.org/pdf/2305.02463v1.pdf

    サイト内の関連ページ

    Shap-E のインストールと動作確認(テキストや画像からの立体生成)(Python,PyTorch を使用)(Windows 上)

    関連する外部ページ

    ShapeNet データセット

    ShapeNet データセットは,3次元CADモデルのリポジトリである.

    ShapeNet データセット は次の URL で公開されているデータセット(オープンデータ)である.

    URL: https://shapenet.org/

    【関連情報】

    Shiny のインストール

    R システムで Shiny のインストールを行うには, R システムで次のコマンドを実行する.

    install.packages("shiny")
    

    R システムの主な機能は,次の URL にまとめている. https://www.kkaneko.jp/pro/r/rintro.html

    Shiny によるデータシステム演習は,次の URL にまとめている. https://www.kkaneko.jp/cc/shiny/index.html

    short-time Fourier transform (STFT)

    short-time Fourier transform (STFT) は, 短い区間のオーバーラッピングウインドウ (overlappig window) を 用いて離散フーリエ変換 (DFT) を行うことにより求める.

    関連項目librosa, 音データ(sound data)

    softmax

    分類モデルにおいて, クラスの確率を提供する関数.

    Spleeter

    音源分離(music source separation)を行う 1手法.2019年発表. 音声と楽器音等の混合から,音声とそれ以外を分離できる.

    【関連用語】 audio source seperation, music source separation

    Google Colaboratory で,音声 (vocal) とそれ以外の分離 (Spleeter を使用)

    公式の手順 https://github.com/deezer/spleeter による.

    次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する).

    1. Spleeter のインストール
      !apt install ffmpeg
      !pip3 install spleeter
      !pip3 show spleeter
      !spleeter separate --help
      

      [image]
    2. 処理したいサウンドファイルの準備

      ここでは,1.m4a をダウンロードしている.

      %cd /content
      !curl -O https://www.kkaneko.jp/sample/audio/1.m4a
      

      [image]
    3. Demucs の実行
      !spleeter separate -p spleeter:2stems -o output/ 1.m4a
      

      [image]
    4. 処理結果のダウンロード

      1」のところは,処理したサウンドファイルのファイル名にあわせること.

      from google.colab import files
      %cd output/1
      files.download('vocals.wav')
      files.download('accompaniment.wav')
      

      [image]

    SPP (Spatial Pyramid Pooling)

    CNN (convolutional neural network) を用いた 画像分類において, 入力として固定サイズの画像(例えば 224x224)を要求していることを不要にできるための1手法. spatial pyramid pooling と呼ばれる pooling 戦略が導入されている. CNN を使用する画像分類全般に使える手法であるとされている.

    CSPNet の公式の実装 (GitHub) のページでは, SPP を用いた物体検出として, CSPDarknet53-PANet-SPP, CSPResNet50-PANet-SPP, CSPResNeXt50-PANet-SPP 等の実装が公開されている.

    関連項目画像分類

    SQLite 3

    SQLite 3(SQLite バージョン 3) は,リレーショナルデータベース管理システムSQLite 3は次の特徴を持つ.

    サーバクライアントで動かす(マルチユーザで使う,オンラインで使うなど)の場合は,並行処理制御,リモートとの通信の機能は SQLite 3 にないので,利用者側でこの機能を整える必要がある. SQL92 の全機能はない

    SQLite 3の起動は「sqlite3コマンド」で行う.

    パスが通っていないときは, Windowsなら「sqlite3.exe」,Ubuntuなら「sqlite」という名前のファイルを検索して実行する.

    Windows での動作画面例

    [image]

    Ubuntu での動作画面例

    [image]

    サイト内の主な SQLite 3 関連ページ

    関連する外部ページ

    SQLite 3 のインストール
    SQLite 3 コマンドラインシェル

    SQLite 3 コマンドラインシェルは,Windows のコマンドプロンプトや Linux のシェルなどで動作するツールである.主な機能は次の通りである.

    サイト内の関連ページ

    SQLiteman

    SQLiteman は SQLite 3 のデータベースを操作する機能を持ったソフトウェア. Windows 版,Linux 版,Max OS X 版がある.ソースコードも配布されている. インストール,データベースの新規作成,SQLの編集と実行,データのブラウズの手順を演習する.

    SQLiteman の URL: https://sourceforge.net/projects/sqliteman/

    SRCNN

    SRCNN は,image super resolution の一手法.2015年発表.

    Dong, Chao and Loy, Chen Change and He, Kaiming and Tang, Xiaoou, Image super-resolution using deep convolutional networks, IEEE transactions on pattern analysis and machine intelligence, vol. 38, no. 2 pp. 295--307, 2015.

    関連項目MMEditing, 超解像 (super resolution)

    SSD

    SSDは,物体検出のモデルである. 2016 年発表.

    MMDetection に実装された SSD を用いた物体検出については,別項目で説明している.

    関連項目MMDetection, モデル, 物体検出

    SSIM (Structural Similarity)

    SSIM は,動画や写真の品質を評価したり,類似性を判定するのに使用する. ImageMagick を用いて算出できる.

    compare -metric SSIM 1.png 2.png NULL:
    

    関連項目LPIPS (Learned Perceptual Image Patch Similarity)

    Stable Diffision

    サイト内の関連ページ

    関連する外部ページ

    Stanford Alpaca

    Stanford Alpaca は, スタンフォード大学で開発された 大規模言語モデルである. このモデルは,52Kの指示に準拠したLLaMAモデルの7Bデータセットをベースにしており,Self-Instruct によるファインチューニングを行っている.

    Stanford Alpacaの生成手順は公開されており,さまざまなプロジェクトで利用されている.

    文献

    Rohan Taori and Ishaan Gulrajani and Tianyi Zhang and Yann Dubois and Xuechen Li and Carlos Guestrin and Percy Liang and Tatsunori B. Hashimoto, Stanford Alpaca: An Instruction-following LLaMA model, 2023.

    関連する外部ページ

    関連項目LLaMA (Large Language Model Meta AI)Self-Instruct大規模言語モデル

    statsmodels

    PyPI の URL: https://pypi.org/project/statsmodels/

    Ubuntu でのインストール

    sudo apt install python3-statsmodels
    

    Stoop

    Stoop は,金融に関するポータルサイト.

    URL: https://stooq.pl/index.html

    関連項目株価データ

    Structure from Motion (SfM)

    SfM (Structure of Motion) は,オブジェクト(動かないもの)を, 周囲の複数の視点から撮影した多数の画像に対して次の処理を行う.

    その結果,各画像の撮影位置と方向が推定されるとともに,オブジェクトの3次元点群が構成される.

    SfM (Structure of Motion) の機能を持ったソフトウエアとしては, meshroomOpenMVG などがある.

    Ubuntu での OpenMVG のインストールは 別ページ »で説明している.

    関連項目3次元再構成 (3D reconstruction), meshroom, Multi View Stereo, OpenMVG, OpenMVS

    SuiteSparse

    SuiteSparse は,下記の機能を持つソフトウェアである.

    UFconfig は,SuiteSparseQR, AMD, COLAMD, CCOLAMD, CHOLMOD, KLU, BTF, LDL, CXSparse, and UMFPACK のビルドに必要.

    AMD は,疎行列の並び替えの機能を持ったソフトウェア. これは,Cholesky factorization や, 不完全 LU 分解 (LU factorization) の前処理として行うもの.

    Windows での SuiteSparse のインストール

    Windows での SuiteSparse のインストール: 別ページ »で説明している.

    SuiteSparse 5.4.0,Metis 5.1.0 の非公式ビルド: suitesparse.zip

    私がビルドしたもの,非公式,無保証, https://github.com/jlblancoc/suitesparse-metis-for-windows/releases で公開されているソースコードを改変せずにビルドした. Windows 10, Visual Build Tools for Visual Studio 2022 を用いてビルドした. BSD ライセンスによる.

    zip ファイルは C:\ 直下で展開し,C:\suitesparse での利用を想定.

    Ubuntu での SuiteSparse のインストール

    Ubuntu での SuiteSparse のインストール: 別ページ »で説明している.

    Sunspot Number データセット(黒点数のデータセット)

    太陽の黒点数の観測データである.

    次の URL で公開されているデータセット(オープンデータ)である.

    URL: https://www.sidc.be/silso/datafiles

    データは数種類ある. 毎日の黒点数のデータは, SN_d_tot_V2.0.csv というファイル名で公開されている. 属性は, (year, month, day, decimal year, SNvalue , SNerror, Nb observations) である

    関連項目】 time-series data

    SVHN (The Street View House Numbers) データセット

    SVHN データセット は,公開されているデータセット(オープンデータ)である.

    SVHN データセット は,小さく切り取られた数字の画像で,ラベル付けがされている. 機械学習での画像分類の学習や検証に利用できる.

    文献

    Yuval Netzer, Tao Wang, Adam Coates, Alessandro Bissacco, Bo Wu, Andrew Y. Ng, Reading Digits in Natural Images with Unsupervised Feature Learning, NIPS Workshop on Deep Learning and Unsupervised Feature Learning 2011, 2011.

    PDF ファイル:http://ufldl.stanford.edu/housenumbers/nips2011_housenumbers.pdf

    サイト内の関連ページ

    関連する外部ページ

    関連項目TensorFlow データセット, オープンデータ, 画像分類

    svn

    svn は,バージョン管理システム

    Windows での svn のインストール

    SlikSVN は,https://sliksvn.com/ から 64-bit 版をダウンロードして,インストール

    Subversion for Windows (SlikSVN) については, https://sliksvn.com/ で確認すること. 利用条件についても,利用者で確認すること

    SwinIR

    SwinIRは,超解像,ノイズ除去の一手法

    文献】 Liang, Jingyun and Cao, Jiezhang and Sun, Guolei and Zhang, Kai and Van Gool, Luc and Timofte, Radu, SwinIR: Image Restoration Using Swin Transformer, arXiv preprint arXiv:2108.10257, 2021.

    関連する外部ページ

    GitHub のページ: https://github.com/JingyunLiang/SwinIR

    SwinIR のインストールと動作確認(超解像,画像のノイズ除去)

    JingyunLiang/SwinIR のインストールと動作確認(超解像,画像のノイズ除去)(Python,PyTorch を使用)(Windows 上)別ページ »で説明している.

    TecoGAN

    関連項目 GAN (Generative Adversarial Network), image super resolution, video super resolution

    Google Colaboratory での TecoGAN のインストールと動作確認

    次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する).

    !pip3 install tensorflow==1.15.5
    !pip3 install -U keras==2.3.1
    !pip3 install git+https://www.github.com/keras-team/keras-contrib.git
    !rm -rf TecoGAN
    !git clone https://github.com/thunil/TecoGAN
    %cd TecoGAN
    !pip3 install -U -r requirements.txt
    !python3 runGan.py 0
    
    !python3 runGan.py 1
    from PIL import Image
    Image.open('LR/calendar/0001.png').show()
    Image.open('results/calendar/output_0001.png').show()
    

    [image]
    Ubuntu での TecoGAN のインストールと動作確認

    前準備:事前に Python のインストール: 別項目で説明している., NVIDIA CUDA ツールキットNVIDIA cuDNN のインストール: 別項目で説明している.を行うこと.

    1. pyenv のダウンロードと更新

      次のコマンドを実行.

      cd /tmp
      git clone https://github.com/pyenv/pyenv.git ~/.pyenv
      cd ~/.pyenv
      git pull
      src/configure 
      make -C src
      
    2. pyenv の設定

      次のコマンドを実行.

      echo 'export PYENV_ROOT="${HOME}/.pyenv"' >> ~/.profile
      echo 'if [ -d "${PYENV_ROOT}" ]; then' >> ~/.profile
      echo '    export PATH=${PYENV_ROOT}/bin:$PATH' >> ~/.profile
      echo '    eval "$(pyenv init --path)"' >> ~/.profile
      echo 'fi' >> ~/.profile
      echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n  eval "$(pyenv init -)"\nfi' >> ~/.profile
      exec $SHELL -l
      source ~/.profile
      
    3. python 3.6 のインストールと有効化(pyenv を使用)

      次のコマンドを実行.

      「pyenv install -l | grep 3.6」でインストールできる最新バージョンを確認

      pyenv install -l | grep 3.6
      pyenv install 3.6.15
      pyenv shell 3.6.15
      python -m pip install -U pip setuptools
      
    4. TecoGAN をUbuntu でインストールを行うには,次のコマンドを実行.
      sudo apt -y update
      sudo apt -y install git
      
      cd /usr/local
      sudo rm -rf TecoGAN
      sudo git clone https://github.com/thunil/TecoGAN
      sudo chown -R $USER TecoGAN
      
      cd /usr/local/TecoGAN
      pip install -U tensorflow-gpu==1.15.5
      pip install -U keras==2.3.1
      pip install git+https://www.github.com/keras-team/keras-contrib.git
      pip install -U -r requirements.txt
      pip list
      
    5. 学習済モデルのダウンロード

      公式ページに記載の https://github.com/thunil/TecoGAN の手順に従う.

      cd /usr/local/TecoGAN
      python runGan.py 0
      
    6. 確認のため実行してみる

      公式ページに記載の https://github.com/thunil/TecoGAN の手順に従う.

      python runGan.py 1
      

    結果のうち一部を下に示す.画像は原寸で(拡大縮小せずに)表示している.

    Temporal Segment Networks (TSN)

    ビデオの動作認識 (action recognition) の一手法.2016年発表

    関連項目MMAction2, 動作認識 (action recognition)

    TensorFlow

    Tensorflowは, データフローグラフ (data flow graph) を特色とするフレームワークの機能を持つ Pythonのパッケージ. データフローグラフでは, 節が数値演算,枝が多次元の配列(テンソル)になっている. Python, C/C++ 言語から利用可能.機械学習のアプリケーションを簡単に作成できるもの. プロセッサ(CPU), GPU, Google TPU で動く. Google 社のディープラーニング研究プロジェクト. 2015年11月に最初のリリース.

    TensorFlow のデータセットとして,https://github.com/tensorflow/datasets などで・音声,画像,テキスト,ビデオのデータが多数公開されており,学習に利用できる

    TensorFlow GPU 版の動作に必要なもの

    古いバージョンである2.4.4 あるいはそれ以前のバージョン のTensorFlow を使う場合は, 最新NVIDIA cuDNNを使わないこと. 詳しくは,別ページ »で説明している.

    文献

    TensorFlow: Large-Scale Machine Learning on Heterogeneous Distributed Systems

    https://arxiv.org/pdf/1603.04467v2.pdf

    関連する外部ページ

    TensorFlow で,GPU のメモリ不足でエラーメッセージがでて,プログラムが止まる場合, プログラムの先頭部分に次を追加すると解決する場合がある.

    メッセージ

    Internal: Attempting to perform BLAS operation using StreamExecutor without BLAS support

    解決策:Python プログラムの先頭部分に次を追加すると解決する場合がある.

    import tensorflow as tf
    gpu = tf.config.list_physical_devices(device_type = 'GPU')
    if len(gpu) > 0:
        print("GPU:", gpus[0].name)
        tf.config.experimental.set_memory_growth(gpu[0], True)
    

    サイト内の関連ページ

    関連項目Applications of Deep Neural Networks, Keras, ディープラーニング

    TensorFlow, PyTorch が必要とするNVIDIA CUDA ツールキットとNVIDIA cuDNN のバージョン

    現在,NVIDIA CUDA ツールキット 12 に対応する NVIDIA cuDNN が無い(2022年12月時点)ため, 古いバージョンであるNVIDIA CUDA ツールキット11.8 と, NVIDIA cuDNN 8.6 を使う.

    その根拠:

    2.4.4 あるいはそれ以前のバージョン のTensorFlow を使う場合

    過去の TensorFlow は, 必ずしも, 新しいNVIDIA CUDA ツールキット, NVIDIA cuDNN で動くわけではないことに注意が必要.

    TensorFlow のバージョンと, NVIDIA CUDA ツールキット,NVIDIA cuDNN のバージョンの関係

    PyTorch のバージョンと, NVIDIA CUDA ツールキットのバージョンの関係

    TensorFlow が必要とする Python のバージョン

    TensorFlow のバージョンは,次ページで確認できる.

    TensorFlow のタグのページ: https://github.com/tensorflow/tensorflow/tags で確認.

    TensorFlow 2.7.1 や,それより前のバージョンは,Python 3.10 が対応していないので,古いバージョンの Python を使用する.

    その根拠:

    https://pypi.org/project/tensorflow/#filesで確認することができる.

    その内容をまとめると次の通りである.

     
    TensorFlow のインストール

    前準備

    上に示した「別ページ」にあるように,TensorFlow バージョン 2 および関連ソフトウェア類のインストールは,コマンドで行うことができる. そのコマンドについて,ここに記しておく. インストールするときは,前準備や,前もって確認する事項があり,次のリンク先のページで,前準備,前もって確認する事項,インストール手順を説明している.

    インストールされている TensorFlow のバージョン確認
    import tensorflow as tf
    print(tf.__version__)
    
    TensorFlow が GPU を認識できているかの確認
    得られた表示に「device_type: "GPU"」があれば,GPUが認識できている.
    TensorFlow の利用可能なデバイスを調べる

    次のプログラムにより,利用可能なデバイスを確認することができる.

    import os
    os.environ['CUDA_VISIBLE_DEVICES'] = '0' # 0 = GPU use; -1 = CPU use
    from tensorflow.python.client import device_lib
    print(device_lib.list_local_devices())
    

    [image]

    次のプログラムにより,TensorFlow で利用しているデバイスを確認することができる.

    import tensorflow as tf
    print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))
    print(tf.test.gpu_device_name())
    

    [image]
    TensorFlow 2 の上で,TensorFlow 1 のプログラムを動かす

    TensorFlow 2 系列の上で TensorFlow 1 のプログラムを動かすときは, このサイトでは,次のように書くようにしている.

    from __future__ import absolute_import, division, print_function, unicode_literals
    import tensorflow.compat.v1 as tf
    # tf.enable_v1_behavior()
    import tensorflow.keras as keras
    import os
    os.environ['CUDA_VISIBLE_DEVICES'] = '0' # 0 = GPU use; -1 = CPU use
    config = tf.compat.v1.ConfigProto( device_count = {'GPU': 1 , 'CPU': 3} )
    sess = tf.compat.v1.Session(config=config)
    tf.keras.backend.set_session(sess)
    
    TensorFlow のベクトル

    ベクトルは,要素の並び.各要素の添字は 0, 1, 2... のようになる. 下に,TensorFlow のベクトルのコンストラクタの例を示す.

    import tensorflow as tf
    v1 = tf.constant([1, 2, 3])
    print(v1)
    
    import numpy as np
    np.array([1, 2, 3])
    v2 = tf.constant( np.array([1, 2, 3]) )
    print(v2)
    

    [image]
    TensorFlow のレイヤ

    TensorFlow のレイヤは,テンソルと設定オプションを入力とし,テンソルを出力とするような Python の関数である. TensorFlow を用いてニューラルネットワークを構築するときは, レイヤを組み立てていく. TensorFlow の Layers API は,以下のようなさまざまなタイプのレイヤを構築することができる.

    TensorFlow の Layers API は,Keras の layers API の書き方に準拠している. TensorFlow の Layers API と Keras の layers API で関数名は同じである. 接頭語「tf.」の部分が異なる.

    関連項目TensorFlow

    TensorFlow の配列

    配列では,添え字が複数になる. 下に,TensorFlow の配列のコンストラクタの例を示す.

    import tensorflow as tf
    M1 = tf.constant([[1, 2, 3], [4, 5, 6]])
    print(M1)
    
    import numpy as np
    np.array([1, 2, 3])
    M2 = tf.constant( np.array([[1, 2, 3], [4, 5, 6]]) )
    print(M2)
    

    [image]

    TensorFlow の Playground デモサイト

    ニューラルネットワークのデモサイト: http://playground.tensorflow.org

    関連項目TensorFlow

    TensorFlow 1.14

    TensorFlow の URL: https://www.tensorflow.org/

    TensorFlow 1.14 を使いたいとき,次の組み合わせになる.cuDNN 7.6.5 は,Windows で実際に試してみたことが根拠.

    関連項目TensorFlow

    TensorFlow 1.15.5

    TensorFlow の URL: https://www.tensorflow.org/

    TensorFlow 1.15.5 は Python 3.7, Python 3.6 で動く(Python 3.10 や Python 3.9 や Python 3.8 では動かない).

    その根拠は,次のページである. https://pypi.org/project/tensorflow/1.15.5/#files

    TensorFlow 1.15.5 は, NVIDIA CUDA ツールキット のバージョン 10.0 を必要とする.それより新しいバージョンでは動かない. NVIDIA cuDNN のバージョン 7 系列を必要とする.バージョン 8 系列では動かない.

    以上から,TensorFlow 1.15.5 を使いたいとき,次の組み合わせになる.

    関連項目TensorFlow

    Windows での TensorFlow 1.15.5 のインストール

    Windows で TensorFlow 1.15.5 を使うためには,次を行う.

    Ubuntu での TensorFlow 1.15.5 のインストール
    Ubuntu でのPythonTensorFlow 1.15 のインストール:別ページで案内している.

    Ubuntu のシステム Python に影響を与えないように,隔離された Python 3.6 仮想環境の新規作成し,その上にTensorFlow 1.15.5 をインストールするという手順(venv を使用)(Ubuntu 上)を案内している.

    TensorFlow 1 で GPU を利用するように設定

    import tensorflow.compat.v1 as tf
    # tf.enable_v1_behavior()
    import os
    os.environ['CUDA_VISIBLE_DEVICES'] = '0' # 0 = GPU use; -1 = CPU use
    config = tf.compat.v1.ConfigProto( device_count = {'GPU': 1 , 'CPU': 3} )
    sess = tf.compat.v1.Session(config=config)
    tf.keras.backend.set_session(sess)
    

    [image]

    関連項目TensorFlow, TensorFlow 1.14, TensorFlow 1.15

    TensorFlow Playground

    TensorFlow Playground はオンラインで動く. ニューラルネットワークニューロン,結合,学習,重みの変化,学習率活性化関数ReLU など),正則化L2 正則化など),バッチサイズ,データの分類,回帰,そして,ハイパーパラメータが,学習にどのように影響するかなどを簡単に確認できるオンラインのサービスである. URL は次の通り.

    http://playground.tensorflow.org

    関連項目TensorFlow

    TensorFlow-Slim

    TensorFlow-Slimは,CNN (convolutional neural network) による画像分類のモデルで利用される学習や検証の機能を持つ. 微調整 (fine tuning)の機能も持つ.

    TensorFlow-Slimは,TensorFlow, 1.14 から 2.2 で動くようである (根拠: https://github.com/google-research/tf-slim). 最新の TensorFlow で動くとは限らないので,利用者で確認すること.

    関連項目: TensorFlow のモデルガーデン

    関連項目TensorFlow

    TensorFlow-Slim のインストール

    TensorFlow-Slim の公式ページ(https://github.com/tensorflow/models/tree/master/research/slim)の手順に従う.

    1. Git のインストール: 別項目で説明している.

      Git の公式ページ: https://git-scm.com/

    2. tf_slim のインストール

      Windows での TensorFlow-Slim のインストールは, コマンドプロンプトを管理者として開き そのコマンドプロンプトで,次のコマンドを実行することで行う.

      python -m pip install -U contextlib2 tf_slim
      
    3. 確認

      インストールできたかの確認は,次のコマンドで行う. エラーメッセージが出ないことを確認すること.

      python -c "import tf_slim as slim; eval = slim.evaluation.evaluate_once"
      

      [image]
    4. TensorFlow モデルガーデン(TensorFlow-Slim 画像分類モデルライブラリを含む)のダウンロード

      c:\Program Files\Python38」のところは,Python のインストールディレクトリを設定すること.

      cd "c:\Program Files\Python38\Lib"
      git clone --recursive https://github.com/tensorflow/models
      mklink /D slim models\research\slim
      
    5. 動作確認

      インストールできたかの確認は,次のコマンドで行う. エラーメッセージが出ないことを確認すること.

      python -c "from slim.nets import cifarnet; m = cifarnet.cifarnet"
      

      [image]

    関連項目TensorFlow

    TensorFlow データセット

    TensorFlow データセットのカタログのページ: https://www.tensorflow.org/datasets/catalog/overview

    「tfds.list_builders()」により,現在インストールされている TensorFlow データセットの データセットビルダーを確認できる.

    TensorFlow データセットのロード時に分割を行うには,次のように書く.

    「0%:50%」は先頭から 50 %, 「50%:100%」は末尾の 50% 部分.

    from __future__ import absolute_import, division, print_function, unicode_literals
    import tensorflow as tf
    import numpy as np
    import tensorflow_datasets as tfds
    
    %matplotlib inline
    import matplotlib.pyplot as plt
    import warnings
    warnings.filterwarnings('ignore')   # Suppress Matplotlib warnings
    
    iris, iris_info = tfds.load('iris', split=['train[0%:50%]', 'train[50%:100%]'], with_info = True, shuffle_files=True, as_supervised=True)
    iris = {'train': iris[0], 'test': iris[1]}
    

    関連項目CIFAR-10 データセット, CIFAR-100 データセット, Fashion MNIST データセット, IMDb データセット, MNIST データセット, くずし字 MNIST データセット(Kuzushiji-MNIST データセット)

    関連項目TensorFlow

    TensorFlow データセットカタログ

    TensorFlow データセットカタログ の URL: https://www.tensorflow.org/datasets/catalog/overview

    関連項目TensorFlow

    TensorFlow のモデルガーデン

    URL: https://github.com/tensorflow/models

    Windows では,次のような手順でダウンロードできる.

    c:\Program Files\Python38」のところは,Python のインストールディレクトリを設定すること.

    1. Git のインストール: 別項目で説明している.

      Git の公式ページ: https://git-scm.com/

    2. ダウンロード
      cd "c:\Program Files\Python38\Lib"
      git clone --recursive https://github.com/tensorflow/models
      
    3. 必要に応じて,次のようなコマンドで,シンボリックを作っておくと便利
      cd "c:\Program Files\Python38\Lib"
      mklink /D slim models\research\slim
      

    関連項目: TensorFlow-Slim

    関連項目TensorFlow

    TensorFlow の最新バージョンの確認

    TensorFlow のバージョン,TensorFlow のバージョンと Python のバージョンの関係は,次のページで確認するのが便利である.

    https://pypi.org/project/tensorflow/#files

    2022年10月時点では TensorFlow の最新版2.10 である

    TensorFlow のインストール別の項目で説明している.

    Tensorpack

    Saliency Map

    !pip3 install --upgrade git+https://github.com/tensorpack/tensorpack.git
    %tensorflow_version 1.x
    %cd /content
    !rm -rf tensorpack
    !git clone https://github.com/tensorpack/tensorpack
    %cd tensorpack
    %cd examples/Saliency
    !curl -O http://download.tensorflow.org/models/resnet_v1_50_2016_08_28.tar.gz
    !tar -xzvf resnet_v1_50_2016_08_28.tar.gz
    !curl -L https://github.com/opencv/opencv/blob/master/samples/data/squirrel_cls.jpg?raw=true -o squirrel_cls.jpg
    !python3 ./saliency-maps.py squirrel_cls.jpg
    

    Tesseract OCR

    Tesseract OCR は,文字認識ソフトウェアである.

    サイト内の関連ページ

    関連する外部ページ

    GitHub の Tesseract OCR のページ: https://github.com/tesseract-ocr/tesseract

    Theano

    ( 2017.9 に開発の停止がアナウンス)

    TinaFace

    TinaFace顔検出法である. ResNet50 と Feature Pyramid Network (FPN) をベースとする顔検出法. FPN は 6 レベルあり,それを踏襲している. そうした仕組みになっていることから,さまざまなサイズの顔を検出できるとされている. WIDER FACE データセットを用いた検証により,当時の他の顔検出法よりも精度が優れているとされている.

    関連項目RetinaNet, SCRFD, モデル, 顔検出 (face detection)

    Titanic データセット

    Titanic データセットは,公開されているデータセット(オープンデータ)である.

    文献

    Frank E. Harrell Jr., Thomas Cason, Titanic dataset, 2002.

    サイト内の関連ページ

    関連する外部ページ

    関連項目オープンデータ, データフレーム

    Torch 7

    Transformers

    関連項目】 GPT-2, text generation, テキスト特徴 (text feature)

    Google Colaboratory で GPT を実行(huggingface の GPT-2 を使用)

    次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する).

    1. transformers のインストール
      !pip3 install transformers
      

    2. huggingface の GPT-2 を用いて,open-end text generation を行ってみる.
      from transformers import pipeline, set_seed
      generator = pipeline('text-generation', model='gpt2')
      set_seed(42)
      generator("Hello, I'm a language model,", max_length=30, num_return_sequences=5)
      

    3. huggingface の GPT-2 を用いて,テキストの特徴を取得する.
      from transformers import GPT2Tokenizer, TFGPT2Model
      tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
      model = TFGPT2Model.from_pretrained('gpt2')
      text = "Replace me by any text you'd like."
      encoded_input = tokenizer(text, return_tensors='tf')
      output = model(encoded_input)
      print(output)
      

    Twinmotion

    Twinmotion は,Unreal Engine を用いて実装されている. 3次元メッシュ(Wavefront OBJ, fbx)のインポート, 3次元点群データのインポート,高さマップ(r15, png)のインポート, OpenStreetMap との連携,人物の配置,波の表現,空の表現などの機能がある.

    関連項目】 Unreal Engine

    t 検定 (t test)

    R システム で,2群 s1, s2 の t 検定を行うプログラム

    t.test(s1, s2, var.equal=TRUE)
    t.test(s1, s2, var.equal=FALSE)
    

    関連項目検定

    U2-Net

    U2-Net は salient obeject detection の一手法. 【文献

    Xuebin Qin, Zichen Zhang, Chenyang Huang, Masood Dehghan, Osmar R. Zaiane and Martin Jagersand, U2-Net: Going Deeper with Nested U-Structure for Salient Object Detection, arXiv:2108.10257, 2021. 【サイト内の関連ページ

    rembg のインストールと動作確認(画像の背景除去)(Python を使用)(Windows 上): 別ページ »で説明している.

    関連する外部ページ

    関連項目BASNet, U-Net, salient object detection, セマンティック・セグメンテーション (semantic segmentation)

    UCF101 (UCF101 Human Actions dataset)

    ビデオでのアクションの認識 UCF101 データセット は,101 のアクションカテゴリに分類済みの動画のデータセット.

    UCF101 データセットは次の URL で公開されているデータセット(オープンデータ)である.

    https://www.crcv.ucf.edu/data/UCF101.php

    【関連情報】

    UCF-QNRF データセット

    画像数は 1535枚. 各画像のアノテーションされたオブジェクト数は 49 から 12865 である.

    【関連用語】 crowd counting, FIDTM, オープンデータ

    U-Net

    関連項目BASNet, セマンティック・セグメンテーション (semantic segmentation), salient object detection

    Google Colaboratory での BASNet のインストールとオンライン実行

    次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する).

    U-Net のテストプログラムのオンライン実行を行うまでの手順を示す.

    1. U-Net プログラムなどのダウンロード**
      !rm -rf PyTorch-UNet
      !git clone https://github.com/milesial/PyTorch-UNet
      

      [image]
    2. 学習済みモデルのダウンロード

      https://github.com/milesial/PyTorch-UNet の指示通りに行う. 学習済みモデル(ファイル名 unet_carvana_scale0.5_epoch1.pth)を ダウンロードし,PyTorch-UNet の下に置く

      [image]
    3. テスト用の画像のダウンロードと確認表示
      %cd PyTorch-UNet 
      !curl -L https://github.com/opencv/opencv/blob/master/samples/data/fruits.jpg?raw=true -o fruits.jpg
      !curl -L https://github.com/opencv/opencv/blob/master/samples/data/home.jpg?raw=true -o home.jpg
      !curl -L https://github.com/opencv/opencv/blob/master/samples/data/squirrel_cls.jpg?raw=true -o squirrel_cls.jpg
      from PIL import Image
      Image.open('fruits.jpg').show()
      Image.open('home.jpg').show()
      Image.open('squirrel_cls.jpg').show()
      

      [image]
      [image]
    4. U-Net の実行
      !python3 predict.py --model unet_carvana_scale0.5_epoch1.pth -i fruits.jpg -o fruits_out.jpg
      !python3 predict.py --model unet_carvana_scale0.5_epoch1.pth -i home.jpg -o home_out.jpg
      !python3 predict.py --model unet_carvana_scale0.5_epoch1.pth -i squirrel_cls.jpg -o squirrel_cls_out.jpg
      from PIL import Image
      Image.open('fruits_out.jpg').show()
      Image.open('home_out.jpg').show()
      Image.open('squirrel_cls_out.jpg').show()
      

      [image]
      [image]

    Unified Scene Text Detection

    Unified Scene Text Detection は,テキスト検出(text detection),ドキュメントのレイアウト解析(layout analysis)を統合することにより,精度の改善を行っている. 2022年発表.

    文献

    Towards End-to-End Unified Scene Text Detection and Layout Analysis, Long, Shangbang and Qin, Siyang and Panteleev, Dmitry and Bissacco, Alessandro and Fujii, Yasuhisa and Raptis, Michalis, Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition, 2022.

    https://arxiv.org/abs/2203.15143

    https://openaccess.thecvf.com/content/CVPR2022/papers/Long_Towards_End-to-End_Unified_Scene_Text_Detection_and_Layout_Analysis_CVPR_2022_paper.pdf

    サイト内の関連ページ

    Unified Scene Text Detection のインストールとテスト実行(テキスト検出)(Python,TensorFlow を使用)(Windows 上): 別ページ »で説明している.

    関連する外部ページ

    関連項目HierText

    Utah teapot

    Utah teapot は,1975 年に University of Utah の Martin Newell により制作された3次元データ.

    Utah teapot のデータは,common.wikimedia.prg の次のページからダウンロードすることができる.

    https://commons.wikimedia.org/wiki/File:Utah_teapot_(solid).stl

    UTKFace データセット

    20000枚以上の顔画像,68ランドマーク,各種の属性(年齢,性別など)

    次の URL で公開されているデータセット(オープンデータ)である.

    UTKFace の URL: https://susanqq.github.io/UTKFace/

    関連項目顔のデータベース, 顔ランドマーク (facial landmark)

    VALL-E X

    VALL-E X は,音声合成(TTS),プロンプトとして音声を与えて音声合成(voice cloning)の技術である.

    サイト内の関連ページ

    関連する外部ページ

    関連項目Bark

    vcpkg

    vcpkg は,C や C++ のライブラリを管理する機能を持ったソフトウェア.Windows, Linux, MacOS で動く. ダウンロードされたファイルは,downloads 下に保存される.

    vcpkg の GitHub のページ: https://github.com/microsoft/vcpkg

    vcpkg のインストール後, cmake から,vcpkg でインストールされたソフトウェアを認識できるようにするために, cmake の実行において,次のようなオプションを付ける場合がある.

    -DCMAKE_TOOLCHAIN_FILE=C:/vcpkg/scripts/buildsystems/vcpkg.cmake -DVCPKG_TARGET_TRIPLET=x64-windows 
    
    Windows での vcpkg のインストール

    Windows での vcpkg のインストール: 別ページ »で説明している.

    venv

    venv は,Python の仮想環境を作成する機能を提供するモジュールである.Python の仮想環境は隔離されており,特定のバージョンのPythonや,特定のバージョンやPythonパッケージを管理するのに役立つ.

    詳しい説明は: 別ページ »で説明している.

    【Python のまとめ】

    別ページ に Python の機能などをまとめている.

    関連項目Python, Python, pip, Python 開発環境,Python コンソールのコマンドでの起動, Python のインストール,pip と setuptools の更新, Python の仮想環境, virtualenv

    Python の隔離された環境を扱う(venv を使用)(Windows の場合)

    venv を用いて,新しいPython の仮想環境の生成 Python の隔離された環境の新規作成,有効化,無効化を行う.

    1. Windows では,前準備として次を行う.
      • Python のインストール: 別項目で説明している.
    2. 使用している Python のバージョンの確認は,次のコマンドで行うことができる.
      python --version
      
    3. Python の仮想環境の作成

      ここでは,venv のためのディレクトリ名「%HOMEPATH%\.venv」を指定して,新しいPython の仮想環境を生成する.

      venv のためのディレクトリ名は何でもよいが,venv で使うことが分かるような分かりやすい名前がよい.記号や,日本語などの全角文字を含めないのがよい.

      ※ 「python -m venv」は,venv モジュールの実行

      python -m venv %HOMEPATH%\.venv
      dir /w %HOMEPATH%\.venv
      

      [image]
    4. Python の隔離された環境の有効化
      %HOMEPATH%\.venv\Scripts\activate.bat
      

      [image]

      [image]
    5. パッケージを確認してみる

      いま,venv を使用中かどうか,プロンプトの「(venv)」で分かる.

      python -m pip list
      

      [image]
    6. 現在使用している Python の隔離された環境の使用中止(無効化)
      deactivate
      

      [image]
    Python の仮想環境を扱う(venv を使用)(Ubuntu の場合)

    venv を用いて,新しいPython の仮想環境の生成 Python の隔離された環境の新規作成,有効化,無効化を行う.

    1. python3-venv のインストール
      sudo apt -y update
      sudo apt -y install python3-venv
      
    2. 使用している システム Python のバージョンの確認は,次のコマンドで行うことができる.
      python3 --version
      

      [image]
    3. Python の仮想環境の作成

      ここでは,venv のためのディレクトリ名「~/.venv」を指定して,新しいPython の仮想環境を生成する.

      venv のためのディレクトリ名は何でもよいが,venv で使うことが分かるような分かりやすい名前がよい.記号や,日本語などの全角文字を含めないのがよい.

      システム Python違うバージョンの Python を使いたいときは, pyenv を用いる.別ページ »で説明

      ※ 「python3 -m venv」は,システム Python を用いての venv モジュールの実行

      python3 -m venv ~/.venv
      ls -la .venv 
      

      [image]
    4. Python の隔離された環境の有効化
      source ~/.venv/bin/activate
      

      [image]
    5. パッケージを確認してみる

      いま,venv を使用中かどうか,プロンプトの「(venv)」で分かる.

      python -m pip list
      

      [image]
    6. 現在使用している Python の隔離された環境の使用中止(無効化)
      deactivate
      

      [image]

    VGGFace2 データセット

    VGGFace2 データセットは,顔画像がクラス分けされたデータ.

    作者からは,社会的,性別的,人種的,その他の偏りに注意して使うように,注意が行われている.

    次の URL で公開されているデータセット(オープンデータ)である.

    https://www.robots.ox.ac.uk/~vgg/data/vgg_face/

    関連項目】 facial inpainting, 顔のデータベース, 顔認識

    video

    動画 (video) については,「動画」の項目で説明している.

    関連項目動画

    vinta の awesome-python

    Python のフレームワーク,ライブラリ,ソフトウェア等のリスト.

    vinta の awesome-python: https://github.com/vinta/awesome-python

    関連項目Python

    VirtualBox

    Oracle VM VirtualBox は仮想マシンのソフトウエア

    サイト内の主な関連ページ

    関連する外部ページ

    Virtual Box の公式ページ: https://www.virtualbox.org/

    virtualenv

    Ubuntu で,Python の仮想環境の作成

    test」のところは,Python の仮想環境の名前を指定. Python の仮想環境を削除するときは「rm -rf test」のように操作する.

    sudo apt -y update
    sudo apt -y install virtualenv python3-virtualenv 
    virtualenv test
    source test/bin/activate
    

    関連項目Python, Python, pip, Python 開発環境,Python コンソールのコマンドでの起動, Python のインストール,pip と setuptools の更新, Python の仮想環境, venv

    Microsoft Build Tools 2015 (Microsoft Build Tools 2015 (マイクロソフト C++ ビルドツール 2015)

    Windows での Microsoft Build Tools 2015 (Microsoft Build Tools 2015 (マイクロソフト C++ ビルドツール 2015)のインストール: 別ページ »で説明している.

    Visual Studio Community 2019 のインストール,C++ ビルドツール (Build Tools) のインストール

    ここでは,次の2つを説明する.
    1. Visual Studio Community 2019 のインストール, C++ ビルドツール (Build Tools) のインストールを同時に行う.
    2. C++ ビルドツール (Build Tools) のみのインストール行う.
    (1) Visual Studio Community 2019 のインストール, C++ ビルドツール (Build Tools) のインストールを同時に行う.

    Visual Studio Community 2019 のインストールには,複数の方法がある. 次のいずれかによりインストールできる.

    ここでは,winget を用いてインストールする方法を説明する.

    1. 事前にwinget のインストールを行っておく.
    2. コマンドプロンプトを管理者として開き そこで,次のコマンドを実行(winget を利用してインストール )
      winget install Microsoft.VisualStudio.2019.Community
      
    3. Visual Studio Installer の起動

      スタートメニューの「Visual Studio Installer」を使うのが便利

    4. Visual Studio Community 2019 で「変更」を選ぶ.

      [image]
    5. C++ (v142) ユニバーサル Windows プラットフォーム」をチェックし,「変更」をクリック.

      [image]
    6. Visual Studio の英語言語パックのインストール

      今後は,「言語パック」で「英語」と「日本語」にチェックし,「変更」をクリック.

    C++ ビルドツール (Build Tools) のみのインストール行う.
    1. Visual Studio のダウンロードの Web ページを開く

      https://visualstudio.microsoft.com/visual-cpp-build-tools/

    2. Build Tools のダウンロード」をクリック

      [image]
    3. ダウンロードが始まる

      [image]
    4. ダウンロードした .exe ファイルを実行する
    5. 表示を確認し,「続行」をクリック

      [image]
    6. C++ によるデスクトップ開発」をクリック.「インストール」をクリック.

      [image]
    7. ダウンロードとインストールが始まる

      [image]
    8. インストール終了の確認

      「再起動が必要です」と表示された場合には,指示に従う.

      [image]

    Vision Transformer

    Vision Transformer は, 画像分類を,CNN よりも高速に,CNN よりも精度が落ちることなく実行できるとされる.

    関連項目画像分類

    https://colab.research.google.com/github/google-research/vision_transformer/blob/master/vit_jax.ipynb

    https://colab.research.google.com/github/google-research/vision_transformer/blob/master/vit_jax_augreg.ipynb#scrollTo=ofwi7yvlx5hj

    非公式の PyTorch での ViT の実装

    https://github.com/lucidrains/vit-pytorch

    VMWare

    VMware は仮想マシンソフトウエア

    サイト内の関連ページ

    VOICEVOX

    VOICEVOX は,音声合成のソフトウェア.

    VOICEVOX CORE の GitHub のページ: https://github.com/VOICEVOX/voicevox_core

    関連項目音声合成 (Text To Speech; TTS)

    VoltDB

    VoltDB Community エディションは, インメモリ SQL データベース,スナップショットによる永続性(persistence)の機能を持つ.

    サイト内の関連ページVoltDB 11.4 のインストール(ソースコードを使用)(Ubuntu 上)

    関連する外部ページ

    VoltDB の GitHub のページ: https://github.com/VoltDB/voltdb

    VoltDB の公式のチュートリアル: https://docs.voltdb.com/tutorial/

    warning C4819 ファイルは,現在のコードページ (932) で表示できない文字を含んでいます.

    「warning C4819 ファイルは,現在のコードページ (932) で表示できない文字を含んでいます. ファイルを Unicode 形式で保存してください」という警告が出る場合がある.

    多くの場合,この警告は無視しても良さそうである.

    警告のため,コンパイルを進めることができないという場合には, ファイルすべての文字コードを「UTF-8」に変換することで, この問題が解決できる場合がある. 文字コードの変換には,FileCode Checker などのソフトウェアを利用できる. 文字コードの変換は,バックアップを作成した後で実行すること.

    FileCode Checker の 作者に感謝します.

    FileCode Checker の Vector のページ: https://www.vector.co.jp/soft/winnt/util/se478635.html

    Wasserstein GAN (WGAN)

    Wasserstein GANでは, GAN (Generative Adversarial Network) での勾配消失問題の解決に取り組んでいる. GAN (Generative Adversarial Network) で用いられてきた Jensen-Shannon divergence (確率密度間の距離尺度の1つ) の代わりに Wasserstein 距離を用いる. 安定して学習ができるとされている

    関連項目GAN (Generative Adversarial Networks), image generation

    Google Colaboratory での Wasserstein GAN (WGAN) のインストールとオンライン実行

    次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する).

    実行時間の目安は,ハードウェアアクセラレータなしで 2時間

    !rm -rf PyTorch-GAN
    !git clone https://github.com/eriklindernoren/PyTorch-GAN
    !python -m pip install -r PyTorch-GAN/requirements.txt
    !rm -rf PyTorch-GAN/implementations/wgan/images
    !python3 PyTorch-GAN/implementations/wgan/wgan.py
    

    結果は /content/PyTorch-GAN/images の下にある. その中の画像をダブルクリックすると,Webブラウザに画像の中身が表示される.

    [image]
    Windows での Wasserstein GAN (WGAN) のインストールと動作確認

    PyTorch-GAN のページで公開されているプログラム等を使用

    Windows では,コマンドプロン プトを管理者として実行し, 次のコマンドを実行する.

    実行時間の目安は,GPU 搭載パソコンで数分.

    cd %LOCALAPPDATA%
    rmdir /s /q PyTorch-GAN
    git clone https://github.com/eriklindernoren/PyTorch-GAN
    cd PyTorch-GAN
    python -m pip install -U -r requirements.txt
    cd implementations/wgan
    rmdir /s /q images
    python wgan.py
    

    結果は images の下に保存される.

    [image]
    Ubuntu での Wasserstein GAN (WGAN) のインストールと動作確認

    PyTorch-GAN のページで公開されているプログラム等を使用

    Ubuntu では,次のコマンドを実行.

    実行時間の目安は,GPU 搭載パソコンで数分.

    sudo apt -y update
    sudo apt -y install git
    
    cd /usr/local
    sudo git clone https://github.com/eriklindernoren/PyTorch-GAN
    sudo chown -R $USER PyTorch-GAN
    
    # システム Python の環境とは別の Python の仮想環境システム Python を使用)を作成
    sudo apt -y update
    sudo apt -y install python3-venv
    python3 -m venv ~/a
    source ~/a/bin/activate
    
    cd /usr/local/PyTorch-GAN
    pip install -U -r requirements.txt
    cd implementations/wgan
    rm -rf images
    python wgan.py
    

    結果は images の下に保存される.

    [image]

    Wasserstein GAN with Fradient Penalty (WGAN-GP)

    関連項目GAN (Generative Adversarial Networks), image generation Wasserstein GAN (WGAN)

    Google Colaboratory での Wasserstein GAN (WGAN) のインストールとオンライン実行

    次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する).

    実行時間の目安は,ハードウェアアクセラレータなしで 2時間

    !rm -rf PyTorch-GAN
    !git clone https://github.com/eriklindernoren/PyTorch-GAN
    !python -m pip install -r PyTorch-GAN/requirements.txt
    !rm -rf PyTorch-GAN/implementations/wgan_gp/images
    !python3 PyTorch-GAN/implementations/wgan_gp/wgan_gp.py
    

    結果は /content/PyTorch-GAN/images の下にある. その中の画像をダブルクリックすると,Webブラウザに画像の中身が表示される.

    [image]
    Windows での Wasserstein GAN with Gradient Penalty (WGAN-GP) のインストールと動作確認

    PyTorch-GAN のページで公開されているプログラム等を使用

    1. Git のインストール: 別項目で説明している.

      Git の公式ページ: https://git-scm.com/

    2. インストール コマンドプロンプトを管理者として開き次のコマンドを実行する.
      cd %LOCALAPPDATA%
      rmdir /s /q PyTorch-GAN
      git clone https://github.com/eriklindernoren/PyTorch-GAN
      cd PyTorch-GAN
      python -m pip install -U -r requirements.txt
      cd implementations/wgan_gp
      rmdir /s /q images
      python wgan_gp.py
      

      [image]
    Ubuntu での Wasserstein GAN with Gradient Penalty (WGAN-GP) のインストールと動作確認

    PyTorch-GAN のページで公開されているプログラム等を使用

    Ubuntu では,次のコマンドを実行.

    sudo apt -y update
    sudo apt -y install git 
    
    cd /usr/local
    sudo git clone https://github.com/eriklindernoren/PyTorch-GAN
    sudo chown -R $USER PyTorch-GAN
    
    # システム Python の環境とは別の Python の仮想環境システム Python を使用)を作成
    sudo apt -y update
    sudo apt -y install python3-venv
    python3 -m venv ~/a
    source ~/a/bin/activate
    
    cd /usr/local/PyTorch-GAN
    pip install -U -r requirements.txt
    cd implementations/wgan_gp
    rm -rf images
    python wgan_gp.py
    

    結果は images の下に保存される.

    [image]

    WebFace260M, WebFace42M データセット

    機械学習向けの大規模な顔画像のデータセット. 顔検出,顔の分類(年齢,性別など)の用途が想定されている.2021年時点では,研究者等が利用可能な,最大規模の顔画像のデータセットである. データは次の2種類がある.

    次の URL で公開されているデータセット(オープンデータ)である.

    URL: https://www.face-benchmark.org/index.html

    詳細は,「the Masked Face Recognition challenge」の文献で説明されている.

    関連項目顔のデータベース

    Wget のインストール(Windows 上)

    GnuWinWget のページからダウンロードしてインストール

    Wget のインストールの詳細: 別ページ »で説明

    1. Wget のダウンロードのページを開く

      https://cmake.org/download/ からダウンロードしてインストール

    2.  ダウンロードしたいので「Download」 の「Complete packages, except sources」の右横の 「Setup」をクリック

      [image]
    3. ダウンロードした .exe ファイルを実行

      このとき,ライセンス条項の確認を行う.設定は既定(デフォルト)のままでよい.

    Whisper

    Whisperは,音声からの文字起こし,翻訳を行う. 訓練されたモデルが既存のデータセットにゼロショットで適用可能であり、データセット固有のファインチューニングを必要とせずに高品質な結果を達成することを特徴とする.

    文献

    Alec Radford, Jong Wook Kim, Tao Xu, Greg Brockman, Christine McLeavey, Ilya Sutskever, Robust Speech Recognition via Large-Scale Weak Supervision, CoRR abs/2212.04356, 2022.

    https://cdn.openai.com/papers/whisper.pdf

    サイト内の関連ページ

    関連する外部ページ

    関連項目

    mallorbc の whisper_mic

    Wide ResNet

    関連項目Residual Networks (ResNets), モデル, 画像分類

    PyTorch, torchvision の Wide ResNet50 学習済みモデルのロード,画像分類のテスト実行

    PyTorch HUB のページ: https://pytorch.org/hub/pytorch_vision_wide_resnet/ を参考にした.

    Google Colab あるいはパソコン(Windows あるいは Linux)を使用.

    1. 前準備

      前準備として,Python のインストール: 別項目で説明している., PyTorch のインストール を行う.

      Google Colaboratory では, Python, PyTorch はインストール済みなので,インストール操作は不要.

      次に,pip を用いて,pillow のインストールを行う.

      pip install -U pillow
      
    2. ImageNet データセット で学習済みのWide ResNet モデルのロード

      PyTorch, torchvision のモデルについては: https://pytorch.org/vision/stable/models.html に説明がある.

      import torch
      import torchvision.models as models
      device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
      m = models.wide_resnet50_2(pretrained=True).to(device)
      
    3. 画像分類したい画像ファイルのダウンロードとロードと確認表示
      from PIL import Image
      import requests
      from IPython.display import display
      
      # ダウンロードとロード
      url = 'https://github.com/pytorch/hub/raw/master/images/dog.jpg'
      response = requests.get(url)
      img = Image.open(requests.get(url, stream=True).raw)
      
      # 確認表示
      display(img)
      

      [image]
    4. 画像の前処理.PyTorch で扱えるようにするため.
      from PIL import Image
      from torchvision import transforms
      img = Image.open(filename)
      preprocess = transforms.Compose([
          transforms.Resize(256),
          transforms.CenterCrop(224),
          transforms.ToTensor(),
          transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
      ])
      input_tensor = preprocess(img)
      input_batch = input_tensor.unsqueeze(0)
      
    5. 推論 (inference) の実行

      「m.eval()」は,推論を行うときのためのもの.これを行わないと訓練(学習)が行われる.

      import torch
      if torch.cuda.is_available():
          input_batch = input_batch.to('cuda')
      
      m.eval()
      with torch.no_grad():
          output = m(input_batch)
      
    6. 結果の表示
      import urllib
      url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt")
      try: urllib.URLopener().retrieve(url, filename)
      except: urllib.request.urlretrieve(url, filename)
      
      with open("imagenet_classes.txt", "r") as f:
          categories = [s.strip() for s in f.readlines()]
      
      # The output has unnormalized scores. To get probabilities, you can run a softmax on it.
      probabilities = torch.nn.functional.softmax(output[0], dim=0)
      print(probabilities)
      
      top5_prob, top5_catid = torch.topk(probabilities, 5)
      for i in range(top5_prob.size(0)):
          print(categories[top5_catid[i]], top5_prob[i].item())
      

      Google Colaboratory での結果

      [image]

      Windows での結果

      [image]

      Linux での結果

      [image]
    PyTorch, torchvision の Wide ResNet101 学習済みモデルのロード,画像分類のテスト実行

    PyTorch HUB のページ: https://pytorch.org/hub/pytorch_vision_wide_resnet/ を参考にした.

    Google Colab あるいはパソコン(Windows あるいは Linux)を使用.

    1. 前準備

      前準備として,Python のインストール: 別項目で説明している., PyTorch のインストール を行う.

      Google Colaboratory では, Python, PyTorch はインストール済みなので,インストール操作は不要.

      次に,pip を用いて,pillow のインストールを行う.

      pip install -U pillow
      
    2. ImageNet データセット で学習済みのWide ResNet モデルのロード

      PyTorch, torchvision のモデルについては: https://pytorch.org/vision/stable/models.html に説明がある.

      import torch
      import torchvision.models as models
      device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
      m = models.wide_resnet101_2(pretrained=True).to(device)
      
    3. 画像分類したい画像ファイルのダウンロードとロードと確認表示
      from PIL import Image
      import requests
      from IPython.display import display
      
      # ダウンロードとロード
      url = 'https://github.com/pytorch/hub/raw/master/images/dog.jpg'
      response = requests.get(url)
      img = Image.open(requests.get(url, stream=True).raw)
      
      # 確認表示
      display(img)
      

      [image]
    4. 画像の前処理.PyTorch で扱えるようにするため.
      from PIL import Image
      from torchvision import transforms
      img = Image.open(filename)
      preprocess = transforms.Compose([
          transforms.Resize(256),
          transforms.CenterCrop(224),
          transforms.ToTensor(),
          transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
      ])
      input_tensor = preprocess(img)
      input_batch = input_tensor.unsqueeze(0)
      
    5. 推論 (inference) の実行

      「m.eval()」は,推論を行うときのためのもの.これを行わないと訓練(学習)が行われる.

      import torch
      if torch.cuda.is_available():
          input_batch = input_batch.to('cuda')
      
      m.eval()
      with torch.no_grad():
          output = m(input_batch)
      
    6. 結果の表示
      import urllib
      url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt")
      try: urllib.URLopener().retrieve(url, filename)
      except: urllib.request.urlretrieve(url, filename)
      
      with open("imagenet_classes.txt", "r") as f:
          categories = [s.strip() for s in f.readlines()]
      
      # The output has unnormalized scores. To get probabilities, you can run a softmax on it.
      probabilities = torch.nn.functional.softmax(output[0], dim=0)
      print(probabilities)
      
      top5_prob, top5_catid = torch.topk(probabilities, 5)
      for i in range(top5_prob.size(0)):
          print(categories[top5_catid[i]], top5_prob[i].item())
      

      Google Colaboratory での結果

      [image]

      Windows での結果

      [image]

      Linux での結果

      [image]

    WIDER FACE データセット

    WIDER FACE データセットは,32,203枚の顔画像のデータセットである. 機械学習での顔検出の学習や検証に利用できる.

    WIDER FACE データセットは,次の URL で公開されているデータセット(オープンデータ)である.

    URL: http://shuoyang1213.me/WIDERFACE/

    【関連情報】

    関連項目顔のデータベース, 顔検出 (face detection)

    Windows

    サイト内の主な Windows 関連ページ

    Wine

    Wine は,Windows の API の機能を提供することにより,Windows アプリケーションを Linux 上で動かすことを一部可能とするソフトウェア.

    Linux でのインストールは,次のWebページに説明がある

    https://wiki.winehq.org/Download

    Wine のインストールの手順は,Linux ディストリビューションの種類によって違うので注意.

    Ubuntu では,次のWebページの手順に従う

    https://wiki.winehq.org/Ubuntu

    WinPython のインストール

    WinPython は,Window 用のPython 処理系と主要な Python パッケージを1つにまとめたソフトウェア.次のアプリケーションも同封されている

    Windows での WinPython のインストールには,複数の方法がある.次のいずれかによりインストールできる.

    関連項目】 Python のインストール: 別項目で説明している.

    XAMPP

    XAMPP は, Apache Web サーバ, MySQL(もしくは MariaDB), PHP 及び関連のソフトウェアを一括でインストールするツール. 学習用に適すると考えている.

    実用で使うなら Linux を使い,パスワード,ファイヤウオール等を適切に設定する.バックアップも適切に行う.

    サイト内の関連ページ

    YOLOv3

    YOLOv3 は,物体検出のモデルである.

    関連項目AlexeyAB darknet, MMDetection, YOLOv4, YOLOX, モデル, 物体検出

    Google Colaboratory で YOLOv3 による物体検出(AlexeyAB darknet を使用)

    次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する)

    1. Google Colaboratory で,ランタイムのタイプを GPU に設定する.
    2. AlexeyAB darknet のビルド
      %cd /content
      !rm -rf darknet
      !git clone https://github.com/AlexeyAB/darknet
      %cd darknet
      !make GPU=1 CUDNN=1 CUDNN_HALF=1 OPENCV=1
      

      [image]
    3. 重みのダウンロード

      AlexeyAB darknet のアセット: https://github.com/AlexeyAB/darknet/releases/

      !curl -LO https://github.com/AlexeyAB/darknet/releases/download/darknet_yolo_v3_optimal/yolov3.weights
      

      [image]
    4. YOLOv3 による物体検出
      !rm -r predictions.jpg
      !./darknet detector test cfg/coco.data cfg/yolov3.cfg yolov3.weights data/dog.jpg -dont_show
      from PIL import Image
      Image.open('predictions.jpg').show()
      !./darknet detector test cfg/coco.data cfg/yolov3.cfg yolov3.weights data/giraffe.jpg -dont_show
      Image.open('predictions.jpg').show()
      !./darknet detector test cfg/coco.data cfg/yolov3.cfg yolov3.weights data/horses.jpg -dont_show
      Image.open('predictions.jpg').show()
      !./darknet detector test cfg/coco.data cfg/yolov3.cfg yolov3.weights data/person.jpg -dont_show
      Image.open('predictions.jpg').show()
      

      [image]

      [image]

      [image]

      [image]
    Google Colaboratory で AlexeyAB darknet のインストールと,YOLOv3 による物体検出(AlexeyAB darknet を使用)

    書きかけ(動作チェック中)

    cd %LOCALAPPDATA%
    rmdir /s /q darknet
    git clone https://github.com/AlexeyAB/darknet
    cd darknet
    del CMakeCache.txt
    cmake -G "Visual Studio 17 2022" -A x64 -T host=x64 ^
        -DCUDA_BUILD_CUBIN=ON -DENABLE_CUDA=ON -DENABLE_CUDNN=ON -DENABLE_CUDNN_HALF=ON
    cmake --build . --config RELEASE --target INSTALL -- /m:4
    
     Windows では,システム環境変数 PATH に,次の2つを追加.
    
        %LOCALAPPDATA%\darknet\build\darknet\x64
        %LOCALAPPDATA%\darknet\3rdparty\pthreads\bin 
    
    cd %LOCALAPPDATA%
    cd darknet
    curl -LO https://github.com/AlexeyAB/darknet/releases/download/darknet_yolo_v3_optimal/yolov3.weights
    darknet detect cfg/yolov3.cfg yolov3.weights data/dog.jpg -ext_output
    darknet detect cfg/yolov3.cfg yolov3.weights data/giraffe.jpg -ext_output
    darknet detect cfg/yolov3.cfg yolov3.weights data/horses.jpg -ext_output
    darknet detect cfg/yolov3.cfg yolov3.weights data/person.jpg -ext_output
    curl -O https://www.kkaneko.jp/sample/video/samplevideo.mp4
    ./darknet detector demo cfg/coco.data cfg/yolov3.cfg yolov3.weights samplevideo.mp4 -i 0 -thresh 0.25 
    
    
    Avatar Erik Linder-Norén による YOLOv3 の実装の,Ubuntu でのインストールと実行

    Avatar Erik Linder-Norén による YOLOv3 の実装: https://github.com/eriklindernoren/PyTorch-YOLOv3

    YOLOv4

    物体検出のモデルである.

    関連項目AlexeyAB darknet, YOLOX, モデル, 物体検出

    Google Colaboratory で YOLOv4 による物体検出(AlexeyAB darknet を使用)

    次のコマンドやプログラムは Google Colaboratory で動く(コードセルを作り,実行する)

    1. Google Colaboratory で,ランタイムのタイプを GPU に設定する.
    2. AlexeyAB darknet のビルド
      %cd /content
      !rm -rf darknet
      !git clone https://github.com/AlexeyAB/darknet
      %cd darknet
      !make GPU=1 CUDNN=1 CUDNN_HALF=1 OPENCV=1
      

      [image]
    3. 重みのダウンロード

      AlexeyAB darknet のアセット: https://github.com/AlexeyAB/darknet/releases/

      !curl -LO https://github.com/AlexeyAB/darknet/releases/download/darknet_yolo_v3_optimal/yolov4.weights
      
    4. YOLOv4 による物体検出
      !rm -r predictions.jpg
      !./darknet detector test cfg/coco.data cfg/yolov4.cfg yolov4.weights data/dog.jpg -dont_show
      from PIL import Image
      Image.open('predictions.jpg').show()
      !./darknet detector test cfg/coco.data cfg/yolov4.cfg yolov4.weights data/giraffe.jpg -dont_show
      Image.open('predictions.jpg').show()
      !./darknet detector test cfg/coco.data cfg/yolov4.cfg yolov4.weights data/horses.jpg -dont_show
      Image.open('predictions.jpg').show()
      !./darknet detector test cfg/coco.data cfg/yolov4.cfg yolov4.weights data/person.jpg -dont_show
      Image.open('predictions.jpg').show()
      

      [image]

      [image]

      [image]

      [image]

    YOLOX

    DarkNet53 バックボーンとするYOLOv3 に修正を行たもの.

    物体検出のモデルである. single-stage である. DarkNet53 バックボーンとするYOLOv3 に修正を行たものである.

    関連項目MMDetection, YOLOv3, YOLOv4, モデル, 物体検出

    Google Colab での YOLOX のインストールとオンライン実行

    公式のソースコードを使用.

    1. cython, pycocotools, YOLOX のインストール
      !pip3 install cython
      !pip3 install git+https://github.com/cocodataset/cocoapi.git#subdirectory=PythonAPI
      !rm -rf YOLOX
      !git clone https://github.com/Megvii-BaseDetection/YOLOX
      !pip3 install -U pip 
      !pip3 install -r YOLOX/requirements.txt
      !(cd YOLOX; python3 setup.py develop)
      
    2. 重みのダウンロード.

      詳しくは:

      !(cd YOLOX; curl -L -O https://github.com/Megvii-BaseDetection/YOLOX/releases/download/0.1.1rc0/yolox_x.pth)
      
    3. 物体検出の実行

      GPU を使うときは「cpu」のところを「GPU」に変える

      !(cd YOLOX; python tools/demo.py image -n yolox-x -c ./yolox_x.pth --path assets/dog.jpg --conf 0.25 --nms 0.45 --tsize 640 --save_result --device cpu)
      

      ./YOLOX_outputs/yolox_x/vis_res の下に結果ができるので確認

      [image]
    4. 別の画像で物体検出の実行

      GPU を使うときは「cpu」のところを「GPU」に変える

      次のプログラムでは,curl は,画像ファイルのダウンロードのために用いている(コマンドを使わずに,手作業で画像ファイルを置く場合には,この部分は不要)

      画像ファイル名には「../img.png」のように「../」を付けていることに注意.「../」は,「1つ上のレベルのディレクトリ」という意味.

      !curl -O https://raw.githubusercontent.com/zylo117/Yet-Another-EfficientDet-PyTorch/master/test/img.png
      !curl -O https://raw.githubusercontent.com/opencv/opencv/master/samples/data/fruits.jpg
      !curl -O https://raw.githubusercontent.com/opencv/opencv/master/samples/data/home.jpg
      
      !(cd YOLOX; python tools/demo.py image -n yolox-x -c ./yolox_x.pth --path ../img.png --conf 0.25 --nms \
      0.45 --tsize 640 --save_result --device cpu)
      !(cd YOLOX; python tools/demo.py image -n yolox-x -c ./yolox_x.pth --path ../fruits.jpg --conf 0.25 --n\
      ms 0.45 --tsize 640 --save_result --device cpu)
      !(cd YOLOX; python tools/demo.py image -n yolox-x -c ./yolox_x.pth --path ../home.jpg --conf 0.25 --nms\
       0.45 --tsize 640 --save_result --device cpu)
      

      ./YOLOX_outputs/yolox_x/vis_res の下に結果ができるので確認

      [image]

      [image]

      [image]

    yuki-koyama の blender-cli-rendering

    bpy (blenderpy)を使うときに便利なソフトウェアのライブラリと,そのサンプルプログラムと,各種のアセット.

    1. 前準備

      Git のインストール: 別項目で説明している.

      Git の公式ページ: https://git-scm.com/ が必要.

    2. yuki-koyama の blender-cli-rendering のダウンロード
      mkdir c:\pytools
      cd c:\pytools
      rmdir /s /q blender-cli-rendering-master
      git clone https://github.com/yuki-koyama/blender-cli-rendering
      
    3. 確認のため Blender の Cycles レンダラーを用いてレンダリングを行う.

      Windowsコマンドプロンプトで, 次を実行

      Windows で Python のバージョン指定したいときは, 「python 」でなく「py -3.7」のように実行すること. 「-3.7」のところには,使用する Python のバージョンを指定(バージョンが分からないときは「py -0」で調べる).

      cd c:\pytools
      cd blender-cli-rendering-master
      python 
      
    4. その後,次の Python プログラムを実行
      import bpy
      import utils
      
      # scene
      utils.clean_objects()
      scene = bpy.data.scenes["Scene"]
      monkey = utils.create_smooth_monkey(location=(0, 0, 1))
      plane = utils.create_plane(size=20.0)
      camera = utils.create_camera(location=(5, -3, 3))
      utils.add_track_to_constraint(camera, monkey)
      
      # light
      light = utils.create_sun_light(rotation=(0.3, -1.5, 1.2))
      
      # rendering
      utils.set_output_properties(scene, 20, 'c:/pytools/02')
      utils.set_cycles_renderer(scene, camera, 16)
      bpy.ops.render.render(write_still=True)
      

      次の画像ができる.

      [image]
    5. その後,次の Python プログラムを実行
      import os
      import bpy
      import utils
      
      # scene
      utils.clean_objects()
      scene = bpy.data.scenes["Scene"]
      monkey = utils.create_smooth_monkey(location=(0, 0, 1))
      plane = utils.create_plane(size=20.0)
      camera = utils.create_camera(location=(5, -3, 3))
      utils.add_track_to_constraint(camera, monkey)
      
      # light
      working_dir_path = os.path.abspath('.')
      hdri_path = os.path.join(working_dir_path, "assets\HDRIs\green_point_park_2k.hdr")
      utils.build_environment_texture_background(scene.world, hdri_path)
      
      # rendering
      utils.set_output_properties(scene, 20, 'c:/pytools/03')
      utils.set_cycles_renderer(scene, camera, 16)
      bpy.ops.render.render(write_still=True)
      

      [image]

    謝辞:この項目に記載のソースコードは, https://github.com/yuki-koyama/blender-cli-rendering/ で公開されているものを改変して使用している.

    関連項目bpy (blenderpy), Blender

    あ〜ん (ひらがな,カタカナ)

    ZLIB DLL

    ZLIB DLL は,データの圧縮と展開(解凍)の機能を持ったライブラリ.

    関連する外部ページ

    ZLIB DLL のインストール

    ZLIB DLL のインストールを行うため, Windows で,コマンドプロンプト管理者として実行

    コマンドプロンプトを管理者として実行: 別ページ »で説明

  • 次のコマンドを実行
    curl -O http://www.winimage.com/zLibDll/zlib123dllx64.zip
    powershell -command "Expand-Archive -Path zlib123dllx64.zip"
    copy zlib123dllx64\dll_x64\zlibwapi.dll .
    

    イテレーション (iteration)

    モデル学習において, モデル重みを更新することを繰り返すが, その各々1回をイテレーション (iteration) という. 「反復」ともいう. 1回のイテレーションで,データの 1つのバッチに対する損失についてのパラメータの勾配が計算される.

    インスタンス・セグメンテーション (instance segmentation)

    インスタンス・セグメンテーション (instance segmentation) は, 物体検出 を行うだけでなく, 検出されたオブジェクトについて, オブジェクトのセグメンテーションマスクを画素単位で生成する.

    セマンティック・セグメンテーション との違いは次の通りである. セマンティック・セグメンテーションでは,「インスタンス」という概念がないため, シーン内に複数の人物 (person) がいるような場合,人物の領域に person をいうラベルを付ける. インスタンス・セグメンテーションは, シーン内に複数の人物 (person) がいるような場合,それぞれの人物を分離する. 【関連項目セマンティック・セグメンテーション (semantic segmentation), シーン解析(scene parsing), CASILVision, MIT Scene Parsing Benchmark, 物体検出

    ウエルチの方法による一元配置分散分析 (One-way analysis of means)

    パラメトリック検定.等分散を仮定しない場合と仮定する場合がある.多群の検定

    R システム で,x, y についての ウエルチの方法による一元配置分散分析 (One-way analysis of means) を行うプログラム.

    なお,群数が2の場合には t 検定(R の t.test)と同じ結果が得られる.

    oneway.test(x ~ y)
    

    等分散 のときは,「var=T」を付ける.

    oneway.test(x ~ y, var=T)    
    

    なお,群数が2の場合には,等分散での t 検定(R の t.test(var.equal=TRUE))と同じ結果が得られる.

    関連項目検定

    ウィルコクソンの符号順位検定 (Wilcoxon signed-rank test)

    帰無仮説: ノンパラメトリック検定の1つ.対応のある2標本で,2群の差が 0 である.

    関連項目検定

    エポック

    教師データを全て使い終わったら 1エポックである.

    ミニバッチ学習を行うとき, 教師データのサイズを N とすると, N 割るバッチサイズの回数のイテレーション (iteration) が実行される. バッチサイズが 100,教師データのサイズが 800であるとすると, 8回のイテレーション (iteration) で 1エポックである.

    オープンデータ (open data)

    このサイトでは,「オープンデータは,インターネットで公開されているデータ,もしくは,インターネット等を用いて利用申込みができるデータ」の意味で用いている.

    オープンデータには次のようなものがある.

    次のデータはオープンデータではない.(ダウンロードには,申請を必要とする).

    【関連情報】

    関連項目R データセット (Rdatasets) を用いる場合には,

    オプティカルフロー

    オプティカルフローは MMFlow で算出できる.

    関連項目MMFlow

    オプティマイザ(最適化器, optimizer)

    オプティマイザは, 勾配降下法を実装したものである. 最適化器には,次のようなものがある.

    TensorFlow の最適化器のベースクラスは tf.train.Optimizer クラスである.

    勾配降下法の効果を高めるために,次のような手法が考案されている.

    論文: An overview of gradient descent optimization algorithms, CoRR, abs/1609.04747.

    http://sebastianruder.com/optimizing-gradient-descent/

    Kerasオプティマイザのページ: https://keras.io/api/optimizers/  

    エントロピー (entropy)

    確率分布 [1/2, 1/2] からエントロピーを求める Python プログラム. 「base = 2」で log の底を 2 としてエントロピーを求めている

    print(scipy.stats.entropy([1/2, 1/2], base=2))
    

    参考ページ: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.entropy.html

    確率分布 c(1/2, 1/2) からエントロピーを求める R のプログラム. 「unit="log2"」で log の底を 2 としてエントロピーを求めている

    library(entropy)
    entropy(c(1/2, 1/2), unit="log2")
    

    [image]

    参考資料: https://cran.r-project.org/web/packages/entropy/entropy.pdf

    オートエンコーダ

    Undercomplete Autoencoder, Sparse Autoencoder, Convolutional Autoencoder, Stacked Autoencoder, Variational Autoencoder (VAE), VQ-VAE(Vector Quantised) などの種類がある.

    キーポイント

    キーポイントは,画像の中での,ある特定の特徴の座標. 「ランドマーク」ともいう.

    くずし字 MNIST データセット(Kuzushiji-MNIST データセット)

    くずし字 MNIST データセットは,公開されているデータセット(オープンデータ)である.

    文献】 CODH:Center for Open Data in the Humanities), KMNISTデータセット(機械学習用くずし字データセット), arXiv:1812.01718 [cs.CV], 2018.

    サイト内の関連ページ

    関連する外部ページ

    関連項目MNIST データセット, TensorFlow データセット, オープンデータ, 画像分類

    Python での くずし字 MNIST データセットのロード(TensorFlow データセットを使用)

    次の Python プログラムは,TensorFlow データセットから,くずし字 MNIST データセットのロードを行う. x_train, y_train が学習用のデータ.x_test, y_test が検証用のデータになる.

    次のプログラムでは,くずし字 MNIST データセットのロードを行う.x_train と y_train を 25枚分表示することにより,x_train と y_train が,手書き文字のモノクロ画像であることが確認できる.

    from __future__ import absolute_import, division, print_function, unicode_literals
    import tensorflow as tf
    import numpy as np
    import tensorflow_datasets as tfds
    
    %matplotlib inline
    import matplotlib.pyplot as plt
    import warnings
    warnings.filterwarnings('ignore')   # Suppress Matplotlib warnings
    
    kmnist, kmnist_metadata = tfds.load('kmnist', with_info = True, shuffle_files=True, as_supervised=True, batch_size = -1)
    x_train, y_train, x_test, y_test = kmnist['train'][0], kmnist['train'][1], kmnist['test'][0], kmnist['test'][1]
    
    plt.style.use('default')
    plt.figure(figsize=(10,10))
    for i in range(25):
        plt.subplot(5,5,i+1)
        plt.xticks([])
        plt.yticks([])
        plt.grid(False)
    # squeeze は,サイズ1の次元を削除.numpy は tf.Tensor を numpy に変換
        plt.imshow(np.squeeze(x_train[i]), cmap=plt.cm.binary)
        plt.xlabel(y_train[i].numpy())
    
    # 確認表示
    plt.show()
    

    [image]
     

    クラス

    クラスはオブジェクトの種類,もしくは,同一種類のオブジェクトの集まりの意味である.  

    クラス番号

    クラス番号は, クラスを示す番号.

    クラスカル・ウォリス検定 ( Kruskal-Wallis rank sum test)

    帰無仮説: ノンパラメトリック検定の1つ.対応の無い多群の差の検定

    群数が2の場合には,マン・ホイットニーの U 検定と同じ結果が得られる.

    * R システム で,クラスカル・ウォリス検定 ( Kruskal-Wallis rank sum test) を行うプログラム.

    kruskal.test(length ~ group)  
    

    関連項目検定

    コルモゴロフ–スミルノフ検定 (Kolmogorov-Smirnov test)

    帰無仮説: ノンパラメトリック検定の1つ.2標本に対して使う場合には,2標本が,同一の母集団である.検定では,各標本の累積確率分布を使用.

    R システム で,2群 s1, s2 のコルモゴロフ–スミルノフ検定 (Kolmogorov-Smirnov test) を行うプログラム

    ks.test(s1, s2) 
    

    関連項目検定

    コンピュータビジョンのタスク

    コンピュータビジョンのタスクは種々があるが,次のようなものをあげることができる.

    シーン解析(scene parsing)

    シーン解析(scene parsing) では,画像全体の画素をクラスに分類する.各画素にクラスのラベルが割り当てられる. セマンティック・セグメンテーション (semantic segmentation) との違いとしては,画像全体の画素を何らかのクラスに分類する(クラスが不明な画素が無い)ことである.

    関連項目セマンティック・セグメンテーション (semantic segmentation)

    システム Python

    Ubuntu のシステム Python を用いるとき, python, pip は,次のコマンドで起動できる.

    Ubuntu のシステム Python を用いるとき, venv の実行は次のようになる.

    python3 -m venv <ディレクトリ名>
    

    関連項目Python, Python, pip, Python 開発環境,Python コンソールのコマンドでの起動

    シグモイド関数 (sigmoid function)

    シグモイド関数 (sigmoid function) は,次の関数である.

    f(x) = 1 / (1 + exp(-x))

    シグモイド関数は,活性化関数としてよく使用されるもののうちの1つである. 活性化関数は,ニューロンの入力の合計から,そのニューロンの活性度の値を決めるためのもの. (他には,ReLULReLUステップ関数ソフトマックス関数などがある.

    シャピロ・ウィルク検定 (Shapiro Wilk test)

    帰無仮説: 標本の母集団は正規分布である

    R システム で, Iris データセットの Sepal.Length についてのシャピロ・ウィルク検定を行うプログラム

    s1 <- iris[iris$Species=='setosa',]$Sepal.Length
    s2 <- iris[iris$Species=='versicolor',]$Sepal.Length
    s3 <- iris[iris$Species=='virginica',]$Sepal.Length
    
    shapiro.test( s1 )
    shapiro.test( s2 )
    shapiro.test( s3 )
    

    関連項目検定  

    ステップ関数 (step function)

    ステップ関数は,次の関数である.

    f(x) = x (x < 0 のとき), 1 (x > = 0 のとき)

    ステップ関数は,活性化関数としてもよく使用される.

    セマンティック・セグメンテーション (semantic segmentation)

    セマンティック・セグメンテーション (semantic segmentation)では, 画像内に人物 (person) がいるような場合,人物の領域に person というラベルを付ける. このとき,人物は複数いても問題ない.

    学習のときには,'road', 'slidewalk', 'building' のようなクラスについての学習を行う. 学習データでは,画像の画素に,'road', 'slidewalk', 'building' のようなクラス名(あるいはクラス番号)がラベルとして付いている. 学習済みデータで推論を行うと,画素に 'road', 'slidewalk', 'building' のようなラベルが付く.

    Cityscapes データセットのクラスは次の通りである(これらクラス以外に「unlabeled」がある).

    road, sidewalk, parking, rail track, person, rider, car, truck, bus, on rails, motorcycle, bicycle, caravan, trailer, building, wall, fence, guard rail, bridge, tunnel, pole, pole group, traffic sign, traffic light, vegetation, terrain, sky, ground, dynamic, static

    関連項目ADE20K データセット, BASNet (Boundary-Aware Salient object detection), BDD100K, CSAILVision, Cityscapes データセット, COCO (Common Object in Context) データセット, DeepLab2, DeepLabv3, DeepLabv3+, Mapillary Vistas Dataset (MVD), MIT Scene Parsing Benchmark, MMSegmentation, OCRNet, Pascal VOC (Pascal Visual Object Classes Challenge) データセット, Residual Networks (ResNets), SegFormer, U-Net, インスタンス・セグメンテーション (instance segmentation), コンピュータビジョンのタスク, シーン解析(scene parsing), 物体検出

    ソースコード

    ソースコードは,コンピュータのプログラムを,プログラミング言語で書いたもの.

    ソースコードからのビルド

    プログラムのソースコードを書き換えた場合,ソースコードからビルドしなおす.

    プログラムが,あるライブラリを使うとき, ライブラリの特定のバージョンのためにビルドされたプログラムが, そのライブラリの別のバージョンでは動かないことがある.そうした場合でも,ソースコードからビルドしなおす.

    プログラムが公開されているとき, ビルド済みの状態(実行可能な形式など)で配布されていることもあれば, ソースコードが公開されている場合もある. そして,それら両方が配布されている場合もある.そうした場合,ソースコードからのビルドを行う利点としては, 次のようなものがある.

    ソースコードは,コンピュータのプログラムを,プログラミング言語で書いたもの.

    ソフトマックス関数 (softmax function)

    次元数 n のベクトル x に対するソフトマックス関数 (softmax function) は,f(x[k]) = exp(x[k]) / (exp(x[1]) + exp(x[2]) + ... exp(x[n]))

    ニューラルネットワークの,ある層(レイヤ)の出力が one-hot 表現の出力であるときによく使用される.

    チェックポイント

    ある特定の時点での,モデルの変数の状態を表したデータのこと. チェックポイントにより,ニューラルネットワーク重み (weight) をエクスポートすることができるようになる.

    データサイエンス

    データサイエンスというとき,データを数理的に処理(事前に定義された数式に当てはめて処理)することにより, 処理された結果が,どのようにして算出されたかが明らかであり,算出に再現性があるという意味合いに加えて, その数理的処理において,体系だった学問があるという意味がある.

    データサイエンスでは,次のようなものを扱う.

    記述統計量,分布,相関,正規化,外れ値,クラスタリング,統計処理  

    データの前処理

    TensorFlowでは,入力の値が 0 から 1 の範囲の浮動小数点数にスケールする必要がある.

    データフレーム

    データフレームでは,データのデータ型は,列ごとに同じである. 列に属性名がある.

    関連項目Iris データセット, ks_1033_data, titanic データセット, ポケモンデータセット

    データ拡張 (data augmentation)

    データ拡張 (data augmentation)では,すでに存在するデータを利用して,データを変換することにより,データを増量する.

    ディープラーニング

    ディープラーニングは,層の浅いニューラルネットワークの組み合わせによる多層性の実現により勃興した分野. ジェフ・ヒントンらが見出したオートエンコーダやディープ・ビリーフ・ネットワークが基礎である.

    関連項目applications of deep neural networks, cnn (convolutional neural network), gan (generative adversarial network), gru (gated recurrent neural networks), keras, lstm (long short-term memory), pytorch tensorflow, ニューラルネットワーク, 強化学習, 層構造のニューラルワーク,

    ディープニューラルネットワーク

    ディープラーニングを行う ニューラルネットワーク. 「ディープモデル (deep model)」ともいう.  

    ドロップアウト

    学習の途中で, ニューラルネットワークを構成するニューロンを無作為(ランダム)に「あたかも存在しない状態」すること. 過学習の防止に効果がある場合があるとされる.

    参考文献: dropout: a simple way to prevent neural networks from overfitting, https://www.cs.toronto.edu/~rsalakhu/papers/srivastava14a.pdf

    参考文献: improving neural networks by preventing co-adaptation of feature detectors, corr, abs/1207.0580

    ニューラルネットワーク

    ニューラルネットワークは,人間の脳細胞を,信号が流れるネットワークと見立てたうえで, 個々の脳細胞を, 次の簡単な数理で組み立てるもの.

    ニューラルネットワークは,入力を与えると, 出力が出てくる. この仕組みにより,質問が与えられたときに,多数の選択肢の中から 1つを選ぶことなどもできる. 例えば,コンピュータに画像を見せて「男か女か」の答えを出す,年齢を「0から120の中から」答えるということができる.

    ニューラルネットワークは層で構成されている.隠れ層を持つのがふつうである. ニューロンには非線形性がある.

    ニューラルネットワークでは, 前もって,入力とそれに対する正解についての学習を行うことによって, 入力に対して,適切な出力が出てくるにようになる.

    ニューラルネットワークは 1980年内に登場した. ニューラルネットワークの技術革新としては,次のようなものがある.

    以上の背景から,ディープニューラルネットワークが広く使われるようになった.

    関連項目applications of deep neural networks, ディープラーニング

    ニューラルネットワークのビジュアライズ

    keras visualizer を用いて kerasニューラルネットワークをビジュアライズするプログラムは次の通り.

    from keras_visualizer import visualizer  
    visualizer(m, format='png')
    from PIL import Image
    Image.open('graph.png').show()
    

    windows の場合は,コマンドプロンプトを管理者として開き次のコマンドを実行する.

    python -m pip install git+https://github.com/lordmahyar/keras-visualizer
    

    google colaboratory では「!pip3 install git+https://github.com/lordmahyar/keras-visualizer」を実行

    !pip3 install git+https://github.com/lordmahyar/keras-visualizer
    
     

    ニューラルネットワークの種類

    ニューラルネットワークの種類には,次のようなものがある. 「教師あり」は,教師データを用いての 学習の機能があるもの. 「教師なし」は,そうでないものである.

    1. 教師あり

    2. 教師なし

      オートエンコーダ (autoencoder)

    ニューラルネットワークのビジュアライズ

    keras のモデルのビジュアライズについては: https://keras.io/ja/visualization/

    ニューラルネットワーク m のビジュアライズを行う keras のプログラム

    import pydot
    plot_model(m)
    

    ニューロン (neuron)

    ニューロンは, 複数の入力の総和に,バイアス (bias)を足したのち,ニューロンに設定された活性化関数を適用して得られた値を出力する. ニューロンの入力と出力の間には 重みがある. ニューロンの出力には,重みが掛け合わされたのちに,次のニューロンの入力になる.

    1つのニューロンは,複数の入力を取ることができる.出力は1つである.これら入力と出力は,次のいずれかの条件を満たす

    層構造のニューラルワークでは, バイアスは,ニューロンごとに違い, 活性化関数は,同じ層(レイヤ)ニューロンでは同じものとするのが通例.

    ニューロンの発火

    ニューロンの発火は, 所定のバイアス (bias)を超えたときに,1を出力すること.

    パーセプトロン (perceptron)

    パーセプトロンは,1つまたは複数の入力を取り,入力値の加重和に対して関数を実行し,1つの出力値を計算するシステムである. 機械学習では,関数として,reluシグモイド関数などの非線形関数を用いることが多い, 例えば,以下のパーセプトロンでは,x1, x2, x3, x4, x5 の加重和に対してシグモイド関数を実行し,出力値を得るものである. f(x1, x2, x3, x4, x5) = sigmoid(w1x1 + w2x2 + w3x3 + w4x4+ w5x5)

    パーセプトロンは, ニューラルネットワークは, 複数のパーセプトロンを接続したネットワークであり, バックプロパゲーションによりフィードバックを行う.  

    バイアス (bias)

    次の式では,b はバイアスである.

    y = b + w1 * x1 + w2 * x2 + ... + wn * xn
    

    ニューラルネットワークでのバイアスは個々のニューロンが持つ値.ニューロンの発火のしやすさを表す値とされる.

    ハイパーパラメータ (hyper parameter)

    ハイパーパラメータは,次の 2つである.

    ハイパーパラメータチューニング

    最適なハイパーパラメータを探索すること.  

    ハイパーパラメータチューニングを行うモデルの定義

    ハイパーパラメータチューニングを行うモデルの定義では, ハイパーパラメータの探索を行う探索空間を定義する.

    iris データセット を,3種類に分類する keras プログラムの例は次の通り.

    from __future__ import absolute_import, division, print_function, unicode_literals
    import tensorflow as tf
    from tensorflow.keras import layers
    import numpy as np
    from sklearn.datasets import load_iris
    import sklearn.model_selection
    from sklearn.preprocessing import normalize
    from IPython.display import display
    
    gpu = tf.config.list_physical_devices(device_type = 'GPU')
    if len(gpu) > 0:
        print("GPU:", gpus[0].name)
        tf.config.experimental.set_memory_growth(gpu[0], True)
    
    # データ
    num_classes = 3
        
    iris = load_iris()
    x = iris.data
    y = iris.target
    
    x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(x.reshape(x.shape[0], -1), y, train_size=0.5) 
    
    m = tf.keras.Sequential(
        [
            layers.Dense(units=64, input_dim=len(x_train[0]), activation='relu'),
            layers.Dropout(0.5),
            layers.Dense(num_classes, activation="softmax"),
        ]
    )
    
    print(m.summary())
    
    batch_size = 4
    epochs = 300
    
    m.compile(
        optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
        loss='sparse_categorical_crossentropy',
        metrics=['sparse_categorical_crossentropy', 'accuracy']
    )
    
    history = m.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, validation_data=(x_test, y_test))
    
    score = m.evaluate(x_test, y_test, verbose=0)
    print("Test loss:", score[0])
    print("Test accuracy:", score[1])
    
    # 分類
    predictions = m.predict(x_test)
    print(predictions.argmax(axis=1))
    # 正解の表示
    print(y_test)
    
    import pandas as pd
    h = pd.DataFrame(history.history)
    h['epoch'] = history.epoch
    print(h)
    
    # 学習曲線
    # https://www.tensorflow.org/tutorials/keras/overfit_and_underfit?hl=ja で公開されているプログラムを使用
    %matplotlib inline
    import matplotlib.pyplot as plt
    import warnings
    warnings.filterwarnings('ignore')   # Suppress Matplotlib warnings
    
    def plot_history(histories, key='binary_crossentropy'):
      plt.figure(figsize=(16,10))
    
      for name, history in histories:
        val = plt.plot(history.epoch, history.history['val_'+key],
                       '--', label=name.title()+' Val')
        plt.plot(history.epoch, history.history[key], color=val[0].get_color(),
                 label=name.title()+' Train')
    
      plt.xlabel('Epochs')
      plt.ylabel(key.replace('_',' ').title())
      plt.legend()
    
      plt.xlim([0,max(history.epoch)])
    
    plot_history([('history', history)], key='sparse_categorical_crossentropy')
    

    [image]

    バウンディングボックス (bounding box)

    写真やビデオの中での,対象領域を示す矩形. 取り扱いたい対象を囲むような矩形を作ることが多いことから「バウンディング」と呼ばれる.

    バッチ (batch)

    バッチ (batch) は, ミニバッチ学習 での 学習の1回のイテレーション (iteration) で使われるデータ集合などのこと.

    バウンディングボックス (bounding box)

    バウンディングボックス (bounding box) は, 画像で,オブジェクトなどを囲む四角形のこと.

    パッケージ (package)

    パッケージ (モジュール,インクルードファイルなどともいう) 複数のプログラムが共有して使えるような機能を持ったソースコード

    バックプロパゲーション (backpropagation)

    バックプロパゲーション (backpropagation) は, ニューラルネットワークで,勾配降下法 (gradient descent) を実行するためのアルゴリズムである. パラメータと損失偏微分を算出することにより,バックプロパゲーションが実行される.

    バッチサイズ (batch size)

    1つのバッチ (batch) の中のデータ等の数のこと. 確率的勾配降下法 (sgd 法) のバッチサイズは 1 である. ミニバッチ学習 でのバッチサイスは普通 10 から 100 である.

    バッチ正規化 (batch normalization)

    バッチ正規化 (batch normalization) は, ミニバッチ学習を行うとき,ミニバッチごとに, 隠れ層 (hidden layer) の活性化関数の入力や出力を, 正規化すること. 過学習 (overfitting) の緩和などの効果がある.

    バッチ正規化 (batch normalization) の代替とされる手法(adaptive gradient clipping 法など)も登場しつつある.

    keras で バッチ正規化 (batch normalization) を行うときは,次のように全結合を示す「dense」の直後に,「m.add(batchnormalization)」を入れる.

    keras のプログラム】

    from __future__ import absolute_import, division, print_function, unicode_literals
    import tensorflow as tf
    m = tf.keras.sequential()
    m.add(tf.keras.layers.flatten(input_shape=(28, 28)))
    m.add(tf.keras.layers.dense(units=128, activation='relu'))
    m.add(tf.keras.layers.batchnormalization())
    m.add(tf.keras.layers.dropout(0.5))
    m.add(tf.keras.layers.dense(units=10, activation='softmax'))
    

    ソフトマックス関数 (softmax function)活性化関数とするような層(レイヤ)では,batchnormalization は行わないようです.

    パラメータ (parameter)

    機械学習でのパラメータは, モデルの変数のうち,機械学習のシステムでの学習の対象になっているもの. モデルの変数でも,学習の対象になっていないものはハイパーパラメータである.

    ビルド

    ビルドは,プログラムのソースコードを,実行可能な形式や中間言語の形式に変換すること. 実行可能な形式のファイルは windows では .exe や .dll の拡張子が付いていることが多い.

    プーリング (pooling)

    直前の畳み込み層で生成された1つの行列(あるいは複数の行列)を,より小さな行列に縮小すること

    フィードフォワード (feed forward)

    ある層のニューロンでの結果を,次の層のニューロンが受け取る (それ以外にはない)ような構造になっているような ニューラルネットワークを「フィードフォワード」という.

    フォトグラメトリ

    フォトグラメトリ (Photogrammetry) は写真測量のこと.

    プロトコル・バッファ(protocol buffer)

    プロトコル・バッファ(protocol buffer)は,次のような proto ファイルを書き,様々なプログラミング言語のプログラムや機器の間でデータ交換等を行うためのもの.

    message Person {
      required string name = 1;
      required int32 id = 2;
      optional string email = 3;
    }
    

    関連項目プロトコル・バッファ・コンパイラ (protocol buffer compiler)

    プロトコル・バッファ・コンパイラ (protocol buffer compiler)

    インストールの公式ページ: https://grpc.io/docs/protoc-installation/

    関連項目Protobuf

    プロトコル・バッファ・コンパイラ (protocol buffer compiler) のインストール(Windows 上)
    1. コマンドプロンプトを管理者として開く.
    2. protoc のダウンロードと展開(解凍)

      23.3」のところにはバージョンを指定すること.

      https://github.com/protocolbuffers/protobuf/releases

      python -m pip install -U protobuf==3.19.6c:\protoc
      cd c:\protoc
      curl -L -O https://github.com/protocolbuffers/protobuf/releases/download/v23.3/protoc-23.3-win64.zip
      powershell -command "Expand-Archive -DestinationPath . -Path protoc-23.3-win64.zip"
      

      [image]
    3. Windowsシステム環境変数 Pathに,c:\protoc\bin追加することにより,パスを通す

      Windows で,コマンドプロンプト管理者として実行

      コマンドプロンプトを管理者として実行: 別ページ »で説明

      powershell -command "$oldpath = [System.Environment]::GetEnvironmentVariable(\"Path\", \"Machine\"); $oldpath += \";c:\protoc\bin\"; [System.Environment]::SetEnvironmentVariable(\"Path\", $oldpath, \"Machine\")"
      

      [image]
    Ubuntu でのプロトコル・バッファ・コンパイラ (protocol buffer compiler) のインストール

    Ubuntu でインストールを行うには,次のコマンドを実行.

    sudo apt -y update
    sudo apt -y install libprotobuf-dev protobuf-compiler protobuf-c-compiler python3-protobuf
    

    ボクセル化 (voxelize)

    ボクセル化は,3次元データをボクセル形式に変換すること.

    ボクセル化のソフトウェアとしては,binvox, cuda_voxelizer がある.

    binbox のURL: https://www.patrickmin.com/binvox/

    binbox の文献: Fakir S. Nooruddin and Greg Turk, Simplification and Repair of Polygonal Models Using Volumetric Techniques, IEEE Transactions on Visualization and Computer Graphics, vol. 9, no. 3, pp. 191--205, 2003.

    cuda_voxelizer の GitHub のページ: https://github.com/Forceflow/cuda_voxelizer

    .binbox 形式ファイルのボクセルデータを,STL 形式のデータに変換するソフトウェアとしては, binvox2mesh が知られる.

    binbox2mesh の GitLab のページ: https://gitlab.com/mandries/binvox2mesh

    ポケモンデータセット

    ポケモンデータセットの url: https://gist.github.com/armgilles

    次の Python プログラムは,ポケモンデータセットの主成分分析を行い,第1主成分,第2主成分,第3主成分,ポケモンデータセットの属性 Type 1 で3次元の散布図を表示する.

    次の Python プログラムでは,3次元の散布図のために, plotly の scatter_3d を用いている.

    !git clone https://gist.github.com/armgilles/194bcff35001e7eb53a2a8b441e8b2c6
    !mv 194bcff35001e7eb53a2a8b441e8b2c6/pokemon.csv .
    
    import numpy as np
    import pandas as pd
    from sklearn.datasets import load_iris
    import sklearn.decomposition
    %matplotlib inline
    import matplotlib.pyplot as plt
    import warnings
    warnings.filterwarnings('ignore')   # Suppress Matplotlib warnings
    import plotly.express as px
    from IPython.display import display
    
    pokemon = pd.read_csv("pokemon.csv")
    display(pokemon)
    
    x = pokemon.iloc[:,4:11].to_numpy()
    type1 = pokemon.iloc[:,2]
    pca = sklearn.decomposition.PCA(n_components=4)
    r = pca.fit_transform(x)
    
    fig = px.scatter_3d(x=r[:,0], y=r[:,1], z=r[:,2], color=type1, symbol=type1, opacity=0.4, 
                     labels={'x': '1', 'y': '2', 'z': '3', 'color': 'Type 1', 'symbol': 'Type 1'})
    fig.show()
    

    [image]

    マイクロソフト C++ ビルドツール (Microsoft C++ Build Tools)

    URL: https://visualstudio.microsoft.com/visual-cpp-build-tools/

    Windows での Build Tools for Visual Studio 2022(ビルドツール for Visual Studio 2022)のインストール: 別ページ »で説明

    マスク付き顔の処理

    マスク付き顔の処理には次のようなものがある.

    関連項目cabani の MaskedFace-Net データセット, Chandrika Deb の顔マスク検出 (Chandrika Deb's Face Mask Detection)

    マスターフェイス (master face)

    マスターフェイス (master face)は,顔認識 (face recognition)のシステムにおいて, そこに登録された顔のテンプレートの複数にマッチ (match) するような顔.

    顔認識のシステムは,他人の顔を間違って認識したり,あるいは人工知能が合成した顔を間違って認識したりすることがありえるものである.

    近年,種々の研究があり, 「Dlib, FaceNet, SphereFace の 3つの顔認識システムについて, 10未満のマスターフェイスが,LFW データセットの 40 パーセント以上にマッチする」という報告もある. (コメント:Dlib, FaceNet, SphereFace の優劣や評価ではなく,現行の顔認識システム全般の脆弱性の指摘であると受け止めることができると,本サイト作成者は考えています).

    関連項目顔識別 (face identification), 顔認識 (face recognition), 顔に関する処理

    マン・ホイットニーの U 検定 (Mann-Whitney U test, Wilcoxon rank sum test)

    帰無仮説: ノンパラメトリック検定の1つ.独立な2標本で,2標本が同じ母集団から得られた標本である.

    R システム で,2群 s1, s2 のマン・ホイットニーの U 検定を行うプログラム

    wilcox.test(s1, s2) 
    

    なお,correct=F を付けると,連続性の修正(continuity correction)を行わないようになる.

    wilcox.test(s1, s2, correct=F) 
    

    関連項目検定

    ミニバッチ (mini-batch)

    学習の繰り返しのうち,各々の繰り返しで使用されるバッチ全体の中からランダムに選ばられた部分集合である. ミニバッチバッチサイズは,ふつう,10 から 1000 である. ミニバッチの使用により,損失の計算を高速化できるとされている.  

    ミニバッチ学習

    ミニバッチ学習は,教師データの中から,「バッチ」あるいは「ミニバッチ」と呼ばれる少数を無作為に(ランダムに)選び出し,それを使って学習を行うこと.

    ミニバッチ確率勾配降下法 (mini-batch stochastic gradient descent)

    ミニバッチを使用する確率勾配降下法である. 学習データのミニバッチを用いて,勾配が算出される. 通常の確率的勾配降下法は,サイズ1のミニバッチを使用するミニバッチ確率勾配降下法と同じである.

    メッシュ簡略化 (Mesh Simplification)

    メッシュ簡略化は,メッシュの頂点数とポリゴン数の削減を行う.

    MeshLab を用いて,次の手順で, メッシュ簡略化 を行うことができる.

    1. MeshLab を使用.
    2. MeshLab で 「File」, 「Import Mesh...」.そして,ファイルを選ぶ.
    3. 「Filters」, 「Remashing, Simplification and Reconstruction」,「Simplification: Quadric Edge Collapse Decimation (with texture)」と操作.
    4. 設定し「Apply」.

    関連項目MeshLab, メッシュ平滑化 (Mesh Smoothing)

    メッシュ平滑化 (Mesh Smoothing)

    メッシュ平滑化は,メッシュをなめらかにする.

    MeshLab を用いて,次の手順で, メッシュ平滑化 を行うことができる.

    1. MeshLab を使用.
    2. MeshLab で 「File」, 「Import Mesh...」.そして,ファイルを選ぶ.
    3. 「Filters」, 「Smoothing, Fairing and Deformation」,「Laplacian Smooth」と操作.
    4. 設定し「Apply」.

    関連項目MeshLab, メッシュ簡略化 (Mesh Simplification)

    メトリクス(metrics)

    メトリクスは,モデルの性能を判定するための関数である. メトリクスは,損失関数とは違い,学習時には使用されない.

    Keras では,メトリクスは,関数のリストである.そして,Keras では,任意の損失関数メトリクスとして使うことができる.

    Kerasメトリクスのページ: https://keras.io/api/losses/index.html

    モデル

    機械学習での「モデル」は, 機械学習のシステムが教師データを用いて学習した内容を表現したものである.

    TensorFlowでは,「モデル」は次のような意味でつかわれる場合がある. ・TensorFlow グラフは,ニューラルネットワークによる予測がどのように計算されるかの構造を表現したもの. ・TensorFlow グラフの重みとバイアスの値は,学習により決定される.

    ディープニューラルネットワークのモデルには,次のようなものがある.

    関連項目PyTorch, torchvision のモデル, rwightman の PyTorch Image Models (TIMM)

    モメンタム (momentum)

    ある学習ステップは,現在のステップでの勾配だけでなく, その直前のステップの勾配にも依存するという考え方による勾配降下法. モメンタムでは,時間経過に伴いながら,勾配の指数加重移動平均を算出する.

    ライブラリ (library)

    ライブラリは,複数のプログラムが共有して使えるような機能を持ったプログラムのこと. 多くの場合,プログラムの実行時にリンク(結合)される  

    ラベル (label)

    ラベルは,クラスの番号やクラス名など,クラスを識別できる番号や文字列などのこと.

    リレーショナルデータベース管理システム

    リレーショナルデータベースシステムは,リレーショナルデータベースとリレーショナルデータベース管理システムから構成される.

    【サイト内のリレーショナルデータベース関連の資料】

     

    ロジット

    分類の結果として得られる数値ベクトルで,正規化されていないもの. ロジットに対しては,正規化が行われるのが普通である.

    多クラス分類では,ロジット正規化するために ソフトマックス関数 (softmax function)を用いるのが普通である. ソフトマックス関数 (softmax function)により,数値ベクトルが生成されるが,そのそれぞれの値が1クラスに対応する.

    ロジットの別の意味として,ロジットという言葉を,ロジット関数(シグモイド関数 (sigmoid function))という意味で使うことがある.

    あ〜ん (漢字)

    音データ(sound data)

    ffmpeg を用いて,m4a (mp4 audio) のファイルを 16 ビット 整数RAW big endian モノラルに変換

    ffmpeg -y -vn -sn -ar 44100 -i "sample.m4a" -ac 1 -ar 48000 -f s16be "output.raw"
    

    ffmpeg を用いて,16 ビット 整数RAW big endian モノラルのファイルを m4a (mp4 audio) に変換

    ffmpeg -y -vn -sn -ar 48000 -f u16be -i "output2.raw" -ac 1 -ar 48000 -acodec flac -f flac "output2.flac"
    

    関連項目librosa, ffmpeg

    重み (weight)

    線形モデルでの特徴での係数である. ニューラルネットワークで,あるニューロンニューロンが結合しているとき, 個々の結合には重みがある. 重みが大きいほど,当ニューロンの出力が強く,次のニューロンに渡される. 例えば, あるニューロンが,別の2つのニューロンと結合していて,それら2つの出力を受け取るとき, そのニューロンの入力は,w[1] * x[1] + w[2] * x[2] のよになる. w[1], w[2] は重み, x[1], x[2] は2つのニューロンの出力である.

    学習では,最適な重みが決定される.  

    重みの初期化

    重みの初期化 (weights initialization)  

    重みの方向ベクトル

    重みが複数あるとき,それらは重みの方向ベクトルをなす. 重みが複数あり,それら重みをそれぞれ増やしたり減らしたりする量は,重みの方向ベクトルをなす.

    音声処理のタスク

    音声処理のタスクには次のようなものがある.

    音声合成 (Text To Speech; TTS)

    人間の音声を合成すること.

    関連項目Coqui TTS, Speech synthesis, VALL-E X, VOICEVOX, 自然言語処理のタスク

    解釈可能性 (interpretability)

    モデルを用いた予測について,それが容易に説明できるかの度合い.

    顔に関する処理

    顔に関する処理には,次のようなものがある.

    顔のコード化

    顔のコード化では,顔を数値(複数の数値)に置き換える. このとき,同一人物の顔は,近い値の数値に, 違う人物の顔は,離れた値の数値になるようにコード化を行う.

    顔のデータベース

    顔のデータベースの有名なものには,

    などがある.これらの中には,シナリオが「in-the-wild」であるもの,顔が部分しか見えていないものを含むようなデータセットもある.

    その他,マスク付きの顔のデータセットには, cabani の MaskedFace-Net データセット, Chandrika Deb の顔マスク検出 (Chandrika Deb's Face Mask Detection) および顔のデータセット などがある.

    その他,顔のデータセットは, 300W (300 Faces-In-The_Wild) データセット, AgeDB データセット, C-MS-Celeb Cleaned データセットFERET データベース, HELEN データセット, iBUG 300-W データセット, IMM 顔データベース (IMM Face Database), MS-Celeb-1M データセット, MUCT 顔データベース, VGGFace2 データセットなどがある.

    関連項目オープンデータ

    顔の性別,年齢等の予測

    画像から顔の性別,年齢等の予測を行う.

    関連項目FairFace, 顔に関する処理

    顔検出 (face detection)

    顔検出 (face detection)は,写真やビデオの中の顔を検出すること.顔とそれ以外のオブジェクトを区別することも行う.

    顔検出 (face detection)の結果は, バウンディングボックスで得られるのが普通である.

    関連項目Chandrika Deb の顔マスク検出, Dlib の顔検出, Emotion-Investigator, InsightFace, RetinaFace, SCRFD (Sample and Computation Redistribution for Face Detection), TinaFace, WIDER FACE データセット 顔検証 (face verification), 顔識別 (face identification), 顔認識 (face recognition), 顔に関する処理, 物体検出

    顔検証 (face verification)

    顔検証 (face verification)は, 顔と顔とを比べてマッチするか(同一人物であるか)を調べること. 本人確認などで 顔検証 (face verification) が行われる.

    関連項目ArcFace 法, MobileFaceNets, マスターフェイス (master face), 顔検出 (face detection), 顔識別 (face identification), 顔認識 (face recognition), 顔に関する処理

    顔識別 (face identification)

    顔識別 (face identification)では,ある顔と,データベースの中の多数の顔についての情報を用いて, 顔が誰であるのかの個人の特定を行う. このとき,データベースの中の多数の顔とのマッチングが行われる.

    関連項目ArcFace 法, マスターフェイス (master face), 顔検証 (face verification), 顔検出 (face detection), 顔認識 (face recognition), 顔に関する処理

    顔認識 (face recognition)

    顔認識 (face recognition)は, 写真やビデオについて顔検出 (face detection)を行い, その結果として得られた顔について(複数の顔が得られた場合にはそれぞれについて), 顔識別 (face identification) を(データベースの中の多数の顔についての情報を用いての,個人の特定)を行う.

    関連項目ArcFace 法, LFW データセット, マスターフェイス (master face), 顔検証 (face verification), 顔検出 (face detection), 顔識別 (face identification), 顔に関する処理

    顔ランドマーク (facial landmark)

    顔ランドマーク (facial landmark)は, 顔について,目,眉,鼻,口,あごのラインなどのアノテーションを行ったもの. 目,眉,鼻,口,あごのラインなど,顔のパーツの構造を特定できる形状予測器 (shape predictor) の学習に使うことができる.

    関連項目AFLW (Annotated Facial Landmarks in the Wild) データセット, UTKFace データセット, 顔に関する処理, 顔の 68 ランドマーク, 顔ランドマークの3次元化

    顔ランドマークの3次元化

    ディープラーニングを用いて 顔ランドマーク (facial landmark)の3次元化する学習済みモデルは,次のページで公開されている.

    https://www.adrianbulat.com/face-alignment

    関連項目顔ランドマーク(facial landmark)

    過学習 (overfitting)

    教師データにはよく適合しているが,新しいデータに対しては,正しい予測ができないようなモデルを生成すること.

    過学習では, 訓練データでは精度が高く,損失が少ないが, 検証データでは精度が低く,損失が多いというように,訓練データと検証データでの乖離が起きている.  

    学習 (learning)

    学習は,より正しい出力が得られるように, ニューラルネットワーク重みバイアスを修正すること. あるいは, 最適な出力が得られるように, 重みバイアスを最適化すること.

    そのために,教師データのうち,入力を使い, ニューラルネットワークを動かす. そして,正解の出力を使い, 損失関数の値ができるだけ小さくなるように, オプティマイザ(最適化器)を用いて, ニューラルネットワークを構成するニューロン重みバイアスなど, ニューラルネットワークのパラメータを修正する.

    学習曲線 (learning curve)

    学習の繰り返しによる損失の変化を示したグラフ.

    学習済みモデル (trained model)

    学習を終えたモデルのこと.  

    学習不足 (underfitting)

    教師データに対して,モデルの学習の余地が残っていること.

    学習不足の原因は種々あり得る.

    学習率 (learning rate)

    勾配降下法を用いてモデル学習を行うときに使用される値である. 勾配降下法では,イテレーションごとに,勾配学習率の掛け算を行う. その結果として得られる積を「gradient step」と言う. 学習率は,ハイパーパラメータの1つである.

    学習率をダイナミックに変化させる技術には, AdaDelta 法Adam 法などが知られる.

    確率勾配降下法 (SGD, stochastic gradient descent)

    バッチサイズが 1として,勾配降下法を実行すること. これは,教師データから,ランダムに1つのを選び,勾配を算出して,学習を行う.

    確率的勾配降下法 (SGD 法) は,次の方法で行う勾配降下法である.

    m.compile(
        optimizer=tf.keras.optimizers.SGD(learning_rate=0.0001, momentum=0.9, nesterov=True), 
        loss='sparse_categorical_crossentropy',
        metrics=['sparse_categorical_crossentropy', 'accuracy']
    )
    

    隠れ層 (hidden layer)

    ニューラルネットワークで,入力層出力層の間の

    画素

    MNIST データセットは,濃淡画像 70000枚である.その画素は 0 から 255 の値になっている.

    [image]

    画像全体は配列として扱うことが多い.

    [image]

    画像

    関連項目動画については,「動画」の項目で説明している.

    画像データの形式変換

    画像の形式変換は,ImageMagickを用いて行うことができる.

    convert a.png a.jpg
    
    画像のサイズ変更 (image resize)

    次の Python プログラムは,画像ファイル http://images.cocodataset.org/train2017/000000310645.jpg のダウンロードとロードを行ったのち, 画像のサイズ変更を行う.画像の表示も行う.

    from PIL import Image
    import requests
    
    # ダウンロードとロード
    url = 'http://images.cocodataset.org/train2017/000000310645.jpg'
    response = requests.get(url)
    img = Image.open(requests.get(url, stream=True).raw)
    
    # サイズ変更と確認表示
    img2 = img.resize((400, 200), Image.ANTIALIAS)
    display(img2)
    

    [image]
    画像の切り出し (image crop)

    次の Python プログラムは,画像ファイル http://images.cocodataset.org/train2017/000000310645.jpg のダウンロードとロードを行ったのち, 画像を正方形に切り出す.画像の表示も行う.

    from PIL import Image
    import requests
    
    def square(img):
        width, height = img.size
        if height > width:
          e = (height - width) / 2
          region = (0, e, width, width + e)
        else:
          e = (width - height) / 2
          region = (e, 0, height + e, height)
    
        return img.crop(region)
    
    # ダウンロードとロード
    url = 'http://images.cocodataset.org/train2017/000000310645.jpg'
    response = requests.get(url)
    img = Image.open(requests.get(url, stream=True).raw)
    
    # 切り出しと確認表示
    display(square(img))
    

    [image]
    画像ファイルのダウンロードとロード

    次の Python プログラムは,画像ファイル http://images.cocodataset.org/train2017/000000310645.jpg のダウンロードとロードを行う.画像の表示も行う.

    1. 前準備
      pip install pillow
      
    2. プログラムのソースコードと実行結果
      from PIL import Image
      import requests
      from IPython.display import display
      
      # ダウンロードとロード
      url = 'http://images.cocodataset.org/train2017/000000310645.jpg'
      response = requests.get(url)
      img = Image.open(requests.get(url, stream=True).raw)
      
      # 確認表示
      display(img)
      

      [image]

    画像データのデータ拡張 (image data augmentation)

    CIFAR-10 データセットについて,データ拡張のために フリップと回転を行う Keras のプログラムは次の通りである.

    from __future__ import absolute_import, division, print_function, unicode_literals
    import tensorflow as tf
    import numpy as np
    import tensorflow_datasets as tfds
    
    # CIFAR-10 データセットのロード
    cifar10, cifar10_metadata = tfds.load('cifar10', with_info = True, shuffle_files=True, as_supervised=True, batch_size = -1)
    x_train, y_train, x_test, y_test = cifar10['train'][0], cifar10['train'][1], cifar10['test'][0], cifar10['test'][1]
    print(cifar10_metadata)
    
    # 増量
    INPUT_SHAPE = [32, 32, 3]
    data_augmentation = tf.keras.Sequential()
    data_augmentation.add(tf.keras.layers.experimental.preprocessing.RandomFlip("horizontal", input_shape=INPUT_SHAPE))
    data_augmentation.add(tf.keras.layers.experimental.preprocessing.RandomRotation(0.1))
    
    def f(x):
        tf.reshape(data_augmentation(tf.reshape(x, (1, INPUT_SHAPE[0], INPUT_SHAPE[1], INPUT_SHAPE[2]))), (INPUT_SHAPE[0], INPUT_SHAPE[1], INPUT_SHAPE[2]))
    
    display([*map(f, x_train)])
    

    画像分類 (image classification)

    画像分類は,画像からそのクラス名を求めるもの.

    Big Tranfer ResNetV2, CSPNet, MobileNetV2MobileNetV3, Inception-Resnet, ResNet50, ResNet101, ResNet152, ResNeXt, DenseNet121, DenseNet169NASNet, Vision Transformer, Wide ResNet などの画像分類のモデルがある.

    CSPNet, 
    文献: CSPNet: A New Backbone that can Enhance Learning Capability of CNN - https://arxiv.org/abs/1911.11929
    公式の実装: https://github.com/WongKinYiu/CrossStagePartialNetworks
    rwightman の PyTorch Image Models (TIMM) の画像分類モデルの説明(Papers With Code 内): https://paperswithcode.com/lib/timm/csp-resnet
    CSPResNet is a convolutional neural network where we apply the Cross Stage Partial Network (CSPNet) approach to ResNet. The CSPNet partitions the feature map of the base layer into two parts and then merges them through a cross-stage hierarchy. The use of a split and merge strategy allows for more gradient flow through the network.
    
    import timm
    m = timm.create_model('cspresnet50', pretrained=True)
    m.eval()
    
    
    MobileNetV3,
    文献: Searching for MobileNetV3 - https://arxiv.org/abs/1905.02244
    公式の実装: https://github.com/tensorflow/models/tree/master/research/slim/nets/mobilenet
    rwightman の PyTorch Image Models (TIMM) の画像分類モデルの説明(Papers With Code 内): https://paperswithcode.com/lib/timm/mobilenet-v3
    MobileNetV3 is a convolutional neural network that is designed for mobile phone CPUs. The network design includes the use of a hard swish activation and squeeze-and-excitation modules in the MBConv blocks.
    
    import timm
    m = timm.create_model('mobilenetv3_large_100', pretrained=True)
    m.eval()
    
    
    Inception-Resnet,
    文献: Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning - https://arxiv.org/abs/1602.07261
    実装: https://github.com/Cadene/pretrained-models.pytorch
    rwightman の PyTorch Image Models (TIMM) の画像分類モデルの説明(Papers With Code 内): https://paperswithcode.com/lib/timm/inception-resnet-v2
    Inception-ResNet-v2 is a convolutional neural architecture that builds on the Inception family of architectures but incorporates residual connections (replacing the filter concatenation stage of the Inception architecture).
    
    import timm
    m = timm.create_model('inception_resnet_v2', pretrained=True)
    m.eval()
    
    
    ResNet152, 
    文献: Deep Residual Learning for Image Recognition - https://arxiv.org/abs/1512.03385
    実装: https://github.com/pytorch/vision/tree/master/torchvision/models
    rwightman の PyTorch Image Models (TIMM) の画像分類モデルの説明(Papers With Code 内): https://paperswithcode.com/lib/timm/resnet
    Residual Networks, or ResNets, learn residual functions with reference to the layer inputs, instead of learning unreferenced functions. Instead of hoping each few stacked layers directly fit a desired underlying mapping, residual nets let these layers fit a residual mapping. They stack residual blocks ontop of each other to form network: e.g. a ResNet-50 has fifty layers using these blocks. 
    
    import timm
    m = timm.create_model('resnet152', pretrained=True)
    m.eval()
    
    ResNeXt, 
    文献: Aggregated Residual Transformations for Deep Neural Networks - https://arxiv.org/abs/1611.05431
    実装: Code: https://github.com/pytorch/vision/tree/master/torchvision/models
    rwightman の PyTorch Image Models (TIMM) の画像分類モデルの説明(Papers With Code 内): https://paperswithcode.com/lib/timm/resnext
    A ResNeXt repeats a building block that aggregates a set of transformations with the same topology. Compared to a ResNet, it exposes a new dimension, cardinality (the size of the set of transformations) , as an essential factor in addition to the dimensions of depth and width. 
    
    import timm
    m = timm.create_model('resnext50_32x4d', pretrained=True)
    m.eval()
    
    DenseNet169,
    文献: Densely Connected Convolutional Networks - https://arxiv.org/abs/1608.06993
    実装: https://github.com/pytorch/vision/tree/master/torchvision/models
    rwightman の PyTorch Image Models (TIMM) の画像分類モデルの説明(Papers With Code 内): https://paperswithcode.com/lib/timm/densenet
    DenseNet is a type of convolutional neural network that utilises dense connections between layers, through Dense Blocks, where we connect all layers (with matching feature-map sizes) directly with each other. To preserve the feed-forward nature, each layer obtains additional inputs from all preceding layers and passes on its own feature-maps to all subsequent layers.
    
    import timm
    m = timm.create_model('densenet169', pretrained=True)
    m.eval()
    
    
    NASNet, 
    文献: Learning Transferable Architectures for Scalable Image Recognition - https://arxiv.org/abs/1707.07012
    実装: https://github.com/Cadene/pretrained-models.pytorch
    rwightman の PyTorch Image Models (TIMM) の画像分類モデルの説明(Papers With Code 内): https://paperswithcode.com/lib/timm/nasnet
    NASNet is a type of convolutional neural network discovered through neural architecture search. The building blocks consist of normal and reduction cells.
    
    import timm
    m = timm.create_model('nasnetalarge', pretrained=True)
    m.eval()
    
    Big Tranfer ResNetV2, 
    文献: Big Transfer (BiT): General Visual Representation Learning - https://arxiv.org/abs/1912.11370
    公式の実装: https://github.com/google-research/big_transfer
    rwightman の PyTorch Image Models (TIMM) の画像分類モデルの説明(Papers With Code 内): https://paperswithcode.com/lib/timm/big-transfer
    Big Transfer (BiT) is a type of pretraining recipe that pre-trains on a large supervised source dataset, and fine-tunes the weights on the target task. Models are trained on the JFT-300M dataset. The finetuned models contained in this collection are finetuned on ImageNet.
    
    import timm
    m = timm.create_model('resnetv2_101x1_bitm', pretrained=True)
    m.eval()
    
    related resnetv2
    
    Vision Transformer, 
    文献: An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale - https://arxiv.org/abs/2010.11929
    公式の実装: https://github.com/google-research/vision_transformer
    rwightman の PyTorch Image Models (TIMM) の画像分類モデルの説明(Papers With Code 内): https://paperswithcode.com/lib/timm/vision-transformer
    The Vision Transformer is a model for image classification that employs a Transformer-like architecture over patches of the image. This includes the use of Multi-Head Attention, Scaled Dot-Product Attention and other architectural features seen in the Transformer architecture traditionally used for NLP.
    
    import timm
    m = timm.create_model('vit_large_patch16_224', pretrained=True)
    m.eval()
    
    Wide ResNet
    文献: https://arxiv.org/abs/1605.07146v4
    rwightman の PyTorch Image Models (TIMM) の画像分類モデルの説明(Papers With Code 内): https://github.com/rwightman/pytorch-image-models
    Wide Residual Networks are a variant on ResNets where we decrease depth and increase the width of residual networks. This is achieved through the use of wide residual blocks.
    
    import timm
    m = timm.create_model('wide_resnet169_2', pretrained=True)
    m.eval()
    

    関連項目Big Tranfer ResNetV2, CSPNet, MobileNetV2MobileNetV3, Inception-Resnet, ResNet50, ResNet101, ResNet152, ResNeXt, rwightman の PyTorch Image Models (TIMM) DenseNet121, DenseNet169NASNet, Vision Transformer, Wide ResNet Residual Networks (ResNets), SPP (Spatial Pyramid Pooling)  

    活性化関数

    活性化関数は,ニューロンの入力の合計から,そのニューロンの出力(活性度の値)を求めるための関数である. 活性化関数には,次のようなものがある.

    株価データ

    pandas_datareader を用いて Stoop から,株価のデータをダウンロードし,mplfinance を用いて確認表示する.

    1. pandas_datareader, mplfinance のインストール

      pip を用いて pandas_datareader, mplfinance をインストールする

    2. 次の Python プログラムは, pandas_datareader を用いて Stoop から,株価のデータをダウンロードし,mplfinance を用いて確認表示(ろうそく足,出来高,移動平均線のプロット)する.
      import pandas_datareader.data as pdrdata
      import mplfinance
      
      name = "1301.JP"
      a = pdrdata.DataReader(name,"stooq")
      mplfinance.plot(a, type='candle', volume=True, mav=(5, 50))
      

      [image]

    関連項目Pandas, Python, Stoop, オープンデータ

    教師あり学習 (supervised learning)

    入力データとそれに対応する正解から,モデル学習すること.  

    教師データ

    教師データは,次の2つのセット.

    「訓練データ」などともいう.

    教師なし学習 (unsupervised learning)

    正解となるラベルのないデータを用いて学習を行うこと.クラスタリングなどがある.

    距離学習

    距離学習は,同一クラスであれば距離が小さく, 違うクラスであれば距離が遠くなるような数値ベクトル(数値の並び)を,機械学習によって得ることである.

    距離学習は,2つの顔画像が同一人物であるかを判定したり,顔画像が既知の人物の誰であるかを特定したり(あるいは,既知の人物ではないと判定しあり)する場合に役立つ.

    距離学習と分類は違う.分類は,全クラスに属するデータを事前に得て学習させることを行う. 距離学習は,全クラスに属するデータを事前に得ることができないことを前提とする. 距離学習は,推論のときに,未知のクラスのデータが与えられる可能性があるなど,クラス数が不定である場合に有用である.  

    訓練

    訓練は,学習ともいう.

    検証 (validation)

    学習のときに,機械学習のモデルの品質を,検証用のデータを用いて評価する. 検証用のデータは,教師データとは独立したものである必要がある.

    検定

    検定には次のようなものがある.検定のときに,度数分布(ヒストグラム)をあわせて作成しておくことは,良い手がかりになる.

     

    交差エントロピー

    多クラスの交差エントロピーは,

    のとき,次の通り.

    -sigma_i( t[i] * log( y[i] ) )

    2クラスの交差エントロピーは,

    のとき,次の通り.

    -sigma_i( t[i] * log( y[i] + (1 - t[i]) * (1 - log( y[i]) )

    勾配 (gradient)

    勾配は,すべての自由変数について偏微分を行った結果として得られる ベクトルである.

    機械学習では,モデル関数の偏微分を行った結果として得られるベクトルである. 重みに関する損失関数勾配は,損失関数の値を最も減らすような重みの方向ベクトルである.

    勾配消失問題 (vanishing gradient problem)

    ニューラルネットワーク入力層に近い隠れ層について,その勾配が 0 に近くなる傾向のこと. 勾配が 0 に近くなると,学習における重みの変化が小さくなり,学習がうまく行えなくなる. LSTM (Long Short-Term Memory) は勾配消失問題を解決できるとされている.

    国土数値情報

    混合行列 (confusion matrix)

    分類モデル (classification model) での分類結果について集計した N かける N の表. N はクラス数である. 分類モデルでの分類として得られたクラスと, 実際のクラス(正解のクラス)とを,縦方向と横方向にする.

    勾配降下法 (gradient descent)

    モデルのパラメータについて,損失勾配を算出することにより, 損失を最小化する方法の1つ. 損失を最小化するような重みバイアスの最適な組み合わせに徐徐に近づけるために,パラメータの調整を繰り返す.

    最小全域木 (minimum spanning tree)

    最小全域木 (minimum spanning tree) を作成する R システムのプログラムは, 別ページ »で説明している.

    散布図

    散布図(縦軸のラベル,横軸のラベル,凡例の表示付き)の作成を行う Python プログラムを紹介する. plotly を使うものと,Seaborn を使うものと,Matplotlib を使うものを紹介する.

    plotly を用いた散布図の例

    次の Python プログラムは,Iris データセットの散布図を表示する.

    次の Python プログラム は Iris データセットの 'sepal length (cm)', 'sepal width (cm)' を横軸と縦軸の値として散布図を書く. 'species' を使って色を付けるとともに,形を変える. 縦軸のラベル,横軸のラベル,凡例の表示も行う. Pandas データフレームから散布図を作成しているのは,このプログラムの末尾の2行である.

    import numpy as np
    import pandas as pd
    from sklearn.datasets import load_iris
    %matplotlib inline
    import matplotlib.pyplot as plt
    import warnings
    warnings.filterwarnings('ignore')   # Suppress Matplotlib warnings
    import plotly.express as px
    from IPython.display import display
    
    iris = load_iris()
    df = pd.DataFrame(iris.data, columns=iris.feature_names)
    df['species'] = iris.target_names[iris.target]
    
    fig = px.scatter(df, x="sepal width (cm)", y="sepal length (cm)", color='species', symbol='species', opacity=0.4)
    fig.show()
    

    [image]

    次の Python プログラムは,Iris データセットの散布図を表示する.

    次の Python プログラムの関数 scatter_plot_matplotlib は x, y を横軸と縦軸の値として散布図を書く. target を使って色を付けるとともに,形を変える. このプログラムは,numpy ndarray のデータを散布図にしたいときの見本として作成した. 散布図を作成しているのは,このプログラムの末尾の2行である.

    import numpy as np
    import pandas as pd
    from sklearn.datasets import load_iris
    %matplotlib inline
    import matplotlib.pyplot as plt
    import warnings
    warnings.filterwarnings('ignore')   # Suppress Matplotlib warnings
    import plotly.express as px
    from IPython.display import display
    
    iris = load_iris()
    df = pd.DataFrame(iris.data, columns=iris.feature_names)
    df['species'] = iris.target_names[iris.target]
    
    x = df['sepal length (cm)'].to_numpy()
    y = df['sepal width (cm)'].to_numpy()
    target = df['species']
    
    fig = px.scatter(x=x, y=y, color=target, symbol=target, opacity=0.4, 
                     labels={'x': 'sepal length (cm)', 'y': 'sepal width (cm)', 'color': 'species', 'symbol': 'species'})
    fig.show()
    

    [image]
    plotly とDash の連携の例

    関連する外部ページ】 https://dash.plot.ly/getting-started

    import dash
    import dash_table
    import dash_core_components as dcc
    import dash_html_components as html
    import pandas as pd
    import seaborn as sns
    import plotly.graph_objs as go
    
    X = sns.load_dataset('iris')
     
    external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
    
    app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
    
    app.layout = html.Div(children=[
        html.H1(children='Iris DataSet'),
    
        html.Div(children='''
            Iris DataSet Display
        '''),
    
        dcc.Graph(
            id='example-graph',
            figure={
                'data': [
                    go.Scatter(
                        x = X[X.iloc[:,4]==i].iloc[:,0], 
                        y = X[X.iloc[:,4]==i].iloc[:,1],
                        mode = 'markers', 
                        marker={
                            'size': 10, 
                            'line': {'width': 0.5, 'color': 'white'}
                        }, 
                        opacity = 0.5, 
                        name=i
                    ) for i in X.iloc[:,4].unique()  
                ],
                'layout': {
                    'title': 'Iris DataSet Graph'
                }
            }
        )
    
    ])
    
    Seaborn を用いた散布図の例

    次の Python プログラムは,Iris データセットの散布図を表示する.

    次の Python プログラム は Iris データセットの 'sepal length (cm)', 'sepal width (cm)' を横軸と縦軸の値として散布図を書く. 'species' を使って色を付ける. 縦軸のラベル,横軸のラベル,凡例の表示も行う. Pandas データフレームから散布図を作成しているのは,このプログラムの末尾の3行である.

    import numpy as np
    import pandas as pd
    from sklearn.datasets import load_iris
    %matplotlib inline
    import matplotlib.pyplot as plt
    import warnings
    warnings.filterwarnings('ignore')   # Suppress Matplotlib warnings
    import seaborn as sns
    from IPython.display import display
    
    iris = load_iris()
    df = pd.DataFrame(iris.data, columns=iris.feature_names)
    df['species'] = iris.target_names[iris.target]
    
    nump = np.max(pd.factorize(df['species'])[0] + 1)
    plt.style.use('ggplot')
    sns.scatterplot(x='sepal length (cm)', y='sepal width (cm)', hue='species', data=df, palette=sns.color_palette("hls", nump), legend="full", alpha=0.4)
    

    [image]

    次の Python プログラムは,Iris データセットの散布図を表示する.

    次の Python プログラムの関数 scatter_plot_matplotlib は x, y を横軸と縦軸の値として散布図を書く. target を使って色を付ける. xlabel, ylabel, target_name は,横軸の名前,縦軸の名前,凡例のタイトルをグラフに表示させるためのもの. このプログラムは,numpy ndarray のデータを散布図にしたいときの見本として作成した.

    import numpy as np
    import pandas as pd
    from sklearn.datasets import load_iris
    %matplotlib inline
    import matplotlib.pyplot as plt
    import warnings
    warnings.filterwarnings('ignore')   # Suppress Matplotlib warnings
    import seaborn as sns
    from IPython.display import display
    
    iris = load_iris()
    df = pd.DataFrame(iris.data, columns=iris.feature_names)
    df['species'] = iris.target_names[iris.target]
    
    def scatter_plot_sns(x, y, xlabel, ylabel, target, target_name, alpha):
        # x, y, target は同じ長さの1次元の numpy.ndarray
        df = pd.DataFrame(np.stack([x, y, target], 1), columns=[xlabel, ylabel, target_name])
        nump = np.max(pd.factorize(df['species'])[0] + 1)
        g = sns.scatterplot(x=xlabel, y=ylabel, hue=target_name, data=df, palette=sns.color_palette("hls", nump), legend="full", alpha=alpha)
        plt.show()
    
    plt.style.use('ggplot')
    scatter_plot_sns(df['sepal length (cm)'].to_numpy(), df['sepal width (cm)'].to_numpy(), 'sepal length (cm)', 'sepal width (cm)', df['species'], 'species', 0.4)
    

    [image]

    次のプログラムも M の最初の2列を横軸と縦軸の値として散布図を書く. b を使って色を付ける.今度は,seaborn の lmplot を使用

    def scatter_plot(M, b, alpha):
        a12 = pd.DataFrame( M[:,0:2], columns=['a1', 'a2'] )
        a12['target'] = b
        sns.lmplot(x='a1', y='a2', data=a12, hue='target', scatter_kws={'alpha': alpha}, fit_reg=False)
    
    Matplotlib を用いた散布図の例

    次の Python プログラムは,Iris データセットの散布図を表示する.

    次の Python プログラムの関数 scatter_plot_matplotlib は x, y を横軸と縦軸の値として散布図を書く. target を使って色を付ける. xlabel, ylabel, target_name は,横軸の名前,縦軸の名前,凡例のタイトルをグラフに表示させるためのもの.

    import numpy as np
    import pandas as pd
    from sklearn.datasets import load_iris
    %matplotlib inline
    import matplotlib.pyplot as plt
    import warnings
    warnings.filterwarnings('ignore')   # Suppress Matplotlib warnings
    from IPython.display import display
    
    iris = load_iris()
    df = pd.DataFrame(iris.data, columns=iris.feature_names)
    df['species'] = iris.target_names[iris.target]
    
    def scatter_plot_matplotlib(x, y, xlabel, ylabel, target, target_name, alpha):
        # x, y, target は同じ長さの1次元の numpy.ndarray
        f = pd.factorize(target)
        plt.style.use('ggplot')
        fig, ax = plt.subplots()
        for i in range(np.min(f[0]), np.max(f[0]) + 1):
          ax.scatter(x=x[f[0] == i], y=y[f[0] == i], alpha=alpha, label=target[np.where(f[0] == i)[0][0]])
        ax.legend(title = target_name)
        plt.xlabel(xlabel)
        plt.ylabel(ylabel)
        plt.show()
    
    plt.style.use('ggplot')
    scatter_plot_matplotlib(df['sepal length (cm)'].to_numpy(), df['sepal width (cm)'].to_numpy(), 'sepal length (cm)', 'sepal width (cm)', df['species'], 'species', 0.4)
    

    [image]

    次の Python プログラムは,Iris データセットの散布図を表示する.

    データフレーム df について, は 'sepal length(cm)', 'sepal width(cm)' を横軸と縦軸の値として散布図を書く. 'species' の値を使って色を付ける. 横軸の名前,縦軸の名前を表示させる. 上のプログラムとは違って凡例は表示しない.プログラムは簡単になっている

    import pandas as pd
    from sklearn.datasets import load_iris
    %matplotlib inline
    import matplotlib.pyplot as plt
    import warnings
    warnings.filterwarnings('ignore')   # Suppress Matplotlib warnings
    from IPython.display import display
    
    iris = load_iris()
    df = pd.DataFrame(iris.data, columns=iris.feature_names)
    df['species'] = iris.target_names[iris.target]
    
    df['plot_color'] = pd.factorize(df['species'])[0]
    plt.style.use('ggplot')
    plt.scatter(x='sepal length (cm)', y='sepal width (cm)', c='plot_color', data=df, alpha=0.4)
    plt.xlabel('sepal length (cm)')
    plt.ylabel('sepal width (cm)')
    plt.show()
    

    [image]

    時系列データ(time series data)

    時系列データは,「昨日の気温は15度,今日の気温が13度」のように,時間とともに,値が変化するようなデータである.

    関連項目Johns Hopkins 大の COVID-19 データレポジトリ

    時系列データのニューラルネットワークでの扱い

    時系列データをニューラルネットワークで扱うとき, 前回の推論時でのニューロンの出力の一部を,次の推論に反映させることが役立つ. 例えば,10月23日のデータでの推論時のでの ニューロンの出力の一部を,10月24日のデータでの推論に反映させるようなことである.

    前回の推論時での出力の一部を,次の推論に反映させるために, 前回の推論時でのニューロンの出力が, 次の推論時で,同じニューロンの入力の一部になるようにするなどで,ニューラルネットワークを作る場合がある. そのようなニューラルネットワークには, リカレントニューラルネットワークがある. リカレントニューラルネットワークには, LSTM (Long Short-Term Memory), GRU (Gated Recurrent Neural Networks) などのバリエーションがある.

    関連項目】 GRU (Gated Recurrent Neural Networks), LSTM (Long Short-Term Memory), リカレントニューラルネットワーク

    次元削減 (dimension reduction)

    特徴ベクトルの特定の属性を表現するのに用いられる次元の数を削減すること.  

    事前学習

    収束

    収束は, 学習において, 学習を繰り返したのち, 学習を 1回行うごとの training loss と validation loss の変化がとても少なくなっているか,そうでないかの判断を場合に関係する.

    主成分分析 (principal component alalysis)

    次の Python プログラムは,Iris データセットの主成分分析を行い,第1主成分,第2主成分,Iris データセットの属性 species で散布図を表示する.

    次の Python プログラム では Iris データセットの主成分分析の第1主成分,第2主成分を横軸と縦軸の値として散布図を書く. 'species' を使って色を付けるとともに,形を変える. 縦軸のラベル,横軸のラベル,凡例の表示も行う.

    import numpy as np
    import pandas as pd
    from sklearn.datasets import load_iris
    import sklearn.decomposition
    %matplotlib inline
    import matplotlib.pyplot as plt
    import warnings
    warnings.filterwarnings('ignore')   # Suppress Matplotlib warnings
    import plotly.express as px
    from IPython.display import display
    
    iris = load_iris()
    df = pd.DataFrame(iris.data, columns=iris.feature_names)
    df['species'] = iris.target_names[iris.target]
    
    pca = sklearn.decomposition.PCA(n_components=4)
    r = pca.fit_transform(df.iloc[:,0:4].to_numpy())
    
    fig = px.scatter(x=r[:,0], y=r[:,1], color=df['species'], symbol=df['species'], opacity=0.4, 
                     labels={'x': '1', 'y': '2', 'color': 'species', 'symbol': 'species'})
    fig.show()
    

    [image]

    次の Python プログラムは,Iris データセットの主成分分析を行い,第1主成分,第2主成分,第3主成分,Iris データセットの属性 species で3次元の散布図を表示する.

    次の Python プログラムでは,3次元の散布図のために, plotly の scatter_3d を用いている.

    import numpy as np
    import pandas as pd
    from sklearn.datasets import load_iris
    import sklearn.decomposition
    %matplotlib inline
    import matplotlib.pyplot as plt
    import warnings
    warnings.filterwarnings('ignore')   # Suppress Matplotlib warnings
    import plotly.express as px
    from IPython.display import display
    
    iris = load_iris()
    df = pd.DataFrame(iris.data, columns=iris.feature_names)
    df['species'] = iris.target_names[iris.target]
    
    pca = sklearn.decomposition.PCA(n_components=4)
    r = pca.fit_transform(df.iloc[:,0:4].to_numpy())
    
    fig = px.scatter_3d(x=r[:,0], y=r[:,1], z=r[:,2], color=df['species'], symbol=df['species'], opacity=0.4, 
                     labels={'x': '1', 'y': '2', 'z': '3', 'color': 'species', 'symbol': 'species'})
    fig.show()
    

    [image]

    出力層 (output layer)

    ニューラルネットワークの最終の層のこと.

    正規化

    正規化は, 値の範囲を,標準的な値の範囲に変換すること. 次のような意味がある.

    1. 複数のデータがあるとき,分布を保ちながら「データの範囲を0から1の間に収める」ようなデータ変換操作.

      Python のプログラムは次の通り.

      import numpy as np
      from sklearn.preprocessing import scale, minmax_scale
      scale(np.array([1, 3, 4, 5, 2]))
      
    2. 複数のデータがあるとき,分布を保ちながら「平均 0,標準偏差1になる」ようなデータ変換操作.

      Python のプログラムは次の通り.

      import numpy as np
      from sklearn.preprocessing import scale, minmax_scale
      minmax_scale(np.array([1, 3, 4, 5, 2]))
      
    3. 数値ベクトルがあるとき,そのベクトルの向きを保ちながら,長さを1にするようなデータ変換操作

      Python のプログラムは次の通り.

      import numpy as np
      from sklearn.preprocessing import normalize
      a = np.array([[1, 2, 0], [11, 12, 0]])
      a.shape
      normalize(a, axis=0)
      normalize(a, axis=1)
      

      [image]

    推論 (inference)

    ニューラルネットワークを教師あり学習で使用する場合での推論は,学習済みのモデルに対して,入力を与え,出力を得ること. このとき,ニューラルネットワークの重みは変化しない

    ニューラルネットワークの重みが変化可能に設定したままの状態で推論を行うと,精度よく推論が出来ないなどの問題がある.PyTorch では,eval メソッドの実行により, ニューラルネットワークの重みが変化しないように設定した上で推論を行う.

    出力は分類結果であったり,分類結果の確率分布であったり,さまざまありえる.

    生成モデル (generative model)

    生成モデルは,データ X とクラス C の結合確率をモデル化し, そのモデルのパラメータと,データ X の同時確率を最大化したもの.

    あるいは生成モデルのことを,データ X を生成するための確率モデルという意味でいうこともある.

    正則化 (regularization)

    正則化は,モデルの複雑さに対するペナルティととらえることができる. 正則化過学習の防止,緩和に役立つとされる. 正則化には次のような種類がある.

    参考文献: http://research.microsoft.com/en-us/um/people/jingdw/pubs/cvpr16-disturblabel.pdf

    生成的 AI (generatve AI)

    生成的 AI (generatve AI) は,大量のデータによる学習により,要求に応じた文章や画像や音声などを生成する能力に上達する能力を持った人工知能である.

    関連項目リカレントニューラルネットワーク

    正則化率 (regularization rate)

    重みと比べたときの,正則化関数の相対的な重要性を指定する数値である. 正則化率を上げると,過学習が減少するが,モデルの精度が低下する可能性がある. 正則化率を「lambda」と書くことが多い.  

    全結合 (Dense)

    全結合は,多層パーセプトロン (MLP)で,である層のニューロンすべてと,隣の層のニューロンすべてを結合すること.

    全結合層

    ニューラルネットワーク層(レイヤ)のうち, 後続の層(レイヤ)全結合されている層(レイヤ)のことを 全結合層という.

    「Fully-connected Layer」と言ったり,「Dense Layer」と言ったり,「Affine レイヤ」と言ったりもする.

    層(レイヤ)

    ニューラルネットワークは, 層(レイヤ)の積み重ねで構成されると考えることができる.

    ニューラルネットワークの1つの層(レイヤ)は, コンピュータの中に作るとき,全結合層 (fully-connected layer), 活性化関数層 (activation layer) いう複数の層(レイヤ)に分かれることが普通である. さらに Dropout のような,新しい層(レイヤ)が加わることもある.

    Keras のプログラム】

    入力の次元数が 784,ニューロン数 100, 100, 100の3層,クラス数 10,ドロップアウト 0.05 であるような分類モデル">のプログラムは次のようになる.

     

    層構造のニューラルネットワーク

    この資料で, 「層構造のニューラルネットワーク」というときは, ニューラルネットワークが層構造をなしていて,さらに,ある層(レイヤ)ニューロンは, 次の層(レイヤ)のみにつながる(つながりでは,飛び越しや後戻りがない)という場合のことをいう. Keras では,「Sequential」という.

    例えば,次のような 10層からなる層構造のニューラルネットワークを考えることができる.

    Keras のプログラム】

    m.add(Dense(units=100, input_dim=len(768[0])))
    m.add(Activation('relu'))
    m.add(Dropout('0.05'))
    m.add(Dense(units=100))
    m.add(Activation('relu'))
    m.add(Dropout('0.05'))
    m.add(Dense(units=100))
    m.add(Activation('relu'))
    m.add(Dropout('0.05'))
    m.add(Dense(units=クラス数))
    m.add(Activation('softmax'))
    

    相互情報量 (mutual information)

    相互情報量を求める R のプログラム.

    library(entropy)
    X <- c(1,2,1,2,3,2,1)
    Y <- c(4,5,5,4,6,5,4)
    a <-discretize2d(X, Y, 3, 3)
    mi.plugin(a)
    chi2indep.plugin(a)
    

    [image]

    参考資料: https://cran.r-project.org/web/packages/entropy/entropy.pdf

     

    相対度数分布 (relative frequency histgram)

    度数分布のうち,データの個数を数え上げる普通の度数分布の他に, 比率(全体を 1 をする)を数え上げる相対度数分布(relative frequency histgram), 累積値を数え上げる累積度数分布(cumulative frequency histogram)がある.

    相対度数分布を数える Python プログラム.numbins で帯数を指定.

    scipy.stats.relfreq([0, 1, 1, 0, 0, 0, 1, 0, 0], numbins = 2)
    

    参考ページ: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.relfreq.html

    相対度数分布を数える R のプログラム.numBins で帯数を指定.

    library(entropy)
    a = c(0, 1, 1, 0, 0, 0, 1, 0, 0)
    discretize(a, numBins=2)/length(a)
    

    [image]

    参考資料: https://cran.r-project.org/web/packages/entropy/entropy.pdf

    損失 loss)

    ニューラルネットワークの出力と正解との差. つまり,損失は,モデルにより予測された値が,正解とどれだけ離れているかを示す. 損失の値を算出するために,損失関数が必要である.

    損失関数

    損失を算出するための関数のこと. 平均二乗誤差 (MSE, Mean Squared Error), カルバック-ライブラー情報量などがある. 「誤差関数」ともいうこともある.

    ニューラルネットワークの学習においては,損失関数の値が最小になるように探索が行われる.

    Keras損失関数のページ: https://keras.io/api/losses/index.html

     

    大規模言語モデル (large language model)

    大規模言語モデル は,自然言語処理を機械学習で行うためのモデルの一種であり,その中でも数億〜数十億以上のパラメーターを持ち,膨大な量の自然言語データによる訓練を受けたものを指す. 大規模言語モデルは,文章の生成,要約,翻訳,対話システムなどの自然言語処理において有用性が示されつつあります. 代表的な大規模言語モデルには,OpenAI の GPT,Google の BERT,Meta の LLaMA,Stanford Alpaca などがある.

    関連項目FlexGenLLaMA (Large Language Model Meta AI)LoRAOPTStanford AlpacaWhisper

    多クラス

    「多クラス」は,クラス数が3以上であること.クラス数が2の場合には「2クラス」という.  

    多クラスの分類 (multi-class classification)

    2つ以上のクラス分類すること. 2クラスに分類するときは binary classication という.

    畳み込みニューラルネットワーク (CNN, Convolutional Neural Network)

    畳み込みニューラルネットワーク (Convolutional Neural Network) は,畳み込み層 (convolutional layer) を含むような ニューラルネットワークである.

    畳み込みニューラルネットワーク (Convolutional Neural Network) は, 次の 3種類の層を含むように構成するのが普通である.

    関連項目Applications of Deep Neural Networks, Keras, ディープラーニング

    畳み込みニューラルネットワーク (Convolutional Neural Network) を作成する Python プログラム(Keras を使用)

    例えば,次のような 5層からなる層構造のニューラルネットワークの作成を行う.

    1. 2次元の畳み込み層 (convolutional layer)
    2. 2次元の畳み込み層 (convolutional layer)
    3. プーリング層 (pooling layer)
    4. 全結合層 (fully-connected layer).ニューロン数は 128.
    5. 全結合層 (fully-connected layer).ニューロン数は 10

    その Python プログラムは次のようになる.

    from __future__ import absolute_import, division, print_function, unicode_literals
    import tensorflow as tf
    from tensorflow.keras import layers 
    from tensorflow.keras import backend as K
    
    gpu = tf.config.list_physical_devices(device_type = 'GPU')
    if len(gpu) > 0:
        print("GPU:", gpus[0].name)
        tf.config.experimental.set_memory_growth(gpu[0], True)
    
    # 畳み込みニューラルネットワークの作成
    num_classes = 10
    img_rows, img_cols = 28, 28
    if K.image_data_format() == 'channels_first':
        input_shape = (1, img_rows, img_cols)
    else:
        input_shape = (img_rows, img_cols, 1)
    
    m = tf.keras.Sequential(
        [
            tf.keras.Input(shape=input_shape),
            layers.Conv2D(32, kernel_size=(3, 3), activation="relu"),
            layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
            layers.MaxPooling2D(pool_size=(2, 2)),
            layers.Dropout(0.25),
            layers.Flatten(),
            layers.Dense(128, activation='relu'),
            layers.Dropout(0.5),
            layers.Dense(num_classes, activation="softmax"),
        ]
    )
    
    m.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    print(m.summary())
    

    補足説明は次の通りである.

    多層パーセプトロン (MLP)

    超解像 (super resolution)

    超解像 (super resolution) は,低解像度のものを入力として受け取り, 高解像度のものを出力する. その結果,解像度が高まる.

    下図の左は ESRGAN (RRDN GANS) 法の結果, 下図の右は bicubic 法の結果.

    関連項目Real-ESRGAN, ESRGAN

    転移学習 (transfer learning)

    ある機械学習のタスクから別のタスクに情報を転移すること.

    ニューラルネットワークの転移学習では,学習済みモデル を使い,新しい分類を行う.新しい分類のための教師データを十分に準備できないときに効果を期待できる. 転移学習では, 学習済みモデルについて,重みを凍結(フリーズ)する. 学習済みモデルに新しい層(レイヤ)を追加して, 新しい分類を行えるようにする. 学習済みモデルは,新しい分類のための特徴抽出のために使うと考えることができる

    動画 (video)

    動画の情報確認

    動画のサイズ,縦横比,コーデックなどの確認は,mediainfo コマンドで行うことができる.

    avi ファイルでの実行結果例

    [image]

    mp4 ファイルでの実行結果例

    [image]
    動画の形式変換

    動画の形式変換は,ffmpeg を用いて行うことができる.

    動画から連番画像の作成
    ffmpeg -i kaneko_sample_video.mp4 -r 4 -f image2 img%06d.png
    
    動画の編集

    動画の形式変換は,OpenShot などを用いて行うことができる.

    動画のストリーミング配信,録画,リアルタイム合成

    OBS (Open Broadcaster Software) は, 動画のストリーミング配信,録画,リアルタイム合成の機能を持つ. 例えば,FaceRig の動画と,パソコンの画面との合成も簡単にできる.

    OBS の公式ページ(日本語版): https://obsproject.com/ja/

    統計的機械学習 (Statistical Machine Learning)

    統計的機械学習には,次のようなものがある.

    特徴ベクトル (feature vector)

    特徴値 (feature value) のベクトル.

    度数分布(ヒストグラム)

    度数分布のうち,データの個数を数え上げる普通の度数分布の他に, 比率(全体を 1 をする)を数え上げる相対度数分布(relative frequency histgram), 累積値を数え上げる累積度数分布(cumulative frequency histogram)がある.

    度数分布を数える R のプログラム.numBins で帯数を指定.

    library(entropy)
    a = c(0, 1, 1, 0, 0, 0, 1, 0, 0)
    discretize(a, numBins=2)
    

    参考資料: https://cran.r-project.org/web/packages/entropy/entropy.pdf

    Iris データセットの度数分布(ヒストグラム)をプロットする R のプログラム.

    library(ggplot2)
    p <- ggplot( iris[iris$Species=='setosa',]$Sepal.Length )
    p + stat_bin(aes(hoge, ..count..))
    

    凸最適化 (convex optimization)

    凸最適化 (convex optimization) には, 凸関数 (convex function) での最小を発見する勾配降下法 (gradient descent) などがある.

    入力層 (input layer)

    ニューラルネットワークの最初の  

    入力の次元数

    ニューロンの入力が数のベクトルであるとき,そのベクトルの次元数を「入力の次元数」という.

    非公式ビルド

    オープンソースのソフトウェアを,非公式にビルドしたもの.

    白色化

    白色化 (whitening) とは,ニューラルネットワークの入力である数値ベクトルについて, 次のことを行う処理のこと.

    微調整 (fine tuning)

    2度めの最適化を実施することで, すでに学習済みモデルのパラメーターを, 新しい問題に適合するように調整すること.

    「教師なしのニューラルネットワークで学習済みのものについて, 重みを調整することで,教師ありのニューラルネットワークとして使えるようにする」という意味もある.

    転移学習では,モデル全体もしくはモデルの一部の凍結(フリーズ)を解除し,新しいデータで学習を行う.このとき,十分な量のデータを準備すること,そして,学習率を低く設定するなので,モデルの改善を行う.

    半教師あり学習 (semi-supervised learning)

    教師データとして,正解の付いているデータと,正解の付いていないデータを使う. 正解の付いているデータを使い,ニューラルネットワーク学習を使い. そして,このニューラルネットワークに,正解の付いていないデータを与え,出力を得る. この出力を正解とみなして,正解の付いていないデータと合わせて,教師データとして使う.

    深さ (depth)

    深さ (depth) は,ニューラルネットワーク層(レイヤ) のうち, 重み (weight) についての学習を行う層(レイヤ)の数のこと.

    物体検出

    物体検出は,写真やビデオの中から,ある特定の種類の物体を検出すること.種類は複数ありえ,その場合には,物体検出 が行われるともに,その種類が判別される.

    物体検出の結果は, バウンディングボックスで得られるのが普通である.

    関連項目ADE20K データセット Box Annotation, COCO (Common Object in Context) データセット, DETR, Deformable DETR, EfficientDet, ImageNet データセット, Mask R-CNN, Max-Margin 物体検出 (Max-Margin Object Detection), MMDetection, MMPose, MMSegmentation3D, MMSelfSup, MMTracking, PANet (Path Aggregation Network), Pascal VOC (Pascal Visual Object Classes Challenge) データセット, RetinaNet, Seesaw Loss, SSD, YOLOv3, YOLOX, 顔検出 (face detection) セマンティック・セグメンテーション (semantic segmentation), インスタンス・セグメンテーション (instance segmentation)

    分類 (classification)

    分類は, データから,そのクラス名,もしくは,クラスについての確率分布を求めること. 「クラス分類」ともいう.

    多くの場合には,ベクトルデータの集合を, オブジェクトをクラス(カテゴリ)に分けたり, クラスに属する確率を求める.

    ディープラーニングによる分類は,事前に,教師データを用いて訓練(学習)を行う.

    分類モデル (classification model)

    機械学習のモデルで,クラスの判別に使うもの.

    Iris データセット を,3種類に分類する Keras プログラムの例は次の通り.

    from __future__ import absolute_import, division, print_function, unicode_literals
    import tensorflow as tf
    import numpy as np
    from sklearn.datasets import load_iris
    import sklearn.model_selection
    from sklearn.preprocessing import normalize
    from IPython.display import display
    
    iris = load_iris()
    x = iris.data
    y = iris.target
    
    x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(x.reshape(x.shape[0], -1), y, train_size=0.5) 
    
    NUM_CLASSES = 3
    
    m = tf.keras.Sequential()
    m.add(tf.keras.layers.Dense(units=64, input_dim=len(x_train[0]), activation='relu'))
    m.add(tf.keras.layers.Dropout(0.5))
    m.add(tf.keras.layers.Dense(units=NUM_CLASSES, activation='softmax'))
    
    print(m.summary())
    
    m.compile(
        optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
        loss='sparse_categorical_crossentropy',
        metrics=['sparse_categorical_crossentropy', 'accuracy']
    )
    
    EPOCHS = 300
    history = m.fit(x_train, y_train, batch_size=32, epochs=EPOCHS, validation_data=(x_test, y_test))
    
    # 分類
    predictions = m.predict(x_test)
    print(predictions.argmax(axis=1))
    # 正解の表示
    print(y_test)
    
    import pandas as pd
    h = pd.DataFrame(history.history)
    h['epoch'] = history.epoch
    print(h)
    
    # 学習曲線
    # https://www.tensorflow.org/tutorials/keras/overfit_and_underfit?hl=ja で公開されているプログラムを使用
    %matplotlib inline
    import matplotlib.pyplot as plt
    import warnings
    warnings.filterwarnings('ignore')   # Suppress Matplotlib warnings
    
    def plot_history(histories, key='binary_crossentropy'):
      plt.figure(figsize=(16,10))
    
      for name, history in histories:
        val = plt.plot(history.epoch, history.history['val_'+key],
                       '--', label=name.title()+' Val')
        plt.plot(history.epoch, history.history[key], color=val[0].get_color(),
                 label=name.title()+' Train')
    
      plt.xlabel('Epochs')
      plt.ylabel(key.replace('_',' ').title())
      plt.legend()
    
      plt.xlim([0,max(history.epoch)])
    
    
    plot_history([('history', history)], key='sparse_categorical_crossentropy')
    

    上のプログラムの実行結果は下の図の通り.

    [image]

    上のプログラムで作成される分類モデルは,次の通り.

    [image]

    学習に追加に使うデータ: x_testy_test のペア

    print(x_train)
    print(y_train) 
    

    [image]

    [image]

    学習のあと,別のデータを使って分類してみる

    まず分類したいデータの確認

    print(x_test)
    

    [image]

    分類結果の確認

    m.predict(x_test)
    

    [image]

    偏微分 (partial derivative)

    変数が複数あるとき,ある特定の1変数を除くすべての変数を定数とみなした導関数のこと. 例えば,x に関する f(x, y) の偏微分では,y を定数に保ちながら微分を行う. x に対する f の偏導関数は,x がどのように変化するかのみに注目するもので,方程式内の x 以外のすべての変数を無視する.

    変分オートエンコーダ(Variational Auto Encoder; VAE)

    変分オートエンコーダ(Variational Auto Encoder; VAE) は,エンコーダとデコーダから構成される. 学習によって,エンコーダとデコーダのパラメータが決定されるもので,デコーダは,生成モデルになっている.

    変分オートエンコーダ(Variational Auto Encoder; VAE) は,オートエンコーディング変分ベイズアルゴリズム(Auto-Encoding VB algorithm; AEVB algorithm)を用いた学習を行う. オートエンコーディング変分ベイズアルゴリズムは, 確率的勾配降下法を用いて,確率的勾配変分ベイズ推定量 (Stochastic Gradient Variational Bayes estimator) を極大化するような,エンコーダとデコーダのパラメータを求める.

    その構造は,オートエンコーダに類似するが, 次の違いがある.

    変分オートエンコーダ(Variational Auto Encoder; VAE) は,CVAE と関連する.

    連番画像

    次のコマンドは,動画ファイルから連判画像を生成する.

    rm *.png
    ffmpeg -i IMG_0581.MOV -vcodec png 0581_%06d.png
    ffmpeg -i IMG_0596_Trim.mp4 -vcodec png 0596_%06d.png