質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Keras

Kerasは、TheanoやTensorFlow/CNTK対応のラッパーライブラリです。DeepLearningの数学的部分を短いコードでネットワークとして表現することが可能。DeepLearningの最新手法を迅速に試すことができます。

機械学習

機械学習は、データからパターンを自動的に発見し、そこから知能的な判断を下すためのコンピューターアルゴリズムを指します。人工知能における課題のひとつです。

コードレビュー

コードレビューは、ソフトウェア開発の一工程で、 ソースコードの検査を行い、開発工程で見過ごされた誤りを検出する事で、 ソフトウェア品質を高めるためのものです。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

1回答

1539閲覧

MNISTの学習モデルを使用した手書き文字判別時の次元のエラー

Kkeguri

総合スコア6

Keras

Kerasは、TheanoやTensorFlow/CNTK対応のラッパーライブラリです。DeepLearningの数学的部分を短いコードでネットワークとして表現することが可能。DeepLearningの最新手法を迅速に試すことができます。

機械学習

機械学習は、データからパターンを自動的に発見し、そこから知能的な判断を下すためのコンピューターアルゴリズムを指します。人工知能における課題のひとつです。

コードレビュー

コードレビューは、ソフトウェア開発の一工程で、 ソースコードの検査を行い、開発工程で見過ごされた誤りを検出する事で、 ソフトウェア品質を高めるためのものです。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

1クリップ

投稿2020/06/05 04:03

編集2020/06/05 12:02

前提・実現したいこと

eindow8.1でpython3.8をインストールし、
keras,tensorflowをインストールし、
MNISTの画像判別のニュートラルを実施し学習モデルを作成しました。

その学習モデル.h5を使用して、自分の手書き文字を判別使用としたところ、下記のような次元に関するエラーが出ております。

当方、超初心者のため、意味がよくわからず、何がおかしいのかよくわかりません。
教えていただけないでしょうか。

手書きの画像データはペイントで作成し、背景を黒、白文字に28x28でpngとしています。

コードは下記の2つのサイトを参照し、流用しました。
(学習モデルの作成)https://qiita.com/sasayabaku/items/64a01363bcd5c44feb0b
(手書きモデルの判別)https://qiita.com/moritalous/items/1c014afbb97a2e48bbdf

発生している問題・エラーメッセージ

