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

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

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

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

深層学習

深層学習は、多数のレイヤのニューラルネットワークによる機械学習手法。人工知能研究の一つでディープラーニングとも呼ばれています。コンピューター自体がデータの潜在的な特徴を汲み取り、効率的で的確な判断を実現することができます。

強化学習

強化学習とは、ある環境下のエージェントが現状を推測し行動を決定することで報酬を獲得するという見解から、その報酬を最大限に得る方策を学ぶ機械学習のことを指します。問題解決時に得る報酬が選択結果によって変化することで、より良い行動を選択しようと学習する点が特徴です。

機械学習

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

Q&A

1回答

937閲覧

自作画像分類器の画像読み込み時のエラーについて

_mini

総合スコア15

Keras

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

深層学習

深層学習は、多数のレイヤのニューラルネットワークによる機械学習手法。人工知能研究の一つでディープラーニングとも呼ばれています。コンピューター自体がデータの潜在的な特徴を汲み取り、効率的で的確な判断を実現することができます。

強化学習

強化学習とは、ある環境下のエージェントが現状を推測し行動を決定することで報酬を獲得するという見解から、その報酬を最大限に得る方策を学ぶ機械学習のことを指します。問題解決時に得る報酬が選択結果によって変化することで、より良い行動を選択しようと学習する点が特徴です。

機械学習

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

0グッド

0クリップ

投稿2020/07/21 04:35

編集2022/01/12 10:55

sumple_cnn_classification.pyとpredict.pyというコードを書き、学習とそれによる二種類の画像の判別を行うプログラム
を作ったのですが、エラーが出てしまってうまく動きません。
sumple_cnn_classification.pyはうまく動いているので、predict.pyのコードが間違っていると思います。predict.pyを制作する際に参考にしたサイトはこちらです。
Kerasによる、ものすごくシンプルな画像分類(りんごとオレンジ)

ファイルの階層
イメージ説明

predict.py

from keras.models import Sequential from keras.layers import Activation, Dense, Dropout from keras.utils.np_utils import to_categorical from keras.optimizers import Adagrad from keras.optimizers import Adam import numpy as np from PIL import Image import os # 学習用のデータを作る. image_list = [] label_list = [] # ./data/train 以下のorange,appleディレクトリ以下の画像を読み込む。 for dir in os.listdir("data/train"): if dir == ".DS_Store": continue dir1 = "data/train/" + dir label = 0 if dir == "次郎": # appleはラベル0 label = 0 elif dir == "次郎ではない": # orangeはラベル1 label = 1 for file in os.listdir(dir1): if file != ".DS_Store": # 配列label_listに正解ラベルを追加(りんご:0 オレンジ:1) label_list.append(label) filepath = dir1 + "/" + file # 画像を25x25pixelに変換し、1要素が[R,G,B]3要素を含む配列の25x25の2次元配列として読み込む。 # [R,G,B]はそれぞれが0-255の配列。 image = np.array(Image.open(filepath).resize((25, 25))) print(filepath) # 配列を変換し、[[Redの配列],[Greenの配列],[Blueの配列]] のような形にする。 image = image.transpose(2, 0, 1) # さらにフラットな1次元配列に変換。最初の1/3はRed、次がGreenの、最後がBlueの要素がフラットに並ぶ。 image = image.reshape( 1, image.shape[0] * image.shape[1] * image.shape[2]).astype("float32")[0] # 出来上がった配列をimage_listに追加。 image_list.append(image / 255.) # kerasに渡すためにnumpy配列に変換。 image_list = np.array(image_list) # ラベルの配列を1と0からなるラベル配列に変更 # 0 -> [1,0], 1 -> [0,1] という感じ。 Y = to_categorical(label_list) # モデルを生成してニューラルネットを構築 model = Sequential() model.add(Dense(200, input_dim=1875)) model.add(Activation("relu")) model.add(Dropout(0.2)) model.add(Dense(200)) model.add(Activation("relu")) model.add(Dropout(0.2)) model.add(Dense(2)) model.add(Activation("softmax")) # オプティマイザにAdamを使用 opt = Adam(lr=0.001) # モデルをコンパイル model.compile(loss="categorical_crossentropy", optimizer=opt, metrics=["accuracy"]) # 学習を実行。10%はテストに使用。 model.fit(image_list, Y, nb_epoch=1500, batch_size=100, validation_split=0.1) # テスト用ディレクトリ(./data/train/)の画像でチェック。正解率を表示する。 total = 0. ok_count = 0. for dir in os.listdir("data/train"): if dir == ".DS_Store": continue dir1 = "data/jirou-test/" + dir label = 0 if dir == "次郎": label = 0 elif dir == "次郎ではない": label = 1 for file in os.listdir(dir1): if file != ".DS_Store": label_list.append(label) filepath = dir1 + "/" + file image = np.array(Image.open(filepath).resize((25, 25))) print(filepath) image = image.transpose(2, 0, 1) image = image.reshape( 1, image.shape[0] * image.shape[1] * image.shape[2]).astype("float32")[0] result = model.predict_classes(np.array([image / 255.])) print("label:", label, "result:", result[0]) total += 1. if label == result[0]: ok_count += 1. print("正解率: ", ok_count / total * 100, "%")

エラー文

