2022年2月10日木曜日

学習データの変換方法。

作業で再現するのも大変ですが、これを一から作るのはもっと大変です。

 もちろんすんなりいきません。

作ったときと今とではバージョンが違うのでそれだけでも一苦労です。

ここまで来るのも一苦労、これからまだ作業と検証が必要。


2回目以降の手順シェルスクリプトで

source activate yad2k

keras-yolo3-masterフォルダに入ってから

python convert.py wiwao_train.cfg wiwao_train_6000.weights model_data/murou.h5

2回目はconda activate downgradeしてから

cd yolo_coreml

coreml_model = coremltools.converters.keras.convert('/Users/wiwao/Documents/keras-yolo3-master/model_data/murou.h5', input_names='input1', image_input_names='input1',  image_scale=1/255.)

一旦今のファイルを消す

(base) wiwaoMacBookPro:bin wiwao$ sudo rm -i w_t.mlmodel

それから新規ファイルをコピーする。

sudo cp w_t.mlmodel /Applications/Xcode.app/Contents/Developer/usr/bin

python coreml.py


pip でインストールすると仮想環境では使えない。yolov3はpython3.7でtensorflow==1.14でないと使えない。


git clone https://github.com/allanzelener/yad2k.git

cd yad2k

To replicate the conda environment:

conda env create -f environment.yml

で重なっているファイルは全て消す

ResolvePackageNotFound: 

 

結局下記でインストール出来た。

name: yad2k

channels:

- defaults

dependencies:

- pip:

  - keras==2.0.3

  - protobuf==3.2.0

  - pydot-ng==1.0.0


  - theano==0.9.0

prefix: /home/wiwao/anaconda3/envs/yad2k

prefixは上記の様に自分の環境に合わせる。


source activate yad2k

YAD2Kも下記の様にバージョン指定して必要なものは合わせてインストール

conda install keras==2.2.4

conda install -c anaconda tensorflow==1.14


keras-yolo3-masterフォルダに入ってから、以降もanaconda環境のYAD2K中で作業を行います。


まずconvert.py を実行しますが、このままではエラーが出てしまうので、convert.pyの88行目をinput_layer = Input(shape=(416, 416, 3))に変更します。


ウェイトをダンロードしてから下記を必要に応じて変更

python convert.py yolov3.cfg yolov3.weights model_data/yolo.h5

次に、同じディレクトリへ該当するweightsファイル、そして学習で使ったcfgファイルを入れておきます。

cfgファイルのはじめに設定しているパラメーターを bach=1 subdivisions=1に変更しておき、以下のコマンドで 新たにh5ファイルを作成します。cfg、weightファイル名はコピーしたそれぞれのファイル名に変更し、.h5ファイルは好きな名称を付けます。

この例ではdataフォルダにh5ファイルができます。


conda の(downgrade) でpythonのバージョンを3.7.11に落として

Apple 提供のcoremltoolsをインストールします

anaconda install coremltools

新たにフォルダを作成し(yolo_coremlと仮定)

mkdir yolo_coreml

cd yolo_coreml


wiwaoMacBookPro:yolo_coreml wiwao$ conda install coremltools

conda install keras==2.2.4

conda install -c anaconda tensorflow==1.14


仮想環境を行き来するせいか絶対パスに書き換える


import coremltools

 

coreml_model = coremltools.converters.keras.convert('/Users/wiwao/Documents/keras-yolo3-master/model_data/yolo.h5', input_names='input1', image_input_names='input1',  image_scale=1/255.)

coreml_model.input_description['input1'] = 'Input image'

 

coreml_model.author = 'Original paper: Joseph Redmon, Ali Farhadi'

coreml_model.license = 'Public Domain'

coreml_model.short_description = "The YOLOv3 network from the paper 'YOLOv3: An Incremental Improvement'"

 

coreml_model.save('w_t.mlmodel')


python coreml.py

の実行で、フォルダ内にw_t.mlmodelファイルが作成されます。多少時間がかかります。

## Package Plan ##


  environment location: /Users/wiwao/opt/anaconda3/envs/downgrade


  added / updated specs:

    - coremltools



