Ubuntu で,システム Python 以外の Python をインストールしたい場合は pyenv が便利である: 別ページで説明している.
Python の公式ページ: http://www.python.org/
Python は,次のコマンドで起動できる.
システム Python を用いるときは,pip, setuptools の更新は次のコマンドで行う.
sudo apt -y update sudo apt -y install python3-pip python3-setuptools
pip は,次のコマンドで起動できる.
【Python 開発環境のインストール】
Python を使うときは,Python開発環境や Python コンソール(Jupyter Qt Console,Spyder,PyCharm,PyScripter など)の利用も便利である
Windows, Ubuntu での Python 開発環境,Python コンソール(Jupyter Qt Console, Jupyter ノートブック (Jupyter Notebook), Jupyter Lab, Nteract, spyder)のインストール: 別ページで,インストール手順を説明している.
コマンドプロンプトを管理者として実行し,次のコマンドを実行.
python -m pip install -U numpy pandas seaborn matplotlib
端末で,次のコマンドを実行
sudo apt -y update sudo apt -y install python3-numpy python3-pandas python3-seaborn python3-matplotlib
Git の URL: https://git-scm.com/
Windows での手順を示す.Ubuntu でも同様の手順である.
mkdir C:\data cd C:\data rmdir /s /q kmnist
Kuzushiji-MNIST, Kuzushiji-49, Kuzushiji-Kanji の 3種類をダウンロードできる.
下の実行例では,「2」,「1」を選び,Kuzushiji-49 をダウンロードしている.
cd C:\data git clone https://github.com/rois-codh/kmnist cd kmnist python download_data.py
Kuzushiji-MNIST, Kuzushiji-49, Kuzushiji-Kanji の 3種類をダウンロードできる.
下の実行例では,「1」,「2」を選び,Kuzushiji-49 をダウンロードしている.
cd C:\data cd kmnist python download_data.py
import numpy as np x_train = np.load("C:/data/kmnist/k49-train-imgs.npz")['arr_0'] y_train = np.load("C:/data/kmnist/k49-train-labels.npz")['arr_0'] x_test = np.load("C:/data/kmnist/k49-test-imgs.npz")['arr_0'] y_test = np.load("C:/data/kmnist/k49-test-labels.npz")['arr_0'] # 【x_train, x_test, y_train, y_test の numpy ndarray への変換と,値の範囲の調整(値の範囲が 0 ~ 255 であるのを,0 ~ 1 に調整)する】 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))
%matplotlib inline import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') # Suppress Matplotlib warnings plt.imshow(x_train[0], cmap='gray') plt.imshow(x_test[0], cmap='gray')
import numpy as np x_train = np.load("C:/data/kmnist/kmnist-train-imgs.npz")['arr_0'] y_train = np.load("C:/data/kmnist/kmnist-train-labels.npz")['arr_0'] x_test = np.load("C:/data/kmnist/kmnist-test-imgs.npz")['arr_0'] y_test = np.load("C:/data/kmnist/kmnist-test-labels.npz")['arr_0'] # 【x_train, x_test, y_train, y_test の numpy ndarray への変換と,値の範囲の調整(値の範囲が 0 ~ 255 であるのを,0 ~ 1 に調整)する】 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))
%matplotlib inline import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') # Suppress Matplotlib warnings plt.imshow(x_train[0], cmap='gray') plt.imshow(x_test[0], cmap='gray')
Kuzushiji-MNIST を用いる.
from __future__ import absolute_import, division, print_function, unicode_literals import tensorflow.compat.v2 as tf tf.enable_v2_behavior() from tensorflow.keras import backend as K K.clear_session() print(tf.__version__) import numpy as np import tensorflow_datasets as tfds from tensorflow.keras.preprocessing import image %matplotlib inline import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') # Suppress Matplotlib warnings
x_train = x_train.astype("float32") / 255.0 x_test = x_test.astype("float32") / 255.0 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))
class_names = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] 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(class_names[y_train[i]]) plt.show()
2層のニューラルネットワークを作成
1層目:ユニット数は 128
2層目:ユニット数は 10
ADAM を使う場合のプログラム例
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.Dropout(rate=0.5)) m.add(tf.keras.layers.Dense(units=10, activation='softmax')) m.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),, loss='sparse_categorical_crossentropy', metrics=['accuracy'])
SGD を使う場合のプログラム例
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(rate=0.5)) m.add(tf.keras.layers.Dense(units=10, activation='softmax')) m.compile(optimizer=tf.keras.optimizers.SGD(lr=0.01, momentum=0.9, nesterov=True), loss='sparse_categorical_crossentropy', metrics=['accuracy'])
print(m.summary())
EPOCHS = 50 history = m.fit(x_train, y_train, validation_data=(x_test, y_test), verbose=2, epochs=EPOCHS)
※ 訓練(学習)などで乱数が使われるので,下図と違う値になる.
predictions = m.predict( x_test ) print( predictions[0] )
テスト画像 0 番の正解を表示
print( y_test[0] )
参考Webページ: 訓練の履歴の可視化については,https://keras.io/ja/visualization/
acc = history.history['accuracy'] val_acc = history.history['val_accuracy'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(1, len(acc) + 1) # "bo" は青いドット plt.plot(epochs, loss, 'bo', label='Training loss') # ”b" は青い実線 plt.plot(epochs, val_loss, 'b', label='Validation loss') plt.title('Training and validation loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show()
plt.clf() # 図のクリア acc = history.history['accuracy'] val_acc = history.history['val_accuracy'] loss = history.history['loss'] val_loss = history.history['val_loss'] plt.plot(epochs, acc, 'bo', label='Training acc') plt.plot(epochs, val_acc, 'b', label='Validation acc') plt.title('Training and validation accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.show()