Keras は TensorFlow, CNTK, Theano 上で動くニューラルネットライブラリです.
このWebページの前半では Keras のインストール手順を、後半では、次のデータを使っての実行の手順を示す.
謝辞:ここで使用しているソフトウエア類の作者に感謝します.
Python の URL: http://www.python.org/
インストール手順の詳細は: 別ページで説明している.
コマンドプロンプトを管理者として実行し,次のコマンドを実行.
python -m pip install -U pip setuptools python -m pip install -U jupyterlab jupyter jupyter-console jupytext nteract_on_jupyter spyder
システム Python を使用(インストール操作は不要)
端末で,次のコマンドを実行.
sudo apt -y install python3-dev python3-pip python3-setuptools sudo pip3 uninstall ptyprocess sniffio terminado tornado jupyterlab jupyter jupyter-console jupytext nteract_on_jupyter spyder sudo apt -y install jupyter jupyter-qtconsole spyder3 sudo apt -y install python3-ptyprocess python3-sniffio python3-terminado python3-tornado sudo pip3 install jupyterlab nteract_on_jupyter
参考Webページ: 「https://keras.io/ja/」の「30 秒で Keras に入門しましょう」
Windows での手順を示す.Ubuntu でも同様の手順になる.
python -m pip install -U numpy scipy h5py scikit-learn matplotlib seaborn
Python 処理系として,Jupyter Qt Console を起動
jupyter qtconsole
ここでは,Jupyter Qt Console を使っている. 他の開発環境(spyder,PyCharm,PyScripter など)も便利である.
ここから先は,Jupyter Qt Console の画面で説明する.
次の Python プログラムを実行
import sklearn.datasets iris = sklearn.datasets.load_iris() X = iris.data y = iris.target
x_train, x_test は主成分分析で2次元にマッピング, y_train, y_test は色.
import pandas as pd import seaborn import sklearn.decomposition # 主成分分析でプロット def pcaplot(A, b, alpha): pca = sklearn.decomposition.PCA(n_components=2) pca.fit(A) a12 = pd.DataFrame( pca.fit_transform(A), columns=['a1', 'a2'] ) a12['target'] = b seaborn.lmplot(x='a1', y='a2', data=a12, hue='target', scatter_kws={'alpha': alpha}, fit_reg=False) pcaplot(X, y, 1)
次の Python プログラムを実行
import keras x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(X, y, train_size=0.5) # 2次元の配列. 要素は float64, 最大値と最小値を用いて正規化 import numpy as np def normalizer(A): M = np.reshape(A, (len(A), -1)) M = M.astype('float32') max = M.max(axis=0) min = M.min(axis=0) return (M - min)/(max - min) x_train = normalizer(x_train) x_test = normalizer(x_test) y_train_logit = keras.utils.to_categorical(y_train) y_test_logit = keras.utils.to_categorical(y_test)
pcaplot(np.concatenate( (x_train, x_test) ), np.concatenate( (y_train, y_test) ), 1)
次の Python プログラムを実行
from keras.models import Sequential model = Sequential() from keras.layers import Dense, Activation model.add(Dense(units=64, input_dim=len(x_train[0]))) model.add(Activation('relu')) model.add(Dense(units=max(set(y_train)) - min(set(y_train)) + 1)) model.add(Activation('softmax')) model.compile(loss='sparse_categorical_crossentropy', optimizer='sgd', metrics=['accuracy']) model.fit(x_train, y_train, epochs=200) score=model.evaluate(x_test, y_test, batch_size=1) print(score) model.predict(x_test) model.summary()
from keras.models import Sequential model2 = Sequential() from keras.layers import Dense, Activation import keras.losses model2.add(Dense(units=64, input_dim=len(x_train[0]))) model2.add(Activation('relu')) model2.add(Dense(units=max(set(y_train)) - min(set(y_train)) + 1)) model2.add(Activation('softmax')) model2.compile(loss=keras.losses.sparse_categorical_crossentropy, optimizer=keras.optimizers.SGD(lr=0.01, momentum=0.9, nesterov=True)) model2.fit(x_train, y_train, epochs=200) score2=model2.evaluate(x_test, y_test, batch_size=1) print(score2) model2.predict(x_test)
keras に付属のデータセットに関する Web ページ: https://keras.io/ja/datasets/
次の Python プログラムを実行
from keras.datasets import cifar10 (x_train, y_train), (x_test, y_test) = cifar10.load_data() import numpy as np # 2次元の配列. 要素は float32, 最大値と最小値を用いて正規化 def normalizer(A): M = np.reshape(A, (len(A), -1)) M = M.astype('float32') max = M.max(axis=0) min = M.min(axis=0) return (M - min)/(max - min) x_train = normalizer(x_train) x_test = normalizer(x_test)
x_train, x_test は主成分分析で2次元にマッピング, y_train, y_test は色.
import pandas as pd import seaborn import sklearn.decomposition # 主成分分析でプロット def pcaplot(A, b, alpha): pca = sklearn.decomposition.PCA(n_components=2) pca.fit(A) a12 = pd.DataFrame( pca.fit_transform(A), columns=['a1', 'a2'] ) a12['target'] = b seaborn.lmplot(x='a1', y='a2', data=a12, hue='target', scatter_kws={'alpha': alpha}, fit_reg=False) pcaplot(np.concatenate( (x_train, x_test) ), np.concatenate( (y_train, y_test) ), 0.1)
参考Webページ http://www.procrasist.com/entry/2017/01/07/154441
https://keras.io/getting-started/sequential-model-guide/ で言及されている次の事項について.
https://github.com/fchollet/keras/tree/master/examples に記載のプログラムを動かしてみる.
https://github.com/fchollet/keras/blob/master/examples/cifar10_cnn.py を実行してみる.
本サイトは金子邦彦研究室のWebページです.サイトマップは,サイトマップのページをご覧下さい. 本サイト内の検索は,サイト内検索のページをご利用下さい.
問い合わせ先: 金子邦彦(かねこ くにひこ)