C:\Users\----\Desktop\script_file\200605-2_mnisttest_new>yosoku.py Using TensorFlow backend. 2020-06-05 20:47:52.704005: W tensorflow/stream_executor/platform/default/dso_loader.cc:55 ] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found 2020-06-05 20:47:52.711669: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore ab ove cudart dlerror if you do not have a GPU set up on your machine. 2020-06-05 20:47:59.743375: I tensorflow/stream_executor/platform/default/dso_loader.cc:44 ] Successfully opened dynamic library nvcuda.dll 2020-06-05 20:48:00.002471: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1561] Found device 0 with properties: pciBusID: 0000:01:00.0 name: Quadro K600 computeCapability: 3.0 coreClock: 0.8755GHz coreCount: 1 deviceMemorySize: 1.00GiB deviceMemoryBandwidth: 26.55Gi B/s 2020-06-05 20:48:00.012087: W tensorflow/stream_executor/platform/default/dso_loader.cc:55 ] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found 2020-06-05 20:48:00.017721: W tensorflow/stream_executor/platform/default/dso_loader.cc:55 ] Could not load dynamic library 'cublas64_10.dll'; dlerror: cublas64_10.dll not found 2020-06-05 20:48:00.025252: W tensorflow/stream_executor/platform/default/dso_loader.cc:55 ] Could not load dynamic library 'cufft64_10.dll'; dlerror: cufft64_10.dll not found 2020-06-05 20:48:00.031194: W tensorflow/stream_executor/platform/default/dso_loader.cc:55 ] Could not load dynamic library 'curand64_10.dll'; dlerror: curand64_10.dll not found 2020-06-05 20:48:00.038717: W tensorflow/stream_executor/platform/default/dso_loader.cc:55 ] Could not load dynamic library 'cusolver64_10.dll'; dlerror: cusolver64_10.dll not found 2020-06-05 20:48:00.045310: W tensorflow/stream_executor/platform/default/dso_loader.cc:55 ] Could not load dynamic library 'cusparse64_10.dll'; dlerror: cusparse64_10.dll not found 2020-06-05 20:48:00.053916: W tensorflow/stream_executor/platform/default/dso_loader.cc:55 ] Could not load dynamic library 'cudnn64_7.dll'; dlerror: cudnn64_7.dll not found 2020-06-05 20:48:00.061317: W tensorflow/core/common_runtime/gpu/gpu_device.cc:1598] Canno t dlopen some GPU libraries. Please make sure the missing libraries mentioned above are in stalled properly if you would like to use GPU. Follow the guide at https://www.tensorflow. org/install/gpu for how to download and setup the required libraries for your platform. Skipping registering GPU devices... 2020-06-05 20:48:00.078168: I tensorflow/core/platform/cpu_feature_guard.cc:143] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 2020-06-05 20:48:00.114045: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x68007878f0 initialized for platform Host (this does not guarantee that XLA will be used) . Devices: 2020-06-05 20:48:00.121366: I tensorflow/compiler/xla/service/service.cc:176] StreamExec utor device (0): Host, Default Version 2020-06-05 20:48:00.127601: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1102] Devic e interconnect StreamExecutor with strength 1 edge matrix: 2020-06-05 20:48:00.133423: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1108] C:\Users\tunnel\AppData\Local\Programs\Python\Python38\lib\site-packages\keras_preprocessi ng\image\utils.py:107: UserWarning: grayscale is deprecated. Please use color_mode = "gray scale" warnings.warn('grayscale is deprecated. Please use ' Traceback (most recent call last): File "C:\Users\tunnel\Desktop\script_file\200605-2_mnisttest_new\yosoku.py", line 30, in <module> features = model.predict(X) File "C:\Users\tunnel\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\eng ine\training.py", line 1441, in predict x, _, _ = self._standardize_user_data(x) File "C:\Users\tunnel\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\eng ine\training.py", line 574, in _standardize_user_data x = training_utils.standardize_input_data( File "C:\Users\tunnel\AppData\Local\Programs\Python\Python38\lib\site-packages\keras\eng ine\training_utils.py", line 131, in standardize_input_data raise ValueError( ValueError: Error when checking input: expected dense_1_input to have 2 dimensions, but go t array with shape (1, 28, 28, 1) C:\Users\tunnel\Desktop\script_file\200605-2_mnisttest_new>

該当のソースコード

python3.8

1【学習モデル】(コメントは勉強用なので無視してください) 2 3# encoding: utf-8 4import urllib.request 5proxy_support = urllib.request.ProxyHandler({'http': '-----------', 6 'https':'-----------'}) 7opener = urllib.request.build_opener(proxy_support) 8urllib.request.install_opener(opener) 9 10 11from keras.datasets import mnist 12from keras.models import Sequential 13from keras.layers.core import Dense, Activation 14from keras.utils import np_utils 15 16# kerasのMNISTデータの取得 17 18(X_train, y_train), (X_test, y_test) = mnist.load_data() 19 20 21# 配列の整形と,色の範囲を0-255 -> 0-1に変換 22X_train = X_train.reshape(60000, 784) / 255 23X_test = X_test.reshape(10000, 784) / 255 24 25 26# 正解ラベルをダミー変数に変換 27y_train = np_utils.to_categorical(y_train) 28y_test = np_utils.to_categorical(y_test) 29 30# ネットワークの定義 31 32model = Sequential([ 33 Dense(512, input_shape=(784,)), 34 Activation('sigmoid'), 35 Dense(10), 36 Activation('softmax') 37 ]) 38 39# 損失関数,最適化アルゴリズムなどの設定 + モデルのコンパイルを行う 40model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy']) 41 42# 学習処理の実行 -> 変数histに進捗の情報が格納される 43# validation_split=0.1 ---> 0.1(10%)の訓練データが交差検証に使われる 44hist = model.fit(X_train, y_train, batch_size=200, verbose=1, epochs=5, validation_split=0.1) 45 46# 予測 47score = model.evaluate(X_test, y_test, verbose=1) 48print("") 49print('test accuracy : ', score[1]) 50 51model.save('mnist_model.h5') 52 53#ここからlossの設定 54import matplotlib.pyplot as plt 55loss = hist.history['loss'] 56val_loss = hist.history['val_loss'] 57 58# lossのグラフを作る 59plt.plot(range(3), loss, marker='.', label='loss') 60plt.plot(range(3), val_loss, marker='.', label='val_loss') 61plt.legend(loc='best', fontsize=10) 62plt.grid() 63plt.xlabel('epoch') 64plt.ylabel('loss') 65plt.savefig('figure_loss4.png') #savefigをplt.show()のあとに入れると、保存された画像が真っ白(なぜ??) 66plt.show() #ここを使えば、表示してくれるはず 67 68#ここまでlossのコード 69 70 71#ここからaccuracyの設定 72acc = hist.history['accuracy'] #acc にすると key errorになるので、accuracyにする 73val_acc = hist.history['val_accuracy'] 74 75# accuracyのグラフを作る 76plt.plot(range(3), acc, marker='.', label='acc') 77plt.plot(range(3), val_acc, marker='.', label='val_acc') 78plt.legend(loc='best', fontsize=10) 79plt.grid() 80plt.xlabel('epoch') 81plt.ylabel('acc') 82plt.savefig('figure_acc.png')#savefigをplt.show()のあとに入れると、保存された画像が真っ白(なぜ??) 83plt.show() #ここを使えば表示してくれる。 84 85#ここまでがaccuracy 86 87 88 89 90#ネットワークを可視化するコード 91from keras.utils import plot_model 92plot_model(model, to_file='./model.png') 93#pngでフォルダ内にはきだしてくれる 94 95 96【手書き文字の判別用】 97# coding:utf-8 98 99import keras 100import numpy as np 101from keras.models import load_model 102from keras.preprocessing.image import array_to_img, img_to_array,load_img 103import os 104import re 105 106model = load_model('mnist_model.h5') 107 108def list_pictures(directory, ext='jpg|jpeg|bmp|png|ppm'): 109 return [os.path.join(root, f) 110 for root, _, files in os.walk(directory) for f in files 111 if re.match(r'([\w]+.(?:' + ext + '))', f.lower())] 112 113for picture in list_pictures('./tegaki/'): 114 X = [] 115 img = img_to_array( 116 load_img(picture, target_size=(28, 28), grayscale=True)) 117 X.append(img) 118 119 X = np.asarray(X) 120 X = X.astype('float32') 121 X = X / 255.0 122 123 features = model.predict(X) 124 125 print('----------') 126 print(picture) 127 print(features.argmax()) 128 print('----------') 129 130 131 132

