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

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

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

NumPyはPythonのプログラミング言語の科学的と数学的なコンピューティングに関する拡張モジュールです。

OpenCV

OpenCV(オープンソースコンピュータービジョン)は、1999年にインテルが開発・公開したオープンソースのコンピュータビジョン向けのクロスプラットフォームライブラリです。

機械学習

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

Python

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

Q&A

解決済

1回答

800閲覧

CNNモデルを使って画像分類をして新しい画像の予測ラベルを表示させたい

koukimaru22

総合スコア6

NumPy

NumPyはPythonのプログラミング言語の科学的と数学的なコンピューティングに関する拡張モジュールです。

OpenCV

OpenCV(オープンソースコンピュータービジョン)は、1999年にインテルが開発・公開したオープンソースのコンピュータビジョン向けのクロスプラットフォームライブラリです。

機械学習

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

Python

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

0グッド

0クリップ

投稿2019/11/27 08:25

前提・実現したいこと

0と1の二つのラベル画像分類をしています。そのモデルを使用して新しい画像の予測ラベルを表示させたいのですがエラー文に詰まって意味が分からないので教えてほしいです

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

Depth of input (1) is not a multiple of input depth of filter (3) for 'conv1_1/Conv2D' (op: 'Conv2D') with input shapes: [?,28,28,1], [5,5,3,32].

該当のソースコード

python

1ValueError Traceback (most recent call last) 2<ipython-input-6-3673e8a03bd8> in <module> 3 96 keep_prob = tf.placeholder("float") 4 97 5---> 98 logits = interence(x_image, keep_prob) 6 99 sess = tf.InteractiveSession() 7 100 8 9<ipython-input-6-3673e8a03bd8> in interence(imegs_placeholder, keep_prob) 10 46 W_conv1 = weight_variable([5, 5, 3, 32]) 11 47 b_conv1 = bias_variable([32]) 12---> 48 h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) 13 49 14 50 # プーリング層1の作成 15 16<ipython-input-6-3673e8a03bd8> in conv2d(x, W) 17 33 # 畳み込み層 18 34 def conv2d(x, W): 19---> 35 return tf.nn.conv2d(x, W, strides=[1,1,1,1], padding="SAME") 20 36 21 37 # プーリング層

CNNモデル

