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

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

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

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Python

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

Q&A

解決済

2回答

593閲覧

【CNN】画像サイズ変更時のプログラム変更箇所について

ttmm

総合スコア15

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Python

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

1グッド

0クリップ

投稿2017/12/21 01:10

下記のコードを参考にして画像サイズを変更させたものを実行させたいと思っています。

python

1#!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 import sys 4 import cv2 5 import numpy as np 6 import tensorflow as tf 7 import tensorflow.python.platform 8 9 NUM_CLASSES = 3 10 IMAGE_SIZE = 28 11 IMAGE_PIXELS = IMAGE_SIZE*IMAGE_SIZE*3 12 13 flags = tf.app.flags 14 FLAGS = flags.FLAGS 15 flags.DEFINE_string('train', 'train.txt', 'File name of train data') 16 flags.DEFINE_string('test', 'test.txt', 'File name of train data') 17 flags.DEFINE_string('train_dir', '/mnt/c/linux/data', 'Directory to put the training data.') 18 flags.DEFINE_integer('max_steps', 200, 'Number of steps to run trainer.') 19 flags.DEFINE_integer('batch_size', 10, 'Batch size' 20 'Must divide evenly into the dataset sizes.') 21 flags.DEFINE_float('learning_rate', 1e-4, 'Initial learning rate.') 22 23 def inference(images_placeholder, keep_prob): 24 """ 予測モデルを作成する関数 25 26 引数: 27 images_placeholder: 画像のplaceholder 28 keep_prob: dropout率のplace_holder 29 30 返り値: 31 y_conv: 各クラスの確率(のようなもの) 32 """ 33 # 重みを標準偏差0.1の正規分布で初期化 34 def weight_variable(shape): 35 initial = tf.truncated_normal(shape, stddev=0.1) 36 return tf.Variable(initial) 37 38 # バイアスを標準偏差0.1の正規分布で初期化 39 def bias_variable(shape): 40 initial = tf.constant(0.1, shape=shape) 41 return tf.Variable(initial) 42 43 # 畳み込み層の作成 44 def conv2d(x, W): 45 return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') 46 47 # プーリング層の作成 48 def max_pool_2x2(x): 49 return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], 50 strides=[1, 2, 2, 1], padding='SAME') 51 52 # 入力を28x28x3に変形 53 x_image = tf.reshape(images_placeholder, [-1, 28, 28, 3]) 54 55 # 畳み込み層1の作成 56 with tf.name_scope('conv1') as scope: 57 W_conv1 = weight_variable([5, 5, 3, 32]) 58 b_conv1 = bias_variable([32]) 59 h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) 60 61 # プーリング層1の作成 62 with tf.name_scope('pool1') as scope: 63 h_pool1 = max_pool_2x2(h_conv1) 64 65 # 畳み込み層2の作成 66 with tf.name_scope('conv2') as scope: 67 W_conv2 = weight_variable([5, 5, 32, 64]) 68 b_conv2 = bias_variable([64]) 69 h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) 70 71 # プーリング層2の作成 72 with tf.name_scope('pool2') as scope: 73 h_pool2 = max_pool_2x2(h_conv2) 74 75 # 全結合層1の作成 76 with tf.name_scope('fc1') as scope: 77 W_fc1 = weight_variable([7*7*64, 1024]) 78 b_fc1 = bias_variable([1024]) 79 h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) 80 h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) 81 # dropoutの設定 82 h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) 83 84 # 全結合層2の作成 85 with tf.name_scope('fc2') as scope: 86 W_fc2 = weight_variable([1024, NUM_CLASSES]) 87 b_fc2 = bias_variable([NUM_CLASSES]) 88 89 # ソフトマックス関数による正規化 90 with tf.name_scope('softmax') as scope: 91 y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) 92 93 # 各ラベルの確率のようなものを返す 94 return y_conv 95 96 def loss(logits, labels): 97 """ lossを計算する関数 98 99 引数: 100 logits: ロジットのtensor, float - [batch_size, NUM_CLASSES] 101 labels: ラベルのtensor, int32 - [batch_size, NUM_CLASSES] 102 103 返り値: 104 cross_entropy: 交差エントロピーのtensor, float 105 106 """ 107 108 # 交差エントロピーの計算 109 cross_entropy = -tf.reduce_sum(labels*tf.log(logits)) 110 # TensorBoardで表示するよう指定 111 tf.scalar_summary("cross_entropy", cross_entropy) 112 return cross_entropy 113 114 def training(loss, learning_rate): 115 """ 訓練のOpを定義する関数 116 117 引数: 118 loss: 損失のtensor, loss()の結果 119 learning_rate: 学習係数 120 121 返り値: 122 train_step: 訓練のOp 123 124 """ 125 126 train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss) 127 return train_step 128 129 def accuracy(logits, labels): 130 """ 正解率(accuracy)を計算する関数 131 132 引数: 133 logits: inference()の結果 134 labels: ラベルのtensor, int32 - [batch_size, NUM_CLASSES] 135 136 返り値: 137 accuracy: 正解率(float) 138 139 """ 140 correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(labels, 1)) 141 accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) 142 tf.scalar_summary("accuracy", accuracy) 143 return accuracy 144 145 if __name__ == '__main__': 146 # ファイルを開く 147 f = open(FLAGS.train, 'r') 148 # データを入れる配列 149 train_image = [] 150 train_label = [] 151 for line in f: 152 # 改行を除いてスペース区切りにする 153 line = line.rstrip() 154 l = line.split() 155 # データを読み込んで28x28に縮小 156 img = cv2.imread(l[0]) 157 img = cv2.resize(img, (28, 28)) 158 # 一列にした後、0-1のfloat値にする 159 train_image.append(img.flatten().astype(np.float32)/255.0) 160 # ラベルを1-of-k方式で用意する 161 tmp = np.zeros(NUM_CLASSES) 162 tmp[int(l[1])] = 1 163 train_label.append(tmp) 164 # numpy形式に変換 165 train_image = np.asarray(train_image) 166 train_label = np.asarray(train_label) 167 f.close() 168 169 f = open(FLAGS.test, 'r') 170 test_image = [] 171 test_label = [] 172 for line in f: 173 line = line.rstrip() 174 l = line.split() 175 img = cv2.imread(l[0]) 176 img = cv2.resize(img, (28, 28)) 177 test_image.append(img.flatten().astype(np.float32)/255.0) 178 tmp = np.zeros(NUM_CLASSES) 179 tmp[int(l[1])] = 1 180 test_label.append(tmp) 181 test_image = np.asarray(test_image) 182 test_label = np.asarray(test_label) 183 f.close() 184 185 with tf.Graph().as_default(): 186 # 画像を入れる仮のTensor 187 images_placeholder = tf.placeholder("float", shape=(None, IMAGE_PIXELS)) 188 # ラベルを入れる仮のTensor 189 labels_placeholder = tf.placeholder("float", shape=(None, NUM_CLASSES)) 190 # dropout率を入れる仮のTensor 191 keep_prob = tf.placeholder("float") 192 193 # inference()を呼び出してモデルを作る 194 logits = inference(images_placeholder, keep_prob) 195 # loss()を呼び出して損失を計算 196 loss_value = loss(logits, labels_placeholder) 197 # training()を呼び出して訓練 198 train_op = training(loss_value, FLAGS.learning_rate) 199 # 精度の計算 200 acc = accuracy(logits, labels_placeholder) 201 202 # 保存の準備 203 saver = tf.train.Saver() 204 # Sessionの作成 205 sess = tf.Session() 206 # 変数の初期化 207 sess.run(tf.initialize_all_variables()) 208 # TensorBoardで表示する値の設定 209 summary_op = tf.merge_all_summaries() 210 summary_writer = tf.train.SummaryWriter(FLAGS.train_dir, sess.graph_def) 211 212 # 訓練の実行 213 for step in range(FLAGS.max_steps): 214 for i in range(len(train_image)/FLAGS.batch_size): 215 # batch_size分の画像に対して訓練の実行 216 batch = FLAGS.batch_size*i 217 # feed_dictでplaceholderに入れるデータを指定する 218 sess.run(train_op, feed_dict= 219 images_placeholder: train_image[batch:batch+FLAGS.batch_size], 220 labels_placeholder: train_label[batch:batch+FLAGS.batch_size], 221 keep_prob: 0.5}) 222 223 # 1 step終わるたびに精度を計算する 224 train_accuracy = sess.run(acc, feed_dict={ 225 images_placeholder: train_image, 226 labels_placeholder: train_label, 227 keep_prob: 1.0}) 228 print "step %d, training accuracy %g"%(step, train_accuracy) 229 230 # 1 step終わるたびにTensorBoardに表示する値を追加する 231 summary_str = sess.run(summary_op, feed_dict={ 232 images_placeholder: train_image, 233 labels_placeholder: train_label, 234 keep_prob: 1.0}) 235 summary_writer.add_summary(summary_str, step) 236 237 # 訓練が終了したらテストデータに対する精度を表示 238 print "test accuracy %g"%sess.run(acc, feed_dict={ 239 images_placeholder: test_image, 240 labels_placeholder: test_label, 241 keep_prob: 1.0}) 242 243 # 最終的なモデルを保存 244 save_path = saver.save(sess, "model.ckpt")

