ニューラルネットワークの作成,訓練(学習),予測を行う. MNIST データセット,Fashion MNIST データセットを使用する.
目次
サイト内の関連ページ
謝辞:ここで使用しているソフトウエア類の作者に感謝します.
参考Webページ:
TensorFlow のチュートリアルの Web ページに記載のソースコードを使用している.
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
Python プログラムを動かす.
※ Python プログラムを動かすために, Windows では,「python」コマンドを使う. Ubuntu では「python3」コマンドを使う.
開発環境や Python コンソール(Jupyter Qt Console,spyder,PyCharm,PyScripter など)も便利である.
from __future__ import absolute_import, division, print_function, unicode_literals import tensorflow.compat.v2 as tf import tensorflow_datasets as tfds import numpy as np import matplotlib.pyplot as plt tf.enable_v2_behavior() print(tf.__version__) mnist, metadata = tfds.load( name="mnist", as_supervised=False, with_info=True, batch_size = -1) train, test = mnist['train'], mnist['test'] print(metadata) x_train, y_train = train["image"].numpy().astype("float32") / 255.0, train["label"] x_test, y_test = test["image"].numpy().astype("float32") / 255.0, test["label"] plt.figure(figsize=(10,10)) for i in range(25): plt.subplot(5,5,i+1) plt.xticks([]) plt.yticks([]) plt.grid(False) image, label = train["image"][i], train["label"][i] plt.imshow(image.numpy()[:, :, 0].astype(np.float32), cmap=plt.get_cmap("gray")) plt.xlabel(label.numpy()) plt.show()
m = tf.keras.Sequential() m.add(tf.keras.layers.Flatten(input_shape=(28, 28, 1))) m.add(tf.keras.layers.Dense(units=128, activation=tf.nn.relu)) m.add(tf.keras.layers.Dropout(rate=0.2)) m.add(tf.keras.layers.Dense(units=10, activation=tf.nn.softmax)) m.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
print(m.summary())
history = m.fit(x_train, y_train, epochs=50)
※ 訓練(学習)などで乱数が使われるので,下図と違う値になる.
print( m.evaluate(x_test, y_test, verbose=2) )
テスト画像を,ニューラルネットワークに与えて,予測させる
※ 訓練(学習)などで乱数が使われるので,下図と違う値になる.
predictions = m.predict( x_test ) print( predictions[0] )
テスト画像 0 番の正解を表示
print( y_test[0] )
参考Webページ: 訓練の履歴の可視化については,https://keras.io/ja/visualization/
import matplotlib.pyplot as plt loss = history.history['loss'] epochs = range(1, len(loss) + 1) # "bo" は青いドット plt.plot(epochs, loss, 'bo', label='Training loss') plt.title('Training loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show()
# plt.clf() # 図のクリア accuracy = history.history['accuracy'] epochs = range(1, len(accuracy) + 1) # "bo" は青いドット plt.plot(epochs, accuracy, 'bo', label='Training accuracy') plt.title('Training accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.show()
Python プログラムを動かす.
※ Python プログラムを動かすために, Windows では,「python」コマンドを使う. Ubuntu では「python3」コマンドを使う.
開発環境や Python コンソール(Jupyter Qt Console,spyder,PyCharm,PyScripter など)も便利である.
from __future__ import absolute_import, division, print_function, unicode_literals import tensorflow.compat.v2 as tf import tensorflow_datasets as tfds import numpy as np import matplotlib.pyplot as plt tf.enable_v2_behavior() print(tf.__version__) fashion_mnist, metadata = tfds.load( name="fashion_mnist", as_supervised=False, with_info=True, batch_size = -1) train, test = fashion_mnist['train'], fashion_mnist['test'] print(metadata) x_train, y_train = train["image"].numpy().astype("float32") / 255.0, train["label"] x_test, y_test = test["image"].numpy().astype("float32") / 255.0, test["label"] class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] plt.figure(figsize=(10,10)) for i in range(25): plt.subplot(5,5,i+1) plt.xticks([]) plt.yticks([]) plt.grid(False) image, label = train["image"][i], train["label"][i] plt.imshow(image.numpy()[:, :, 0].astype(np.float32), cmap=plt.get_cmap("gray")) plt.xlabel(class_names[label]) plt.show()
m = tf.keras.Sequential() m.add(tf.keras.layers.Flatten(input_shape=(28, 28, 1))) m.add(tf.keras.layers.Dense(units=128, activation=tf.nn.relu)) m.add(tf.keras.layers.Dropout(rate=0.2)) m.add(tf.keras.layers.Dense(units=10, activation=tf.nn.softmax)) m.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
print(m.summary())
history = m.fit(x_train, y_train, epochs=50)
※ 訓練(学習)などで乱数が使われるので,下図と違う値になる.
print( m.evaluate(x_test, y_test, verbose=2) )
テスト画像を,ニューラルネットワークに与えて,予測させる
※ 訓練(学習)などで乱数が使われるので,下図と違う値になる.
predictions = m.predict( x_test ) print( predictions[0] )
テスト画像 0 番の正解を表示
print( y_test[0] )
参考Webページ: 訓練の履歴の可視化については,https://keras.io/ja/visualization/
import matplotlib.pyplot as plt loss = history.history['loss'] epochs = range(1, len(loss) + 1) # "bo" は青いドット plt.plot(epochs, loss, 'bo', label='Training loss') plt.title('Training loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.show()
# plt.clf() # 図のクリア accuracy = history.history['accuracy'] epochs = range(1, len(accuracy) + 1) # "bo" は青いドット plt.plot(epochs, accuracy, 'bo', label='Training accuracy') plt.title('Training accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.show()
本サイトは金子邦彦研究室のWebページです.サイトマップは,サイトマップのページをご覧下さい. 本サイト内の検索は,サイト内検索のページをご利用下さい.
問い合わせ先: 金子邦彦(かねこ くにひこ)