スキップしてメイン コンテンツに移動

98%精度のNNモデルが間違える画像(MNIST)とは?

「28x28数字画像入力→L.Linear(100ノード)→L.Linear(100ノード)→L.Linear(10ノード)→10出力クラス」の形のNNモデルを、MNISTデータで98%精度まで学習させた予測器を使用して、MNIST画像データの中を少し深く掘り下げて見てみる。
記事: Chainer初試行⇒成功のNNモデル・結果を利用。

NNモデルのロード

In [1]:
import chainer
import chainer.links as L
import chainer.functions as F

class MLP(chainer.Chain):

    def __init__(self, n_mid_units=100, n_out=10):
        super(MLP, self).__init__()

        # パラメータを持つ層の登録
        with self.init_scope():
            self.l1 = L.Linear(None, n_mid_units)
            self.l2 = L.Linear(n_mid_units, n_mid_units)
            self.l3 = L.Linear(n_mid_units, n_out)

    def forward(self, x):
        # データを受け取った際のforward計算を書く
        h1 = F.relu(self.l1(x))
        h2 = F.relu(self.l2(h1))
        return self.l3(h2)
In [2]:
from chainer import serializers

my_net = MLP()
serializers.load_npz('my_mnist.model', my_net)
In [3]:
from chainer.datasets import mnist
from chainer.dataset import concat_examples
from chainer import iterators

train_val, test = mnist.get_mnist(withlabel=True, ndim=1)

x, t = concat_examples(test, -1)
with chainer.using_config('train', False), chainer.using_config('enable_backprop', False):
    y = my_net(x)

accuracy = F.accuracy(y, t)
print("精度:", accuracy.array, "N:", len(y))
精度: 0.972000002861023 N: 10000

NNモデルが間違えた画像データを描画

テスト側のデータを使って、NNモデルが間違えた画像を全て描画して、見てみると、
In [33]:
import numpy as np
import matplotlib.pyplot as plt

label_pred = y.array.argmax(axis=1)
label_true = t
i_wrong = np.where(label_pred != label_true)[0] # HACK: 謎のtupleで返る為、[0]必要
In [42]:
fig = None
i_ax = 0
for i_x in i_wrong:
    
    if fig is None or i_ax >= 100:
        fig = plt.figure(figsize=(12, 12))
        plt.subplots_adjust(hspace=0, wspace=0)
        i_ax = 0
    i_ax += 1
    
    ax = fig.add_subplot(10, 10, i_ax)
    ax.imshow(x[i_x].reshape(28, 28), cmap='gray', interpolation='none')
    ax.axis('off')
    
plt.show()

コメント

このブログの人気の投稿

1906.09 ChainerのNNモデルの定義でビギナーが陥りやすいエラー 4例

1906.09 ChainerのNNモデルの定義でビギナーが陥りやすいエラー 4例 Chainerを始めて、エラーが起こると、そのエラーの説明表示を見ても、よく分からないことが多い。ここでは、問題形式で、ビギナーが陥りやすいエラーを4例、挙げてみました。 例1 例えば、以下のコードを実行すると「Expect: in_types[2].dtype == in_types[0].dtype」「Actual: float32 != float64」のエラーが発生する。何がいけないのか? In [1]: # sec: lib import numpy as np import chainer import chainer.links as L import chainer.functions as F # sec: ver chainer . print_runtime_info () Platform: Windows-7-6.1.7601-SP1 Chainer: 5.3.0 NumPy: 1.16.2 CuPy: Not Available iDeep: Not Available NNモデルを定義 In [2]: class MyConvNet ( chainer . Chain ): def __init__ ( self ): super ( MyConvNet , self ) . __init__ () # パラメータを持つ層の登録 with self . init_scope (): self . c1 = L . Convolution2D ( None , 20 , ksize = 3 , stride = 2 , pad = 0 ) self . c2 = L . Convolution2D ( None , 40 , ksize = 3 , stride = 2 , pad = 0 ) self . l1 = L . L

Jupyter Notebook (.ipynb)の綺麗な見た目のまま内容をブログで公開する方法

検索 Webを探してみても、意外と、Jupyter Notebook (.ipynb)の内容を、簡単で綺麗に表示できる方法が見当たらない。 https://minus9d.hatenablog.com/entry/2018/03/17/153537 Github  Githubのレポジトリに登録された.ipynbファイルは自動的に整形されて閲覧できます。 Gist  .ipynbファイルのテキストを全文コピーしてGistに貼り付け Binder (beta) Herokuの無料枠を使ってJupyterサーバを立てる nbconvertコマンドを使ってHTMLやMarkdownに変換し加工 別サイトのサービスを利用しなくてはならないと、記事を書く度に毎回、アップロード操作しなくてはならない。 どれも面倒。 そこで 記事の原稿はローカルPCに残る 投稿操作は1回きりで楽 HTMLをそのまま貼り付けたい を満たすような方法を模索すると、以下の方法で、おおよそ 簡単にJupyter Notebookの内容をそのままブログに載せられる ことが分かった。 方法 ブログ記事の作成・編集、コードの実行・試行錯誤は、すべてローカルのPCのJupyter Notebook(.ipynb)上で作る。  ↓ Jupyter Notebookのメニュー→File→ Print Preview でプレビューを表示。 プレビューページ が表示される。  ↓ プレビューページの一部・全てを選択して、 コピー 。  ↓ ブログ(Bloggerを使用)サイトで新規記事を作成して、 ペースト 。 プレビュー表示のHTMLが、そのまま維持・貼り付けされる。  ↓ ブログを投稿。 利点 この方法であれば、かなり書きやすい。 ローカルのPCに原稿の 文章データ(.ipynb)はすべて残り 、安心。 ブログに投稿しても、見た目がほとんど同じ、 綺麗な見た目のまま を維持可。 ブログへの投稿は、 コピー&ペーストだけ でOK、非常に楽。 グラフ画像も、コピー&ペーストで同様に一括で貼り付け られて投稿されるので、楽。 ブログ記事の修正投稿は、ローカル

