20200208のTensorFlowに関する記事は4件です。

AI化、5分でチェック・簡単無料POC! 5min POC(Proof Of Concept) on AI!

https://randomwalkjapan.blogspot.com/2020/02/aipoc-5min-poc-proof-of-concept-on-ai.html

自分の仕事がAI化できるか試してみたい人は多いだろう。Many may wish to check if the task working on can be on AI basis.

出来そうな気がするが、人に頼むとお金がかかるし、自分でやるには大変だし。いろんなシステムも宣伝しているが、使い方を覚えるだけで大変だ。決心してやってみて結局だめだったらお金と時間の無駄だし。It looks possible but will cost if ask someone. But looks hassle if do it your own. Google search shows many advertisements on AI systems but looks hard to learn. Also, even if you decided to do it, if it fails eventually, it will be a waste of time and money.

そんな時、無料で、簡単に、可能性をチェックできるのがこのページだ。先に書いた温度管理のプログラムを読み替えただけだ。プログラムはこちら。In such a case, this page provides you, for free and ease, the feasibility check of concept of your idea. This is just another interpretation of previously shown temperature control program I presented. GitHub is here.

https://github.com/tanakayutaka/Tensorflow.js-tools-/blob/master/index%20-%205%20min%20POC%20tool.html

下のアプリの使い方は簡単。ただ、画面に自分の手持ちデータをそのまま入力し、ボタンを押すだけで完了。AIといっても、言語処理、画像、制御などいろいろあるが、ここでは制御が対象。It is very easy to use below application. Simply, just input your data onto the screen, the click button. There are lots of AI out there such as language processing, image processing and control, here we focus on control.

農業、製造、教育など、あらゆる場面でAIは助けになる何でも屋だ。AI is all rounder covering agriculture, manufacturing, education and many other fields.

深く考えずに、まずは身近のデータを入れて実験してみよう! Just jump in before think too much, then input your local data and experiment.

何らかの状態xのもと、何らかの制御zを行うと、結果yが出る。では、ある状態xの場合、ある結果yを実現するには、どんな制御zをおこなえばいいの?という問題に適用できる。Under some circumstance X, by making some control Z, then got result Y. Now to achieve result Y under some circumstance X, how much control Z should be applied? This is the problem we can test here.

使い方は簡単。データ1-9に何らかの観測値(x軸)、制御値(z軸)、そしてその結果生じた値(y軸)を入れ、空色のボタンを押す。計算後、観測値、目標とする結果を実現する制御値(縦軸z)が表示される。グラフが表示されない場合は、グラフのホームアイコンを押す。The usage is easy. Input data set 1-9, i.e., some observation(x-axis), control value(y-axis) and resulting value(y-axis), then push sky blue button. After calculation, control value(vertical z-axis) is shown as surface to achieve target value at observation value. Click Home Icon on the graph if it is not shown.

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

anacondaを用いた際のエラー解決方法

今回私はanacondaを使ってtensorflow,keras,pythonの勉強していて様々なエラーが発生し、その解決した内容を書いてきます。

 anacondaからターミナルを開いた時『プロセスが完了しました』と表示されコマンドを打つことができず 

何をしたかは忘れましたが仮想環境に入ろうとしても入れなかったため(ターミナルの先頭に私の場合は(tf111cpu))が表示されなかった。
解決策としては、調べた記事通りに進めて本来anacondaと混ぜて使うものではないpyenvを使ったため、pyenvと混在していてanacondaがうまく動作していなかったためだと思います。まずはpyenvをアンインストールしてanacondaが動く状態にしないといけないと思いアンインストールしました。そして、jupyter noteでimport tensorflowを実行したら以下のエラーが発生しました。

ModuleNotFoundError Traceback (most recent call last)
in
----> 1 import tensorflow
2 from tensorflow import keras

ModuleNotFoundError: No module named 'tensorflow'

そこで、仮想環境にもjupyterをインストールしてから、jupyter notebookを起動してもいけなかったため、仮想環境を有効化してから

conda install tensorflow

上記のコマンドを実行したら解決しました。


import tensorflow
from tensorflow import keras

%matplotlib inline
import matplotlib.pyplot as plt

batch_size = 128
num_class = 10
epochs = 20