試したこと

ここに問題に対して試したことを記載してください。

補足情報(FW/ツールのバージョンなど)

ここにより詳細な情報を記載してください。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

meg_

2020/06/05 11:34

エラーはどこで出ていますか? エラーメッセージは省略せずに全部載せてください。(ユーザー名等は隠してもれって結構です)
Kkeguri

2020/06/05 11:54

コメントありがとうございます。初めてで慣れておらず、大変失礼しました。
guest

回答1

0

ベストアンサー

Xのshapeを学習データのshape(784(28*28))と同じにすれば良いかと思います。

投稿2020/06/05 12:19

meg_

総合スコア10577

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

Kkeguri

2020/06/05 12:25

ご回答ありがとうございます。 「Xのshape」というのは具体的にどの部分をさしているのでしょうか?(どの部分をどのように書き換えればよいのでしょうか?) 申し訳ありませんが、ご教示いただけますと幸いです。
meg_

2020/06/05 13:34

X_train = X_train.reshape(60000, 784) / 255 と同様に、X = X.reshape(-1, 784) / 255で良いのではないでしょうか?
Kkeguri

2020/06/07 22:47

返信が遅くなり申し訳ありません。 下記のように修正したところ、問題なく動きました。 ありがとうございました。 # coding:utf-8 import keras import numpy as np from keras.models import load_model from keras.preprocessing.image import array_to_img, img_to_array,load_img import os import re def list_pictures(directory, ext='jpg|jpeg|bmp|png|ppm'): return [os.path.join(root, f) for root, _, files in os.walk(directory) for f in files if re.match(r'([\w]+.(?:' + ext + '))', f.lower())] model = load_model('mnist_model.h5') for picture in list_pictures(r'C:\Users\tunnel\Desktop\script_file\200605-2_mnisttest_new\tegaki'): X = [] img = img_to_array( load_img(picture, target_size=(28, 28), grayscale=True))#画像を28x28かつグレースケールで読み込む(これはPIL形式) X.append(img)#Xのリストの最後にimgを追加する #img_to_arrayでOIL形式からndarray形式に変換する(3次元?) X = np.asarray(X)#Xをnmpy配列に変換する X = X.astype('float32') X = X.reshape(-1,784) / 255.0 features = model.predict(X) print('----------') print(picture) print(features.argmax()) print('----------')
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問