sklearnでクラスタリング(その1)
データ形式がこうなっていれば、直接KMeansに渡せる。2次元データ6件分。
array([[ 1, 2], [ 1, 4], [ 1, 0], [10, 2], [10, 4], [10, 0]])
以降、確認に使ったコード
>>> import numpy as np >>> from sklearn.cluster import KMeans >>> X = np.array([[1, 2], [1, 4], [1, 0],[10, 2], [10, 4], [10, 0]]) >>> >>> X array([[ 1, 2], [ 1, 4], [ 1, 0], [10, 2], [10, 4], [10, 0]]) >>> kmeans = KMeans(n_clusters=2, random_state=0).fit(X) >>> kmeans.labels_ array([1, 1, 1, 0, 0, 0]) >>> kmeans.predict([[0, 0], [12, 3]]) array([1, 0])
anacondaでTensorFlow環境の準備 その2
VS Codeを使っているので、デバッグとかのための手続き。
Pythonのパスを書き換えればよいらしい。フォルダごととか、ワークスペースごととか設定がありそう。
"python.pythonPath": "C:\\Users\\Cucco\\AppData\\Local\\Continuum\\anaconda3\\envs\\tensorflow_gpuenv\\pythonw.exe"
VS Codeの左下の実行環境が選べるようになっているので、勝手に環境見つけている??
設定書き換えたから?
参考
VS Code で Anaconda の Python デバッグ 環境構築(Visual Studio Code) - BEACHSIDE BLOG
Windows10環境にAnaconda+Visual Studio CodeでPython環境を構築【2017年9月】
anacondaでTensorFlow環境の準備
何が起きているかわからないが以下で成功した。
(base) C:\>conda create -n tensorflow_gpuenv tensorflow-gpu
いろいろインストールしていい?と質問があるのでyを回答。
以上で使えました。
環境を使うときのおまじないは以下。
# To activate this environment, use # # $ conda activate tensorflow_gpuenv # # To deactivate an active environment, use # # $ conda deactivate
Install TensorFlow with pip | TensorFlow にあった動作確認プログラムを動かしてみる。
(tensorflow_gpuenv) C:\>python -c "import tensorflow as tf; print(tf.__version__)" 1.11.0
TensorFlow にあったサンプルのプログラムをC:\tensor\hello_tensor.pyに保存して実行するとこんな感じ。
(tensorflow_gpuenv) C:\>python C:\tensor\hello_tensor.py Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz 11493376/11490434 [==============================] - 1s 0us/step Epoch 1/5 2018-10-27 12:06:34.981339: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2 2018-10-27 12:06:36.063940: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1411] Found device 0 with properties: name: GeForce GTX 1050 Ti major: 6 minor: 1 memoryClockRate(GHz): 1.62 pciBusID: 0000:01:00.0 totalMemory: 4.00GiB freeMemory: 3.30GiB 2018-10-27 12:06:36.070639: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1490] Adding visible gpu devices: 0 2018-10-27 12:06:36.586738: I tensorflow/core/common_runtime/gpu/gpu_device.cc:971] Device interconnect StreamExecutor with strength 1 edge matrix: 2018-10-27 12:06:36.591156: I tensorflow/core/common_runtime/gpu/gpu_device.cc:977] 0 2018-10-27 12:06:36.593388: I tensorflow/core/common_runtime/gpu/gpu_device.cc:990] 0: N 2018-10-27 12:06:36.595640: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1103] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 3011 MB memory) -> physical GPU (device: 0, name: GeForce GTX 1050 Ti, pci bus id: 0000:01:00.0, compute capability: 6.1) 60000/60000 [==============================] - 9s 143us/step - loss: 0.2009 - acc: 0.9416 Epoch 2/5 60000/60000 [==============================] - 6s 93us/step - loss: 0.0803 - acc: 0.9755 Epoch 3/5 60000/60000 [==============================] - 6s 93us/step - loss: 0.0518 - acc: 0.9836 Epoch 4/5 60000/60000 [==============================] - 6s 94us/step - loss: 0.0365 - acc: 0.9888 Epoch 5/5 60000/60000 [==============================] - 6s 94us/step - loss: 0.0268 - acc: 0.9910 10000/10000 [==============================] - 0s 45us/step
一方で、失敗例。tensorFlowのPipインストール手順で環境構築したら、動作確認プログラムがモジュールが足りない、となった。
何が悪いんだろう?
(venv) (base) C:\>python -c "import tensorflow as tf; print(tf.__version__)" Traceback (most recent call last): File "C:\venv\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module> from tensorflow.python.pywrap_tensorflow_internal import * File "C:\venv\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in <module> _pywrap_tensorflow_internal = swig_import_helper() File "C:\venv\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description) File "C:\venv\lib\imp.py", line 243, in load_module return load_dynamic(name, filename, file) File "C:\venv\lib\imp.py", line 343, in load_dynamic return _load(spec) ImportError: DLL load failed: 指定されたモジュールが見つかりません。 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\venv\lib\site-packages\tensorflow\__init__.py", line 22, in <module> from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import File "C:\venv\lib\site-packages\tensorflow\python\__init__.py", line 49, in <module> from tensorflow.python import pywrap_tensorflow File "C:\venv\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 74, in <module> raise ImportError(msg) ImportError: Traceback (most recent call last): File "C:\venv\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in <module> from tensorflow.python.pywrap_tensorflow_internal import * File "C:\venv\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in <module> _pywrap_tensorflow_internal = swig_import_helper() File "C:\venv\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description) File "C:\venv\lib\imp.py", line 243, in load_module return load_dynamic(name, filename, file) File "C:\venv\lib\imp.py", line 343, in load_dynamic return _load(spec) ImportError: DLL load failed: 指定されたモジュールが見つかりません。 Failed to load the native TensorFlow runtime. See https://www.tensorflow.org/install/install_sources#common_installation_problems for some common reasons and solutions. Include the entire stack trace above this error message when asking for help.
複数ファイルを連続して読むプログラム
複数に分割されたファイルを決まった順番で、連続して読む。
csv.readerっぽく。forで1行ずつ読めるようにイテレータとして実装。
import csv class MyIterator(object): def __init__(self, readFileNames, skipHeader=False): self.readFileNames = readFileNames self.currentFileIndex = -1 self.fp = None self.csv_reader = None self.skipHeader = skipHeader def __iter__(self): # next()はselfが実装してるのでそのままselfを返す return self def __next__(self): if self.csv_reader is None: #1個目のファイルを開く self.nextfile() try: value=next(self.csv_reader) return value except StopIteration: #終端まで来たら、このStopIterationが投げられる。 try: self.nextfile() value=next(self.csv_reader) return value except StopIteration: # 次のファイルがなかったので、例外を投げてイテレータを終わる。 raise (StopIteration) except: # ここには来ない。 raise (StopIteration) def nextfile(self): self.currentFileIndex = self.currentFileIndex + 1 if self.fp is not None: self.fp.close() if self.currentFileIndex > len(self.readFileNames)-1: # 次のファイルはないので例外を投げる raise(StopIteration) else: self.fp=open(self.readFileNames[self.currentFileIndex],mode='r',newline='\n') self.csv_reader=csv.reader(self.fp, delimiter=',', quotechar='"') if self.skipHeader is True: next(self.csv_reader) readFileNames=[] readFileNames.append("D:/data/data_01.csv") readFileNames.append("D:/data/data_02.csv") readFileNames.append("D:/data/data_03.csv") my_iterator = MyIterator(readFileNames,skipHeader=True) for value in my_iterator: print(value) my_iterator = MyIterator(readFileNames,skipHeader=False) for value in my_iterator: print(value)
Neural Network Consoleによる学習済みニューラルネットワークの利用
環境構築
ベースはanaconda。nnablaがなく、importに失敗するのでパッケージ追加しました。以下のコマンドを管理者で開いたコンソールで実行。
pip install ipykernel pip install nnabla
事前にpip自体の更新が必要な場合もあり。
python -m pip install --upgrade pip
コードの作成と推論の実行
以下を参考に、アヤメのデータで学習して、推論するところまで。
学習はGUI使いました。学習済みパラメータファイルが20180520_142204というフォルダにある想定です。
import nnabla as nn import nnabla.functions as F import nnabla.parametric_functions as PF #loss関数を削るのでyが不要になる。 #def network(x, y,test=False): def network(x, test=False): # Input -> 4 # BatchNormalization with nn.parameter_scope('BatchNormalization'): h = PF.batch_normalization(x, (1,), 0.9, 0.0001, not test) # Affine -> 50 with nn.parameter_scope('Affine'): h = PF.affine(h, (50,)) # ReLU h = F.relu(h, True) # Affine_2 -> 20 with nn.parameter_scope('Affine_2'): h = PF.affine(h, (20,)) # ReLU_2 h = F.relu(h, True) # Dropout if not test: h = F.dropout(h) # Affine_3 -> 3 with nn.parameter_scope('Affine_3'): h = PF.affine(h, (3,)) # Softmax h = F.softmax(h) # SquaredError # 不要なのでコメントアウト # h = F.squared_error(h, y) return h
以降が追加した推論用のコード。実際には上のコードと同じファイルに記載。
# load parameters # \を/に書き換え必要あり。オリジナルのブログはシングルクオートが全角なので書き換えが必要。 nn.load_parameters('C:/iris_sample/iris_sample.files/20180520_142204/parameters.h5') # Prepare input variable # 3つ推論する場合 x=nn.Variable((3,4)) # 1つ推論する場合 x1=nn.Variable((1,4)) x2=nn.Variable((1,4)) x3=nn.Variable((1,4)) # Let input data to x.d # x.d = ... x.d=[[5.1, 3.5, 1.4, 0.2],[7, 3.2, 4.7, 1.4],[6.3, 3.3, 6, 2.5]] #yの1番目が大きな値になる。listを作って渡せばいいのは楽。 x1.d=[5.1, 3.5, 1.4, 0.2] #yの2番目が大きな値になる。 x2.d=[7, 3.2, 4.7, 1.4] #yの3番目が大きな値になる。 x3.d=[6.3, 3.3, 6, 2.5] # Build network for inference # test=Trueで、ドロップアウトの機能を停止する。BatchNormalizationへの影響は不明。 y = network(x, test=True) # Execute inference y.forward() print(y.d)
実行結果。指数表示なので大小関係わかりにくいがあってるはず。
#[[9.9891686e-01 9.9650992e-04 8.6744032e-05] # [7.5185834e-03 7.6037079e-01 2.3211062e-01] # [7.9514321e-06 3.5711315e-02 9.6428072e-01]]