(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()

NameError Traceback (most recent call last)
in
----> 1 (x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()

NameError: name 'keras' is not defined

また、進めているうちにこのようなエラーがでましたがセルの実行順が前後していたようで、CellメニューからRun allとして全てのセルを再実行したらエラーが解決できました。

in []の数字が順番になってないといけなく、それじゃないとデータの整合性が合わなくなることがあるそうです。

以上にになります。ありがとうございました!

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Keras について調査中

Keras について調査中

(たぶん、いろいろ間違えている。)

Keras関連で利用しているtensorflowはtensoflow1.xのこともあるし、tensoflow2.xのことがある。
tensorflow2.xではtensorflow1.x で動作しないことがある。

Kerasで処理する場合でも、kerasでbackend でtensorflowを使うことによってtensorflowのバージョンの影響を受けるようだ。

そのため、別のバージョンのtensorflow を必要とするときはpython3 -m venv .venvなどとして仮想環境を作り、その中にpip install で目的のバージョンのtensorflow を利用して、作業すること。

tensorflowのバージョンの記述のないある程度古い記事の場合には、tensorflow1.x を使っていることが多い。

tensorflowの場合、

  • frozen になっていないモデル:
  • frozen になっていないモデル

との両方があって、他のフレームワークで使うための入力としては、frozenになっているのを使う。

わかっていないこと。
なぜ .pbファイルだけでは不十分なのか?
それでいて
.pbファイルを読んだあとに、pbtxtファイルを生成しているのがあるのか?

第1段階:Kerasで学習、Kerasで推論

TensorFlow > 学ぶ > TensorFlow Core > チュートリアル > Image classification

kerasのモデルのcompileとは

コンパイル

モデルの学習を始める前に,compileメソッドを用いどのような学習処理を行なうかを設定する必要があります.compileメソッドは3つの引数を取ります:

最適化アルゴリズム: 引数として,定義されている最適化手法の識別子を文字列として与える(rmspropやadagradなど),もしくは Optimizerクラスのインスタンスを与えることができます. 参考: 最適化
損失関数: モデルが最小化しようとする目的関数です.引数として,定義されている損失関数の識別子を文字列として与える(categorical_crossentropyやmseなど),もしくは目的関数を関数として与えることができます.参考:損失関数
評価関数のリスト: 分類問題では精度としてmetrics=['accuracy']を指定したくなるでしょう.引数として,定義されている評価関数の識別子を文字列として与える,もしくは自分で定義した関数を関数として与えることができます.

https://keras.io/ja/getting-started/sequential-model-guide/

上記の github 上の ipynb ファイル classification.ipynb

github Keras Multi label Image Classification

Keras modelを保存するには?
モデル全体の保存/読み込み(アーキテクチャ + 重み + オプティマイザの状態)

model.save('my_model.h5')

from keras.models import load_model
model = load_model('my_model.h5')

Kerasで学習のモデルを作る際のネットワークは、drop_outのように推論時には使われない構造が入っている。そのため、Kerasで学習に用いたネットワーク構造では、そのままで、推論を効率的に行うネットワークを与えることが簡単ではない。
(どうやら、それが、Kerasのモデルを直接、他のモデルに変換するのが簡単ではないことにつながっているのだろうか。)

HDF5 ファイル

Keras - Keras のファイルの形式について

model.to_json()
[TF]KerasでModelとParameterをLoad/Saveする方法

to_json()で出力されるファイルは、下にあるkeras to tensorflow のスクリプトの中で使われている。

model.save_weights(filepath): モデルの重みをHDF5形式のファイルに保存します.
https://keras.io/ja/models/about-keras-models/

第2段階:Kerasで学習、Tensorflowで推論

kerasのモデルをデプロイする手順

KerasのTensorflow Backendで作ったCNNをTensorflow Graphにして使う

github Keras to TensorFlow

python keras_to_tensorflow.py 
    --input_model="path/to/keras/model.h5" 
    --input_model_json="path/to/keras/model.json" 
    --output_model="path/to/save/model.pb"

--save_graph_def を有効にするとpbtxt ファイルを出力する

第3段階:Kerasで学習、OpenCVで推論

OpenCVで推論するときには
*.pb, *.pbtxt の2つのファイルを必要とする。
*.pbファイルは、Protocol Buffers形式のデータ構造のデータファイルです。

TensorFlow内部構造解析 (1.1) Protocol Buffers形式のデータ構造

第4段階:Kerasで学習、OpenVinoで推論

Keras to OpenVINO format conversion

その他:keras からOnnxへの変換

keras2onnx


Tensorflow の場合

Tensorflow で学習、Tensorflow で推論

Tensorflow で学習、Tensorflowのfronzenモデルで推論

TensorFlow Object Detection API

Tensorflow で学習、OpenCVで推論

この場合には、推論実行時には tensorflow のインストールは不要になる。

Try to run the model using OpenCV:

readNetFromTensorflow()

retval = cv.dnn.readNetFromTensorflow( model[, config]) 

model path to the .pb file with binary protobuf description of the network architecture
config path to the .pbtxt file that contains text graph definition in protobuf format. Resulting Net object is built by text graph using weights from a binary one that let us make it more flexible.

*.pb , *.pbtxt の2種類の学習済ファイルが必要になる。

Tensorflow で推論、OpenVinoで推論

Converting a TensorFlow* Model


pbtxt file
http://docs.fabo.io/tensorflow/building_graph/tensorflow_protocol_buffers_part2.html

Deep Learningアプリケーション開発 (2) TensorFlow with Python
https://qiita.com/iwatake2222/items/80fc73ff23d8f51650f5

また、get_model_info 関数を呼ぶことで、変換したTensorFlow用モデルの情報をJSONファイルに保存します。

stack overflow How to transform keras model to tensorflow .pb and .pbtxt without issues?

https://answers.opencv.org/question/206493/keras-to-tensorflow-to-opencv-dnn/
pbファイルからpbtxtを生成する例。生成後にpb,pbtxt ファイルの両方を用いて
cvNet = cv.dnn.readNetFromTensorflow('lenet.pb', 'lenet2.pbtxt')
でモデルを読み込んでいる。

your .pbtxt file isn't useful "as is", you have to edit it a bit:
then, you have to manually replace all flatten nodes with a single Flatten one,and rewire the inputs. the end of your .pbtxt should look like this:


https://github.com/pipidog/keras_to_tensorflow


https://medium.com/@pipidog/how-to-convert-your-keras-models-to-tensorflow-e471400b886a

    build and train your model in Keras
    Use K.get_session() to get TF session and output the model as .pb file
    Load .pb file using tf.GraphDef()
    Get the interface to tensors in the graph using their names
    Predict the results as usual tensorflow problem

https://github.com/ohisama/keras_to_tensorflow


https://www.tensorflow.org/lite/convert/python_api?hl=ja

https://www.tensorflow.org/lite/guide/inference

https://www.tensorflow.org/lite/guide/python

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

vscode + pytest 環境で tensorflow 使ってるとテストディスカバリが失敗する

この記事は何

Python 開発環境を VSCode に移し中、pytest を VSCode 環境で動かそうと色々試すも何故かディスカバリに失敗してしまい、しばらく詰まったのでメモ。

背景

Remote Development で繋いでいる VSCode 環境で、新たに Python プロジェクトを作成しています。
Python 環境は poetry で作成し、テストのため pytest を導入しました。
CUI から pytest が poetry run pytest 問題なく実行できることを確認し、VSCode 上からテストを実行させようとしたところ、テストディスカバリに失敗しました。

原因

VSCode から pytest でテストディスカバリを行う際に、何故か標準出力があると失敗扱いになっていました。
下記の issue などから何かしら標準出力があると失敗することが指摘されています。
https://github.com/microsoft/vscode-python/issues/6594
https://github.com/microsoft/vscode-python/issues/7574

TensorFlow を使っている場合、import tensorflow as tf するだけで色々 Warning だったりが出てしまいますが、それが原因だったようです。

解決策

上記 issue の通りです。TensorFlow の出力を制御するため、次のようなファイルを .env という名前でプロジェクトに置きます。

.env
TF_CPP_MIN_LOG_LEVEL='2'

TF のログ出力を制御するための環境変数です。2を設定することで、WARNINGまでは出なくなります。3にするとエラーも出なくなります。

他の種類の標準出力もなんらかの方法で出ないようにできれば、対策できそうです。

以上です。原因が標準出力だということに気づくのに時間かかったので、参考になれば...

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む