import sys import cv2 import numpy as np import tensorflow as tf import tensorflow.python.platform import os import matplotlib.pyplot as plt NUM_CLASSES = 2 IMAGE_SIZE = 28 IMAGE_PIXELS = IMAGE_SIZE*IMAGE_SIZE*3 flags = tf.app.flags FLAGS = flags.FLAGS tf.app.flags.DEFINE_string('f', '', 'kernel') flags.DEFINE_string('train', 'train.txt', 'File name of train data') flags.DEFINE_string('test', 'test.txt', 'File name of train data') flags.DEFINE_string('train_dir', '/tmp/data', 'Directory to put the training data.') flags.DEFINE_integer('max_steps', 200, 'Number of steps to run trainer.') flags.DEFINE_integer('batch_size', 64, 'Batch size' 'Must divide evenly into the dataset sizes.') flags.DEFINE_float('learning_rate', 1e-4, 'Initial learning rate.') def inference(images_placeholder, keep_prob): """ 予測モデルを作成する関数 引数: images_placeholder: 画像のplaceholder keep_prob: dropout率のplace_holder 返り値: y_conv: 各クラスの確率(のようなもの) """ # 重みを標準偏差0.1の正規分布で初期化 def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) # バイアスを標準偏差0.1の正規分布で初期化 def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) # 畳み込み層の作成 def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') # プーリング層の作成 def max_pool_2x2(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') # 入力を28x28x3に変形 x_image = tf.reshape(images_placeholder, [-1, 28, 28, 3]) # 畳み込み層1の作成 with tf.name_scope('conv1') as scope: W_conv1 = weight_variable([5, 5, 3, 32]) b_conv1 = bias_variable([32]) h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) # プーリング層1の作成 with tf.name_scope('pool1') as scope: h_pool1 = max_pool_2x2(h_conv1) # 畳み込み層2の作成 with tf.name_scope('conv2') as scope: W_conv2 = weight_variable([5, 5, 32, 64]) b_conv2 = bias_variable([64]) h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) # プーリング層2の作成 with tf.name_scope('pool2') as scope: h_pool2 = max_pool_2x2(h_conv2) # 全結合層1の作成 with tf.name_scope('fc1') as scope: W_fc1 = weight_variable([7*7*64, 1024]) b_fc1 = bias_variable([1024]) h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) # dropoutの設定 h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) # 全結合層2の作成 with tf.name_scope('fc2') as scope: W_fc2 = weight_variable([1024, NUM_CLASSES]) b_fc2 = bias_variable([NUM_CLASSES]) # ソフトマックス関数による正規化 with tf.name_scope('softmax') as scope: y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) # 各ラベルの確率のようなものを返す return y_conv def loss(logits, labels): """ lossを計算する関数 引数: logits: ロジットのtensor, float - [batch_size, NUM_CLASSES] labels: ラベルのtensor, int32 - [batch_size, NUM_CLASSES] 返り値: cross_entropy: 交差エントロピーのtensor, float """ # 交差エントロピーの計算 cross_entropy = -tf.reduce_sum(labels*tf.log(logits)) # TensorBoardで表示するよう指定 tf.summary.scalar("cross_entropy", cross_entropy) return cross_entropy def training(loss, learning_rate): """ 訓練のOpを定義する関数 引数: loss: 損失のtensor, loss()の結果 learning_rate: 学習係数 返り値: train_step: 訓練のOp """ train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss) return train_step def accuracy(logits, labels): """ 正解率(accuracy)を計算する関数 引数: logits: inference()の結果 labels: ラベルのtensor, int32 - [batch_size, NUM_CLASSES] 返り値: accuracy: 正解率(float) """ correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(labels, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) tf.summary.scalar("accuracy", accuracy) return accuracy if __name__ == '__main__': # ファイルを開く f = open('train/train.txt') # データを入れる配列 train_image = [] train_label = [] for line in f: # 改行を除いてスペース区切りにする line = line.rstrip() l = line.split() # データを読み込んで28x28に縮小 img = cv2.imread('train/'+l[0]) img = cv2.resize(img, (28, 28)) # 一列にした後、0-1のfloat値にする train_image.append(img.flatten().astype(np.float32)/255.0) # ラベルを1-of-k方式で用意する tmp = np.zeros(NUM_CLASSES) tmp[int(l[1])] = 1 train_label.append(tmp) # numpy形式に変換 train_image = np.asarray(train_image) train_label = np.asarray(train_label) f.close() f = open('test/test.txt') test_image = [] test_label = [] for line in f: line = line.rstrip() l = line.split() img = cv2.imread('test/'+l[0]) img = cv2.resize(img, (28, 28)) test_image.append(img.flatten().astype(np.float32)/255.0) tmp = np.zeros(NUM_CLASSES) tmp[int(l[1])] = 1 test_label.append(tmp) test_image = np.asarray(test_image) test_label = np.asarray(test_label) f.close() with tf.Graph().as_default(): # 画像を入れる仮のTensor images_placeholder = tf.placeholder("float", shape=(None, IMAGE_PIXELS)) # ラベルを入れる仮のTensor labels_placeholder = tf.placeholder("float", shape=(None, NUM_CLASSES)) # dropout率を入れる仮のTensor keep_prob = tf.placeholder("float") # inference()を呼び出してモデルを作る logits = inference(images_placeholder, keep_prob) # loss()を呼び出して損失を計算 loss_value = loss(logits, labels_placeholder) # training()を呼び出して訓練 train_op = training(loss_value, FLAGS.learning_rate) # 精度の計算 acc = accuracy(logits, labels_placeholder) prec = precision(logits, labels_placeholder) # 保存の準備 saver = tf.train.Saver() # Sessionの作成 sess = tf.Session() # 変数の初期化 sess.run(tf.initialize_all_variables()) # 訓練の実行 if len(train_image) % FLAGS.batch_size is 0: train_batch = len(train_image)/FLAGS.batch_size else: train_batch = int((len(train_image)/FLAGS.batch_size)+1) shuffle_idx = np.arange(len(train_label)) for step in range(FLAGS.max_steps): np.random.shuffle(shuffle_idx) for i in range(train_batch): # batch_size分の画像に対して訓練の実行 batch = FLAGS.batch_size*i batch_idx = shuffle_idx[batch:batch+FLAGS.batch_size] # feed_dictでplaceholderに入れるデータを指定する sess.run(train_op, feed_dict={ images_placeholder: train_image[batch_idx], labels_placeholder: train_label[batch_idx], keep_prob: 1.0}) # 1 step終わるたびに精度を計算する train_accuracy = sess.run(acc, feed_dict={ images_placeholder: train_image, labels_placeholder: train_label, keep_prob: 1.0}) print(step, train_accuracy) # 訓練が終了したらテストデータに対する精度を表示 print(sess.run(acc, feed_dict={ images_placeholder: test_image, labels_placeholder: test_label, keep_prob: 1.0})) # 最終的なモデルを保存 save_path = saver.save(sess, ".\ckpt\model.ckpt")

予測ラベルを表示させたいプログラム

import tensorflow as tf import cv2 import numpy as np import os NUM_CLASSES = 2 def interence(imegs_placeholder, keep_prob): --中略-- return y_conv if __name__ == "__main__": print(os.getcwd()) # 画像読み込み img = input("画像パスを入力してください >") img = cv2.imread(img, cv2.IMREAD_GRAYSCALE) img = cv2.resize(img, (28, 28)) ximage = img.flatten().astype(np.float32)/255.0 #形式を変更 # 式に用いる変数設定 x_image = tf.placeholder("float", shape=[None, 784]) # 入力 y_label = tf.placeholder("float", shape=[None, 2]) keep_prob = tf.placeholder("float") logits = interence(x_image, keep_prob) sess = tf.InteractiveSession() saver = tf.train.Saver() sess.run(tf.global_variables_initializer()) ckpt = tf.train.get_checkpoint_state('./ckpt') saver.restore(sess, ckpt.model_checkpoint_path) # 変数データの読み込み pred = np.argmax(logits.eval(feed_dict={x_image: [ximage], keep_prob: 1.0})[0]) print(pred) 入力 C:\Users\koukioki\Desktop\isu_oki 画像パスを入力してください >./syorigo/1.jpg

試したこと

自分なりにで調べてもいまいちわからなかったので教えてください

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

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

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

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

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

guest

回答1

0

ベストアンサー

x_image = tf.reshape(images_placeholder, [-1, 28, 28, 3]
とありますが、 x_image.shapeを教えてください。
配列の1次元部分がデータ数になってますか?

投稿2019/11/27 11:24

surphy

総合スコア101

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

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

koukimaru22

2019/11/27 11:29

今言われたところを確認すると1次元になっていました。 違うとこから複合して書いていたので間違っていました。 3次元にするとうまくいきました。 ありがとうございます。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問