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

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

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

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

機械学習

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

Python

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

Q&A

解決済

1回答

2564閲覧

入力データの読み込みのエラー(Keras)

FALLOT

総合スコア16

Keras

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

機械学習

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

Python

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

0グッド

0クリップ

投稿2018/06/27 09:39

識別(りんごとオレンジ)https://qiita.com/hiroeorz@github/items/ecb39ed4042ebdc0a957

上記のプログラム参考にしてRGBではなくグレースケールに変換して読み込もうとしました。

しかし、
alueError: Error when checking input: expected dense_1_input to have 2 dimensios, but got array with shape (612, 1, 360000)
というエラーが出ました。
612は訓練データの数・1は1次元配列?・360000は一枚の画像の総ピクセル数だと思われます。

python

1image =np.reshape(image, (1,360000))

これを変換してからエラーが出たのこれが原因だと思います。。。
ちなみに、グレースケールの画像の読み込みは出来ていました。

以下にソースを載せているのでおかしい所を教えてください。
宜しくお願い致します。

python

1 2from keras.models import Sequential 3from keras.layers import Activation, Dense, Dropout 4from keras.utils.np_utils import to_categorical 5from keras.optimizers import Adagrad 6from keras.optimizers import Adam 7import numpy as np 8from PIL import Image 9import os 10 11# 学習用のデータを作る. 12image_list = [] 13label_list = [] 14 15# ./data/train 以下のorange,appleディレクトリ以下の画像を読み込む。 16for dir in os.listdir("data/train"): 17 if dir == ".DS_Store": 18 continue 19 20 dir1 = "data/train/" + dir 21 label = 0 22 23 if dir == "a": # appleはラベル0 24 label = 0 25 elif dir == "b": # orangeはラベル1 26 label = 1 27 28 for file in os.listdir(dir1): 29 if file != ".DS_Store": 30 # 配列label_listに正解ラベルを追加(りんご:0 オレンジ:1) 31 label_list.append(label) 32 filepath = dir1 + "/" + file 33 # 画像を25x25pixelに変換し、1要素が[R,G,B]3要素を含む配列の25x25の2次元配列として読み込む。 34 # [R,G,B]はそれぞれが0-255の配列。 35 image = np.array(Image.open(filepath).resize((600, 600))) 36 print(image.shape) 37 print(filepath) 38 image =np.reshape(image, (1,360000)) 39 print(image.shape) 40 print('\n') 41 # 出来上がった配列をimage_listに追加。 42 image_list.append(image / 255.) 43 44# kerasに渡すためにnumpy配列に変換。 45image_list = np.array(image_list) 46 47# ラベルの配列を1と0からなるラベル配列に変更 48# 0 -> [1,0], 1 -> [0,1] という感じ。 49Y = to_categorical(label_list) 50 51# モデルを生成してニューラルネットを構築 52model = Sequential() 53 54model.add(Dense(32, input_dim=360000)) 55model.add(Activation("relu")) 56model.add(Dropout(0.8)) 57 58model.add(Dense(1500)) 59model.add(Activation("relu")) 60model.add(Dropout(0.8)) 61 62 63model.add(Dense(1000)) 64model.add(Activation("relu")) 65model.add(Dropout(0.8)) 66 67model.add(Dense(500)) 68model.add(Activation("relu")) 69model.add(Dropout(0.8)) 70 71 72 73model.add(Dense(2)) 74model.add(Activation("softmax")) 75 76# オプティマイザにAdamを使用 77opt = Adam(lr=0.001) 78# モデルをコンパイル 79model.compile(loss="categorical_crossentropy", optimizer=opt, metrics=["accuracy"]) 80# 学習を実行。10%はテストに使用。 81model.fit(image_list, Y, nb_epoch=100, batch_size=100, validation_split=0.1) 82 83# テスト用ディレクトリ(./data/train/)の画像でチェック。正解率を表示する。 84total = 0. 85ok_count = 0. 86 87for dir in os.listdir("data/train"): 88 if dir == ".DS_Store": 89 continue 90 91 dir1 = "data/test/" + dir 92 label = 0 93 94 if dir == "a": 95 label = 0 96 elif dir == "b": 97 label = 1 98 99 for file in os.listdir(dir1): 100 if file != ".DS_Store": 101 label_list.append(label) 102 filepath = dir1 + "/" + file 103 image = np.array(Image.open(filepath).resize((600, 600))) 104 print(filepath) 105 #image = image.transpose(2, 0, 1) 106 #image = image.reshape(1, image.shape[0] * image.shape[1] * image.shape[2]).astype("float32")[0] 107 #iamge = image.reshape(1,360000).astype("float32")[0] 108 image =np.reshape(image, (1,360000)) 109 110 result = model.predict_classes(np.array([image / 255.])) 111 print("label:", label, "result:", result[0]) 112 113 total += 1. 114 115 if label == result[0]: 116 ok_count += 1. 117 118print("seikai: ", ok_count / total * 100, "%") 119

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

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

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

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

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