変形している箇所は数字を変更はしました(サイズを56にしたい場合:28→56)

# 入力を28x28x3に変形 x_image = tf.reshape(images_placeholder, [-1, 28, 28, 3]) .... img = cv2.resize(img, (28, 28))

しかし下記のようなエラーが出てしまいました。

・・・ InvalidArgumentError: Incompatible shapes: [10,5] vs. [160,5] [[Node: gradients/mul_grad/BroadcastGradientArgs = BroadcastGradientArgs[T=DT_INT32, _device="/job:localhost/replica:0/task:0/device:CPU:0"](gradients/mul_grad/Shape, gradients/mul_grad/Shape_1)]] ・・・・

何となくですが全結合層の値も変える必要があると思うのですが
サイズの変化に対してどのように変えればいいかわかりません。
どなたか教えていただけると幸いです。

nagagutsu_af👍を押しています

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

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

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

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

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

guest

回答2

0

各層(主に畳み込みとプーリング)の操作によって要素数がどのように変化するのかは教科書に書いてありますし、インターネット上に豊富な情報があります。
https://teratail.com/questions/103659

それらを勉強する気がないのであれば、TensorflowではなくKerasを使うことで、煩わしさから開放されます。

他にもTensorflowのテンソルのShapeを取得するメソッド.get_shape()があるので、機械的に処理させることもできます。