(base) xxxx@xxxx image-classfication-jiro % /opt/anaconda3/bin/python /Users/xxxx/Downloads/image-classfication-jiro/predict.py Using TensorFlow backend. /opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)]) /opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint8 = np.dtype([("quint8", np.uint8, 1)]) /opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint16 = np.dtype([("qint16", np.int16, 1)]) /opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint16 = np.dtype([("quint16", np.uint16, 1)]) /opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint32 = np.dtype([("qint32", np.int32, 1)]) /opt/anaconda3/lib/python3.7/site-packages/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. np_resource = np.dtype([("resource", np.ubyte, 1)]) /opt/anaconda3/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)]) /opt/anaconda3/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint8 = np.dtype([("quint8", np.uint8, 1)]) /opt/anaconda3/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint16 = np.dtype([("qint16", np.int16, 1)]) /opt/anaconda3/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_quint16 = np.dtype([("quint16", np.uint16, 1)]) /opt/anaconda3/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint32 = np.dtype([("qint32", np.int32, 1)]) /opt/anaconda3/lib/python3.7/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. np_resource = np.dtype([("resource", np.ubyte, 1)]) data/train/not-jiro/images-3.jpeg ・・・・ data/train/jiro/hJLxemaOWndtlpzjbdVroI0DTL91CFuP.jpg data/train/jiro/image.jpg data/train/jiro/XHjnENbJCUCB3Xr7skOdOuq9Aoec7mlt.jpg /Users/xxxx/Downloads/image-classfication-jiro/predict.py:70: UserWarning: The `nb_epoch` argument in `fit` has been renamed `epochs`. model.fit(image_list, Y, nb_epoch=1500, batch_size=100, validation_split=0.1) Traceback (most recent call last): File "/Users/xxxxx/Downloads/image-classfication-jiro/predict.py", line 70, in <module> model.fit(image_list, Y, nb_epoch=1500, batch_size=100, validation_split=0.1) File "/opt/anaconda3/lib/python3.7/site-packages/keras/engine/training.py", line 1154, in fit batch_size=batch_size) File "/opt/anaconda3/lib/python3.7/site-packages/keras/engine/training.py", line 621, in _standardize_user_data exception_prefix='target') File "/opt/anaconda3/lib/python3.7/site-packages/keras/engine/training_utils.py", line 145, in standardize_input_data str(data_shape)) ValueError: Error when checking target: expected activation_3 to have shape (2,) but got array with shape (1,)

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

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

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

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

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

can110

2020/07/21 05:16

文字数制限にひっかかるのであれば、むしろ「predict.py」のほうを全文提示ください。
_mini

2020/07/21 05:28

エラー文はどの部分が必要ですか?
can110

2020/07/21 05:32

エラーは全文(Traceback)提示したほうがよいです。
_mini

2020/07/21 05:41

ではsumple_cnn_classificationの方を消してしまってよいということでしょうか?
can110

2020/07/21 06:04

実際にエラーの発生するソースのほうが重要だと考えての提案です。
_mini

2020/07/21 06:07

predict.pyの方を全文載せ、sumple_...は一旦消させていただきました。 sumple_... の方のコードが必要であれば、私の過去の質問にも載せてあります。
guest

回答1

0

ValueError: Error when checking target: expected activation_3 to have shape (2,) but got array with shape (1,)

ということは
activationの3番目つまり

model.add(Dense(2)) model.add(Activation("softmax"))

のあたりでエラーが発生しているということなので。
エラーをよく見ると
形状(1,)の配列を取得したとなっているので。
このブログラムの画像のラベル付がエラーの発生源だと思います。

if dir == "次郎": label = 0 elif dir == "次郎ではない": label = 1

の部分を

if dir == "次郎": label = 1 elif dir == "次郎ではない": label = 2

とすることによってエラーが解決すると思います。

投稿2020/07/25 05:57

mi.dai.tomo

総合スコア40

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

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

_mini

2020/07/25 15:22

回答ありがとうございます。 ラベル付けを1,2に変更してみましたが、同じエラーが出て実行できませんでした。 コードを記入している際に、「 image = image.reshape( 1, image.shape[0] * image.shape[1] * image.shape[2]).astype("float32")[0]」このコードのimageの部分に赤波線が表示され、問題であるというようにvscodeのエディタ側から指摘されるのですが、これもなにか関係があるのでしょうか?
mi.dai.tomo

2020/07/25 23:45

自分はこの方法で解決したんで、多分この方法であっています 1つ思ったことは下のラベル付の部分だけしか変更していないからこのようなエラーが発生していて 上のラベル付の部分を変更していないからかもしれません。
Q71

2020/07/26 01:34

ラベルが0,1か1,2か、ということではなく、[1,0]か[0,1]か、ではなかろうか。
_mini

2020/07/26 02:58

mi.dai,tomo様 2つともラベルを1,2に変更してみましたが、解決していません… Q71様 [1,0]か[0,1]というのはどの部分でしょうか? ラベルの問題でしたら解決していないので…
Q71

2020/07/26 10:02

3番目のactivationに渡るのは model.add(Dense(2)) なので、これが出力するshapeである(2,)と同じshapeを設定してください。 softmax は引き渡された配列を全部足すと1になる様に整えます。よって、1または2を渡す、というのはあり得ません。「0又は1」を、「[1,0]又は[0,1]」にします。「クラス0である確率が100%でクラス1である確率が0%」又は「クラス0である確率が0%でクラス1である確率が100%」です。
_mini

2020/07/27 02:49

ということは次郎か次郎ではないにラベル付けされるのは0か1ということですよね。 image.shapeの部分が間違っているのでしょうか…
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

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

ただいまの回答率
85.50%

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

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

質問する

関連した質問