The following packages will be downloaded:


    package                    |            build

    ---------------------------|-----------------

    coremltools-4.1            |   py37hf099865_1         2.9 MB

    ------------------------------------------------------------

                                           Total:         2.9 MB


The following NEW packages will be INSTALLED:


  coremltools        pkgs/main/osx-64::coremltools-4.1-py37hf099865_1


The following packages will be UPDATED:


  ca-certificates    anaconda::ca-certificates-2020.10.14-0 --> pkgs/main::ca-certificates-2021.10.26-hecd8cb5_2

  certifi                anaconda::certifi-2020.6.20-py37_0 --> pkgs/main::certifi-2021.10.8-py37hecd8cb5_2



Proceed ([y]/n)? y


cp w_t.mlmodel /Applications/Xcode.app/Contents/Developer/usr/bin

/Applications/Xcode.app/Contents/Developer/usr/bin/coremlc compile w_t.mlmodel /Users/wiwao/yolo_coreml


(base) wiwaoMacBookPro:bin wiwao$ /Applications/Xcode.app/Contents/Developer/usr/bin/coremlc compile w_t.mlmodel /Users/wiwao/yolo_coreml

/Users/wiwao/yolo_coreml/w_t.mlmodelc/coremldata.bin

/Users/wiwao/yolo_coreml/w_t.mlmodelc/model.espresso.weights

/Users/wiwao/yolo_coreml/w_t.mlmodelc/model.espresso.shape

/Users/wiwao/yolo_coreml/w_t.mlmodelc/model.espresso.net

/Users/wiwao/yolo_coreml/w_t.mlmodelc/model/coremldata.bin

/Users/wiwao/yolo_coreml/w_t.mlmodelc/neural_network_optionals/coremldata.bin

(base) wiwaoMacBookPro:bin wiwao$ 

How to make YOLOv3 Pre-learned files.

ここからは十分に経験と知識のある方、NVIDIAのGPUを積んだLinuxマシンが動く環境が使える方が対象です。最初は非常に複雑なインストール作業を伴いますが、2回目以降はさほどでもありません。概要は以下の通りです。内容を理解した段階でMac側の一連の作業をPython等にまとめると効率が上がります。

linuxマシンで学習->学習済みweightsファイルをmacにコピー->h5ファイルに変換->coremlファイルに変換->coremlcファイルに変換->txtファイルを3つ作成-->zipに圧縮 

