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

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

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

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

OpenCV

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

機械学習

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

Python

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

Q&A

0回答

1150閲覧

CNNモデルを使って画像分類をして新しい画像の予測ラベルを表示させたいが学習済みモデルとのかみ合わせがうまくいかないので教えてほしいです

koukimaru22

総合スコア6

NumPy

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

OpenCV

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

機械学習

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

Python

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

0グッド

1クリップ

投稿2019/11/28 02:59

前提・実現したいこと

0と1の二つのラベル画像分類をしています。そのモデルを使用して新しい画像の予測ラベルを表示させたいのですがエラー文に詰まって意味が分からないので教えてほしいです。
モデル自体に問題があるのか保存の仕方に問題があるのかわかりません。

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

NotFoundError: Key _CHECKPOINTABLE_OBJECT_GRAPH not found in checkpoint During handling of the above exception, another exception occurred: NotFoundError Traceback (most recent call last) <ipython-input-7-ece98e557f90> in <module> 102 sess.run(tf.global_variables_initializer()) 103 ckpt = tf.train.get_checkpoint_state('./ckpt') --> 104 saver.restore(sess, ckpt.model_checkpoint_path) # 変数データの読み込み 105 106 pred = np.argmax(logits.eval(feed_dict={x_image: [ximage], keep_prob: 1.0})[0]) NotFoundError: Restoring from checkpoint failed. This is most likely due to a Variable name or other graph key that is missing from the checkpoint. Please ensure that you have not altered the graph expected based on the checkpoint. Original error: Key conv1_1/Variable not found in checkpoint [[node save_1/RestoreV2 (defined at <ipython-input-7-d64b6e1aa736>:101) ]]

該当のソースコード

CNNモデル

python

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

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

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

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

horiegom

2019/11/28 05:48

かみ合わせがうまくいかないとは?
koukimaru22

2019/11/28 07:08

エラー文から考えていたのですが予測モデルで入れた画像がCNNモデルの畳み込み層の1層目でうまく機能していないのでかみ合わせがうまくいっていないと書きました
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

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

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

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問