投稿2017/12/21 02:58

mkgrei

総合スコア8560

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

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

ttmm

2017/12/21 03:29 編集

調べつつやって全結合層の値を(画像のサイズが28の場合⇒7,56の場合⇒14)変えてやってみても 同じようなエラーが出てしまっていたので質問させていただきました。 もう少し自分で調べてみます
mkgrei

2017/12/21 04:01

状況を把握しました。 変更後にエラーが出たコードそのものを添付していただけませんか。 またエラーの全文もできれば。
guest

0

ベストアンサー

FC 層手前の 1 次元化については、訓練部 inference に以下の関数を追加して

Python

1 def linearize(x): 2 x_shape = x.get_shape().as_list() 3 x_length = np.prod(x_shape[1:]) 4 return tf.reshape(x, [-1, x_length]), x_length

FC 層 で

Python

1 linear, linear_length = linearize(h_pool2) 2 3 with tf.name_scope('fc1') as scope: 4 W_fc1 = weight_variable([linear_length, 1024]) 5 b_fc1 = bias_variable([1024]) 6 h_fc1 = tf.nn.relu(tf.matmul(linear, W_fc1) + b_fc1) 7 h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

としておけば、畳み込み・プーリング後の画像サイズを計算する必要もありません。

投稿2017/12/21 07:00

nagagutsu_af

総合スコア32

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

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

ttmm

2017/12/21 08:41 編集

ありがとうございます。 プログラムを参考に反映した結果、動きました。 # 全結合層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) のなかの h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) の一行がいらなかったみたいです。 ありがとうございます。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問