From here, it is for those who have sufficient Deep learning experience and knowledge, and who can use an environment where Linux machines with NVIDIA GPUs can run. The first involves a very complex installation(according to https://github.com/AlexeyAB/darknet), but not much after the second time. The outline is as follows. When you understand the contents, you can improve the efficiency by grouping a series of tasks on the Mac side into Python.

Learning on linux machine-> Copy learned weights file to mac-> Convert to h5 file-> Convert to coreml file-> Convert to coremlc file-> Create three txt files-> Compress to zip

4.1 録画した赤外線画像データをアノテーションする。Annotating LEPTON images and learning

学習データ画像はThermal Cam3xで録画したファイルを使います。アノテーション及び学習方法はこのページを参照して下さい。

YOLOオリジナルデータの学習 - Take’s diary

YOLOオリジナルデータの学習その2(追加学習) - Take’s diary

さらに詳しい内容は以下URLを参考にして下さい。

darknet/cfg at master · AlexeyAB/darknet · GitHub

 

iOSで実行するためには特に以下の設定が必要です。

  • 設定ファイル(CFGファイル)は yolov3-voc.cfg又はyolov3.cfgを使用します。
  • 入力画像の大きさは with=416 heights=416 限定です。
  • YOLOv3.cfgの設定ファイルは参考ページにも説明していますが、classがらみで合計10カ所以上の変更が必要です
  • 学習の収束を早めるための初期weightsファイルは、darknet53.cov.74をダウンロードして使用します。

The learning data image uses a file recorded with Thermal Cam3x. Please refer to this page for annotation and learning methods.

YOLOオリジナルデータの学習 – Take’s diary

YOLOオリジナルデータの学習その2(追加学習) – Take’s diary

Please refer to the following URL for further details.

darknet/cfg at master · AlexeyAB/darknet · GitHub

In order to run on iOS, the following settings are required.

Use yolov3-voc.cfg or yolov3.cfg as the configuration file (CFG file).

The size of the input image is limited to with = 416 heights = 416.

The configuration file of YOLOv3.cfg is also explained on the reference page, but it is necessary to change a total of 10 or more locations in relation to the class

Download and use darknet53.cov.74 as the initial weights file to speed up learning convergence.

4.2 MacにYAD2Kをインストールする。Install YAD2K on your Mac.

以下python3.7用のanaconda環境を作り、YAD2K及びkerasをインストールします。インストール方法は各々冒頭に記述されています。ただし最初のKerasインストール時はTensorflowインストールコマンドのみ conda install -c anaconda tensorflow==1.14 つまりtensorflowのバージョンは1.14にして下さい。

Create Anaconda environment for python3.7 below and install YAD2K and keras. Each installation method is described at the beginning. However, when installing Keras for the first time, only the Tensorflow installation command is used. Conda install -canaconda tensorflow == 1.14 That is, tensorflow version should be 1.14.

GitHub - allanzelener/YAD2K: YAD2K: Yet Another Darknet 2 Keras

GitHub - qqwweee/keras-yolo3: A Keras implementation of YOLOv3 (Tensorflow backend)

4.3 Kares を使ってYOLO学習済みファイルをコンバートする Convert files created in 4.3 to mlmodel

keras-yolo3-masterフォルダに入ってから、以降もanaconda環境の中で作業を行います。

まずconvert.py を実行しますが、このままではエラーが出てしまうので、convert.pyの88行目をinput_layer = Input(shape=(416, 416, 3))に変更します。

次に、同じディレクトリへ該当するweightsファイル、そして学習で使ったcfgファイルを入れておきます。

cfgファイルのはじめに設定しているパラメーターを bach=1 subdivisions=1に変更しておき、以下のコマンドで 新たにh5ファイルを作成します。cfg、weightファイル名はコピーしたそれぞれのファイル名に変更し、.h5ファイルは好きな名称を付けます。

この例ではdataフォルダにh5ファイルができます。

After entering the keras-yolo3-master folder, the following work is also performed in the anaconda environment.

First of all, convert.py is executed, but an error will occur if this is done, so change the 88th line of convert.py to input_layer = Input (shape = (416, 416, 3)).

Next, put the corresponding weights file in the same directory and the cfg file used for learning.

Change the parameter set at the beginning of the cfg file to bach = 1 subdivisions = 1, and create a new h5 file with the following command. Change the cfg and weight file names to the copied file names, and give the .h5 file a name of your choice.

In this example, an h5 file is created in the data folder.

./convert.py yolov3.cfg yolov3.weights model_data/yolo.h5

4.4 4.3でできたファイルをmlmodelに変換する

Apple 提供のcoremltoolsをインストールします

pip install coremltools

新たにフォルダを作成し(yolo_coremlと仮定)

mkdir yolo_coreml

cd yolo_coreml

以下のpythonプログラムを作成します

この中で3行目の ../../keras-yolo3-master/model_data/yolo.h5 は先ほど作成したh5ファイルを指定して下さい。

Install coremltools provided by Apple

pip install coremltools

Create a new folder (assuming yolo_coreml)

mkdir yolo_coreml

cd yolo_coreml

Create the following python program

In this, please specify the h5 file created earlier for ../../keras-yolo3-master/model_data/FLIR_J.h5 on the third line.

coreml.py

--------------------------------------------------------------------------------------------------

import coremltools

 

coreml_model = coremltools.converters.keras.convert('../../keras-yolo3-master/model_data/yolo.h5', input_names='input1', image_input_names='input1',  image_scale=1/255.)

coreml_model.input_description['input1'] = 'Input image'

 

coreml_model.author = 'Original paper: Joseph Redmon, Ali Farhadi'

coreml_model.license = 'Public Domain'

coreml_model.short_description = "The YOLOv3 network from the paper 'YOLOv3: An Incremental Improvement'"

 

coreml_model.save('w_t.mlmodel')

 --------------------------------------------------------------------------------------------------

python coreml.py

の実行で、フォルダ内にw_t.mlmodelファイルが作成されます。多少時間がかかります。

python coreml.py

Execution will create a w_t.mlmodel file in the folder.

4.5 標準では32ビットデータなのでデータ容量を減らしたい場合は16bitに変換する Standard is 32-bit data, so if you want to reduce the data capacity, convert it to 16-bit

16bitモデルは認識率が多少落ちるので、用途に応じて対応して下さい。16bitモデルに変更する場合は以下のpythonプログラムを作成して実行します。

The 16bit model has a slightly lower recognition rate. To change to the 16bit model, create and execute the following python program.

convert16.py

--------------------------------------------------------------------------------------------------

import coremltools

model_spec = coremltools.utils.load_spec('./w_t.mlmodel')

model_fp16_spec = coremltools.utils.convert_neural_network_spec_weights_to_fp16(model_spec)

coremltools.utils.save_spec(model_fp16_spec, 'w_t.mlmodel')

--------------------------------------------------------------------------------------------------

4.6 mlmodelをmlmodelcに変換する Convert mlmodel to mlmodelc

mlmodelをコンパイルしてmlmodelcファイル(実はフォルダ)を作成します。必ず最終ファイル名はw_t.mlmodelcであることを確認して下さい。

Compile mlmodel and create mlmodelc file (actually folder). Make sure that the final file name is w_t.mlmodelc.

/Applications/Xcode.app/Contents/Developer/usr/bin/coremlc compile w_t.mlmodel ./

4.7 さらに3つのファイルを用意する Prepare 3 more files

w_t.names   : 学習に使ったクラス名称ファイルで、ファイル名称を変更して使用します。

w_t.txt   :「3.認識結果アラートの設定方法」を参考にして下さい・

REDME.txt :名称、内容とも任意で、実際には使用しません。今回の作業ファイルはすべて同じ名称にしなければないので、後から確認できるようにデータ内容の説明を記入して下さい。

w_t.names : The class name file used for learning is used by changing the file name.

w_t.txt        : Refer to “3. Setting method of recognition result alert”.

REDME.txt : Name and content are optional and are not actually used. All work files must have the same name, so please enter a description of the data so that you can check it later.

4.8 合計4つのファイルを新たに作成したw_tフォルダに移動する Move a total of 4 files to the newly created w_t folder

w_tフォルダを作成して、中にw_t.mlmodelcフォルダ、w_t.names、w_t.txt.、README.txtをコピーします。

Create a w_t folder and copy the w_t.mlmodelc folder, w_t.names, w_t.txt., and README.txt into it.

4.9 フォルダをzipに変換して自分のアカウントを持つicloudへuplodeする Convert folder to zip and uplode to icloudwith your account

w_tフォルダをzipに圧縮します。iPhoneから一番使いやすいダウンロード先はiCloudです。今回のThermal Cam3xはフォルダ名がw_t限定なので、モデル毎にフォルダ管理して下さい。

Compress the w_t folder to zip. The easiest download location for iPhone is iCloud. Since this Thermal Cam3x folder name is limited to w_t, please manage folders for each model.

 


2022年2月3日木曜日

食品の冷凍冷蔵の電気代

高校生とのプロジェクトは無くなりました。
高校生には非常に失礼な事をしてしまいました。
POSデータは10年分の月毎のデータだったのですが、POSデータに参加したり脱退したりすると数量は大きく変わる上に季節毎の推移も分からないデータなのでこれを元に予測は不可能です。
送付する前に確認するべきでした。またある程度予測可能かを精査してからでないと、今後も協力して頂ける会社は無くなってしまいます。当然ですが、ある程度データ分析を実践することを痛感しました。
仮定ですが、牛乳の販売数量の予測ができれば単位当たりの冷蔵エネルギーは算出できるのでそれで電力の予測も出来るとしていました。
他力本願で都合良く話を展開していたのも問題で自分ができないことを人にさせること自体が間違えでした。







 


2022年1月28日金曜日

社内のデータの分析

社内のデータは集計して欠損値の補完や整理は初めてです。

金額の合計は特に問題ないですが、客先や担当者名で躓いてしまいました。

まずpythonのpandasでdf2 = df.replace({'A課長': 'A','B次長': 'B','K所長': 'K','M部長': 'M'})で名前で集計出来る様にして、会社名が半角と全角がバラバラなのでhttps://forest.watch.impress.co.jp/docs/serial/exceltips/1296013.html

でエクセルでASCで統一してからエクセルをパイソンで集計 

客先別で同じ様な問題があるかもしれませんが…



2022年1月21日金曜日

VRの続き(キューピクル)

 こんなデータを提供する会社ありそうでない。

iPhoneで3Dデータを取得して現場改造のデータを収集したら当然その後の改造や追加する機器をそこに配置する事になるのでとりあえず200k、300k、500kのキュービクルの3Dデータを作りました。


あくまで参考様で製造用のデータではありません。

内部にトランス、LBSやブレーカーを配置してドアは稼働する様に設計しました。


目の都合で少しずつの作業で細かなことはできません。
結局はPC作業もかなりの制限で操作マニュアル調べるのにままならない状況です。
一応autodeskビューアーにアップしています。
https://autode.sk/3F50EEZ



2022年1月7日金曜日

AIの中長期的なプラン

視力の問題でできる事に限りがあるなかで生きていく方法を模索しています。

AIデータサイエンスといった事を始めた矢先で混乱していますが、先ずはデータです。

手元にあるデータ若しくは今後必要に応じて取得するデータがあります。

それらを活用するにはデータを前処理(異常値や欠損データを補完する)事が必要になります。それらを自動で補完する事が必要になります。

Python等のプログラムもありますが、そこまで自分でするのは現状では無理です。

pycaretというものがありました。下手な素人よりは賢いですが、ハイパーパラメータの調整で多少は変わるようです。

Matlabにその様な機能がありまた各産業の実際のデータを使った事例もあるのでそれらも自社に近いデータを見つける事が出来れば効率的になります。

問題はソフトが複雑で数学や物理法則を理解しないと扱えないので習得に時間が掛かる。1日の時間もある程度制限しないといけません。

今後のこともあるので手順や失敗を記述しながら進めて行く事が必要です。

先ずは適当なサンプルを見つける、実践する(出来なければ途中経過を記述する)。

それらを積み重ねて行く事を始めてみようと思います。


 先ずはデータの前処理を勉強中です。社内のデータが欠損やカテゴリーデータの内容を正規化しないと使えないので調整しています。

少しはコードを工夫しないといけないのですが、ネットに色々と調べながら進めています。
YouTubeにも色々と勉強になる動画があるのでノートに書きながら目に負担にならない用に工夫しています。:;、()[]等が判別出来ないので疲れます。

2022年1月4日火曜日

AIを使った何か?例えば主成分分析

 機械学習は魔法ではなくデータを分類する手法です。

例えば身長が高ければ体重は重くなります。ある程度の人数のデータを機械学習して身長175cmの体重を予測する事は出来ます。精度を上げる為に性別や骨格の情報を追加していけばより良い予測ができる事は理解出来ると思います。その計算に右足と左足の長さをデータとして追加しても役に立たない事も理解出来そうです。それでは年齢を追加したらどうでしょう?

結局は追加して予測精度を調べるしかありません。

あるお店の外気温による飲み物の売上の予測はどうでしょうか?

気温が上がれば増えるでしょう。でも気温が30度を超えて40度になっても数量は増えないでしょう。それだけ気温が高いとそもそも外出しないでしょうし。逆に10度になってら減るでしょうか?

マイナス5度になれば売上はマイナスになるでしょうか?

機械学習はコンピューターを使うので計算式を入力する必要があります。

何が言いたいかと言うと社内の業務改善にAIを導入といった考え方ではなく、社内のデータを使って何をする為にどのデータが必要なのかを決めないとどうしようもありません。

最初に手法があると説明しましたが。身長から体重の予測や気温から飲み物の予測は線形回帰やロジスティック回帰、それ以外にも決定木、サポートベクターマシン、XGブースト…

数十種類の手法がありデータや予測したいものによって使い分けます。どれが最適か色々な手法を試す必要があります。

先ほどの左右の足の長さのように不要なデータで機械学習すると当然予測はおかしくなります。

私は知識をしてそれらを知っていますが、プログラムを実装した事はありません。それを始める前に手術してそれらを始める事ができていません。

仮に予測したいことがあれば調べて実装をしようと思いますが、いつまでに出来るかわかりません。

年末年始を利用して少しサンプルの実装していますが、データの前処理も大変です。

今は主成分分析をしています。

体重や身長、足の長さ、気温、性別等のデータの中から予測したい目的にどれほど影響しているかを数学的に分析する機械学習です。

との様に計算するかと言うとそれぞれの数値の平均と取得したデータの差を2乗してそれぞれのデータに相関関係がないかを分散共分散行列を求めて2、3種類までデータを絞る方法です。

それぞれのデータは目的に対して意味あるものであれが多くあれば予測精度が上がりますが研鑽コストも上がってしまします。その項目(説明変数)が使えるか使えないかを数学的に解く手法の一つです。




パイソンのコードです。

import numpy as np

import pandas as pd

import matplotlib.pyplot as plt



# In[2]:



df = pd.read_csv('titanic_train.csv')

df.head()



# In[3]:



df.info()   



# In[4]:



df['Age'] = df['Age'].fillna(df['Age'].mean())

df['Embarked'] = df['Embarked'].fillna(df['Embarked'].mode()[0])


df.info()



# In[5]:



X = df.drop(columns=['PassengerId', 'Survived', 'Name', 'Ticket', 'Cabin'])

y = df['Survived']


X.head()



# In[6]:



from sklearn.preprocessing import LabelEncoder


cat_features = ['Sex', 'Embarked']


for col in cat_features:

    lbl = LabelEncoder()

    X[col] = lbl.fit_transform(list(df[col].values))

    

X.head()



# In[7]:



from sklearn.preprocessing import StandardScaler


num_features = ['Age', 'Fare']


for col in num_features:

    scaler = StandardScaler()

    X[col] = scaler.fit_transform(np.array(df[col].values).reshape(-1, 1))

    

X.head()



# In[8]:



from sklearn.decomposition import PCA


pca = PCA()


X_pca = pca.fit_transform(X)

X_pca



# In[9]:



def plot_2d(X, y):

    plt.plot(X[:, 0][y==0], X[:, 1][y==0], "bo", ms=15)

    plt.plot(X[:, 0][y==1], X[:, 1][y==1], "r^", ms=15) 

    plt.xlabel("First Principal Component")

    plt.ylabel("Second Principal Component")

    plt.legend(['Not Survived', 'Survived'], loc="best")


plt.figure(figsize=(6, 6))

plot_2d(X_pca, y)

plt.show()



# In[10]:



import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D

from matplotlib.widgets import Slider

import numpy as np

get_ipython().run_line_magic('matplotlib', 'widget')

def plot_3d(X, y):

    fig = plt.figure(figsize=(6, 6))

    ax = fig.add_subplot(111, projection='3d')

    

    ax.plot(X[:, 0][y==0], X[:, 1][y==0], X[:, 2][y==0], "bo", ms=15)

    ax.plot(X[:, 0][y==1], X[:, 1][y==1], X[:, 2][y==1], "r^", ms=15)

    

    ax.set_xlabel("First Principal Component", fontsize=15)

    ax.set_ylabel("Second Principal Component", fontsize=15)

    ax.set_zlabel("Third Principal Component", fontsize=15)

    ax.legend(['Not Survived', 'Survived'], loc="best", fontsize=16)

    

plot_3d(X_pca, y)

plt.show()