guest

回答1

0

ベストアンサー

こうですかね

python

1from keras.models import Sequential 2from keras.layers import Activation, Dense, Dropout 3from keras.utils.np_utils import to_categorical 4from keras.optimizers import Adagrad 5from keras.optimizers import Adam 6import numpy as np 7from PIL import Image 8import os 9 10# 学習用のデータを作る. 11image_list = [] 12label_list = [] 13 14# ./data/train 以下のorange,appleディレクトリ以下の画像を読み込む。 15for dir in os.listdir("data/train"): 16 if dir == ".DS_Store": 17 continue 18 19 dir1 = "data/train/" + dir 20 label = 0 21 22 if dir == "a": # appleはラベル0 23 label = 0 24 elif dir == "b": # orangeはラベル1 25 label = 1 26 27 for file in os.listdir(dir1): 28 if file != ".DS_Store": 29 # 配列label_listに正解ラベルを追加(りんご:0 オレンジ:1) 30 label_list.append(label) 31 filepath = dir1 + "/" + file 32 # 画像を25x25pixelに変換し、1要素が[R,G,B]3要素を含む配列の25x25の2次元配列として読み込む。 33 # [R,G,B]はそれぞれが0-255の配列。 34 image = np.array(Image.open(filepath).resize((600, 600))) 35 print(image.shape) 36 print(filepath) 37 image =np.reshape(image, 360000) 38 print(image.shape) 39 print('\n') 40 # 出来上がった配列をimage_listに追加。 41 image_list.append(image / 255.) 42 43# kerasに渡すためにnumpy配列に変換。 44image_list = np.array(image_list) 45 46# ラベルの配列を1と0からなるラベル配列に変更 47# 0 -> [1,0], 1 -> [0,1] という感じ。 48Y = to_categorical(label_list) 49 50# モデルを生成してニューラルネットを構築 51model = Sequential() 52 53model.add(Dense(32, input_dim=360000)) 54model.add(Activation("relu")) 55model.add(Dropout(0.8)) 56 57model.add(Dense(1500)) 58model.add(Activation("relu")) 59model.add(Dropout(0.8)) 60 61 62model.add(Dense(1000)) 63model.add(Activation("relu")) 64model.add(Dropout(0.8)) 65 66model.add(Dense(500)) 67model.add(Activation("relu")) 68model.add(Dropout(0.8)) 69 70 71 72model.add(Dense(2)) 73model.add(Activation("softmax")) 74 75# オプティマイザにAdamを使用 76opt = Adam(lr=0.001) 77# モデルをコンパイル 78model.compile(loss="categorical_crossentropy", optimizer=opt, metrics=["accuracy"]) 79# 学習を実行。10%はテストに使用。 80model.fit(image_list, Y, nb_epoch=100, batch_size=100, validation_split=0.1) 81 82# テスト用ディレクトリ(./data/train/)の画像でチェック。正解率を表示する。 83total = 0. 84ok_count = 0. 85 86for dir in os.listdir("data/train"): 87 if dir == ".DS_Store": 88 continue 89 90 dir1 = "data/test/" + dir 91 label = 0 92 93 if dir == "a": 94 label = 0 95 elif dir == "b": 96 label = 1 97 98 for file in os.listdir(dir1): 99 if file != ".DS_Store": 100 label_list.append(label) 101 filepath = dir1 + "/" + file 102 image = np.array(Image.open(filepath).resize((600, 600))) 103 print(filepath) 104 #image = image.transpose(2, 0, 1) 105 #image = image.reshape(1, image.shape[0] * image.shape[1] * image.shape[2]).astype("float32")[0] 106 #iamge = image.reshape(1,360000).astype("float32")[0] 107 image =np.reshape(image, 360000) 108 109 result = model.predict_classes(np.array([image / 255.])) 110 print("label:", label, "result:", result[0]) 111 112 total += 1. 113 114 if label == result[0]: 115 ok_count += 1. 116 117print("seikai: ", ok_count / total * 100, "%")

投稿2018/06/27 10:51

wakame

総合スコア1170

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

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

FALLOT

2018/06/28 01:58

ありがとうございます! image =np.reshape(image, 360000) の書き方が間違っていたということですね。 助かりました!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.47%

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

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

質問する

関連した質問