Chainerをインストール⇒成功 (ローカルPCのJupyter Notebook上、pipを利用)

ローカルPCで稼働するJupyter NotebookのPythonにChainerをインストール。 Jupyter Notebookは、WinPython 32bit 3.5.2.3 Qt5をインストールして、導入。 1行「!pip install chainer」を実行するだけ でOK、非常に簡単。 In [3]: ! pip install chainer Collecting chainer Downloading https://files.pythonhosted.org/packages/6d/a1/8e9110a60e045341e36910568cd53f54a791fff6844448a46331f597177f/chainer-5.2.0.tar.gz (513kB) Collecting filelock (from chainer) Downloading https://files.pythonhosted.org/packages/d7/ca/3c74396a9ed8a4cfab5459800edeef9a1269591cb21f5a49bd71a49c5fa2/filelock-3.0.10-py3-none-any.whl Requirement already satisfied: numpy>=1.9.0 in c:\users\sample\winpython-32bit-3.5.2.3qt5\python-3.5.2\lib\site-packages (from chainer) (1.11.2+mkl) Collecting protobuf>=3.0.0 (from chainer) Downloading https://files.pythonhosted.org/packages/20/b7/fd638c741e9a75da0ff955b50cf42ddb71042575e5ba14d6ffd269e37a24/protobuf-3.6.1-cp35-cp35m-win32.whl (935kB) Requirement already satisfied: six>=1.9.0 in c:\users\sample\wi

Chainer初試行⇒成功 (ローカルPCのJupyter Notebook上、CPUでの実行、MNIST)

「4.2. Chainerの基本的な使い方」を実際に実行してみる。 https://japan-medical-ai.github.io/medical-ai-course-materials/notebooks/Introduction_to_Chainer.html#Chainer%E3%81%AE%E5%9F%BA%E6%9C%AC%E7%9A%84%E3%81%AA%E4%BD%BF%E3%81%84%E6%96%B9 インストール直後の初回試行時は、net(x)の評価の行でエラーとなっていたが、 Jupyter Notebook再起動、PC再起動 などを実施した後に、エラーが無くなる。 In [5]: from chainer.datasets import mnist # データセットがダウンロード済みでなければ,ダウンロードも行う train_val , test = mnist . get_mnist ( withlabel = True , ndim = 1 ) Downloading from http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz... Downloading from http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz... Downloading from http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz... Downloading from http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz... In [46]: import matplotlib.pyplot as plt plt . imshow ( train_val [ 0 ][ 0 ] . reshape ( 28 , 28 ), cmap = 'gray' , interpolation = "none" ) plt . show

1906.07 Chainer NNモデルの中間層でデータを分岐・結合する方法

1906.07 Chainer NNモデルの中間層でデータを分岐・結合 chainer.functionsの「reshape」と「concat」を用いて結合できる模様。 https://docs.chainer.org/en/stable/reference/generated/chainer.functions.reshape.html https://docs.chainer.org/en/stable/reference/generated/chainer.functions.concat.html#chainer.functions.concat In [1]: # sec: lib import numpy as np import chainer import chainer.links as L import chainer.functions as F # sec: ver chainer . print_runtime_info () Platform: Windows-7-6.1.7601-SP1 Chainer: 5.3.0 NumPy: 1.16.2 CuPy: Not Available iDeep: Not Available NNモデルを定義 In [61]: # sec: NNモデルの定義 class MyConvNet ( chainer . Chain ): def __init__ ( self ): super ( MyConvNet , self ) . __init__ () # パラメータを持つ層の登録 with self . init_scope (): self . c1 = L . Convolution2D ( None , 10 , ksize = 3 , stride = 2 , pad = 0 ) self . c2 = L . Convolution2D ( None , 10 , ksize = 5 ,

NNモデルの評価値をもう一度計算⇒成功 (必要部分だけ抜粋したコードをもう一度書く)

抜粋したコードで評価 Iterator⇒成功 In [56]: my_net = MLP () serializers . load_npz ( 'my_mnist.model' , my_net ) In [57]: train_iter = iterators . SerialIterator ( train_val , batchsize ) x , t = concat_examples ( train_iter . next (), gpu_id ) with chainer . using_config ( 'train' , False ), chainer . using_config ( 'enable_backprop' , False ): y = net ( x ) accuracy = F . accuracy ( y , t ) print ( accuracy . array ) 0.984375 抜粋したコードで評価 画像1枚⇒成功 In [59]: x , t = test [ random . randint ( 0 , len ( test ))] x = infer_net . xp . asarray ( x [ None , ... ]) with chainer . using_config ( 'train' , False ), chainer . using_config ( 'enable_backprop' , False ): y = infer_net ( x ) y = y . array print ( y ) print ( y . argmax ( axis = 1 )[ 0 ], t ) [[ -0.13074946 -3.27831101 14.03434944 4.3200264 -9.22432804 -6.01922178