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

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

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

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

Q&A

解決済

1回答

1779閲覧

TensorFlow Python3

daigakuse-

総合スコア67

Python 3.x

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

0グッド

0クリップ

投稿2017/08/06 05:38

編集2017/08/06 05:43

Tensorflowで作ったモデルをTensorSwiftで使いたいので調べたところモデルをcheckpointではなく変数をそれぞれファイルに書き出す方法があるらしく、以下の方法で書き出します。

python

1ndarray = W_conv1.eval(session=sess) 2list = ndarray.reshape([-1]).tolist() 3f = open("W_conv1", "wb") 4f.write(struct.pack("%df" % len(list), *list)) 5f.close()

このコードを W_conv1 = weight_variable([5, 5, 3, 32])
の下に書いてもこのブロックではsessがまだ代入されていないためもちろんエラー。
sessを代入したコードの下に書いても
W_conv1 はグローバル変数ではないのでこれもエラー。

記述の仕方がわかりません。
どういった方法がありますか?

python

1#!/usr/bin/env python 2# -*- coding: utf-8 -*- 3import sys 4import cv2 5import random 6import numpy as np 7import tensorflow as tf 8import tensorflow.python.platform 9import struct 10 11# AIの学習モデル部分(ニューラルネットワーク)を作成する 12def inference(images_placeholder, keep_prob): 13 14 # 重みを標準偏差0.1の正規分布で初期化する 15 def weight_variable(shape): 16 initial = tf.truncated_normal(shape, stddev=0.1) 17 return tf.Variable(initial) 18 19 # バイアスを標準偏差0.1の正規分布で初期化する 20 def bias_variable(shape): 21 initial = tf.constant(0.1, shape=shape) 22 return tf.Variable(initial) 23 24 # 畳み込み層を作成する 25 def conv2d(x, W): 26 return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') 27 28 # プーリング層を作成する 29 def max_pool_2x2(x): 30 return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME') 31 32 x_image = tf.reshape(images_placeholder, [-1, IMAGE_SIZE, IMAGE_SIZE, 3]) 33 34 # 畳み込み層第1レイヤーを作成 35 with tf.name_scope('conv1') as scope: 36 W_conv1 = weight_variable([5, 5, 3, 32]) 37 # バイアスの数値を代入 38 b_conv1 = bias_variable([32]) 39 h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) 40 41 # プーリング層1の作成 42 with tf.name_scope('pool1') as scope:h_pool1 = max_pool_2x2(h_conv1) 43 44 # 畳み込み層第2レイヤーの作成 45 with tf.name_scope('conv2') as scope: 46 # 第一レイヤーでの出力を第2レイヤー入力にしてもう一度フィルタリング実施。 47 # 64個の特徴を検出する。inputが32なのはなんで?(教えて欲しい) 48 W_conv2 = weight_variable([5, 5, 32, 64]) 49 # バイアスの数値を代入(第一レイヤーと同じ) 50 b_conv2 = bias_variable([64]) 51 # 検出した特徴の整理(第一レイヤーと同じ) 52 h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) 53 54 # プーリング層2の作成(ブーリング層1と同じ) 55 with tf.name_scope('pool2') as scope:h_pool2 = max_pool_2x2(h_conv2) 56 57 # 全結合層1の作成 58 with tf.name_scope('fc1') as scope: 59 W_fc1 = weight_variable([7*7*64, 1024]) 60 b_fc1 = bias_variable([1024]) 61 # 画像の解析を結果をベクトルへ変換 62 h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) 63 # 第一、第二と同じく、検出した特徴を活性化させている 64 h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) 65 # dropoutの設定 66 h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) 67 68 # 全結合層2の作成(読み出しレイヤー) 69 with tf.name_scope('fc2') as scope: 70 W_fc2 = weight_variable([1024, NUM_CLASSES]) 71 b_fc2 = bias_variable([NUM_CLASSES]) 72 73 with tf.name_scope('softmax') as scope: 74 y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) 75 76 # 各ラベルの確率(のようなもの?)を返す 77 return y_conv 78 79def loss(logits, labels): 80 # 交差エントロピーの計算 81 cross_entropy = -tf.reduce_sum(labels*tf.log(logits)) 82 # TensorBoardで表示するよう指定 83 tf.summary.scalar("cross_entropy", cross_entropy) 84 # 誤差の率の値(cross_entropy)を返す 85 return cross_entropy 86def training(loss, learning_rate): 87 #この関数がその当たりの全てをやってくれる様 88 train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss) 89 return train_step 90 91# inferenceで学習モデルが出した予測結果の正解率を算出する 92def accuracy(logits, labels): 93 correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(labels, 1)) 94 # booleanのcorrect_predictionをfloatに直して正解率の算出 95 # false:0,true:1に変換して計算する 96 accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) 97 # TensorBoardで表示する様設定 98 tf.summary.scalar("accuracy", accuracy) 99 return accuracy 100 101if __name__ == '__main__': 102 # ファイルを開く 103 f = open(FLAGS.train, 'r') 104 # データを入れる配列 105 train_image = [] 106 train_label = [] 107 # numpy形式に変換 108 train_image = np.asarray(train_image) 109 train_label = np.asarray(train_label) 110 f.close() 111 112 f = open(FLAGS.test, 'r') 113 test_image = [] 114 test_label = [] 115 for line in f: 116 line = line.rstrip() 117 l = line.split() 118 img = cv2.imread(l[0]) 119 img = cv2.resize(img, (IMAGE_SIZE, IMAGE_SIZE)) 120 test_image.append(img.flatten().astype(np.float32)/255.0) 121 tmp = np.zeros(NUM_CLASSES) 122 tmp[int(l[1])] = 1 123 test_label.append(tmp) 124 test_image = np.asarray(test_image) 125 test_label = np.asarray(test_label) 126 f.close() 127 128 #TensorBoardのグラフに出力するスコープを指定 129 with tf.Graph().as_default(): 130 # 画像を入れるためのTensor(28*28*3(IMAGE_PIXELS)次元の画像が任意の枚数(None)分はいる) 131 images_placeholder = tf.placeholder("float", shape=(None, IMAGE_PIXELS)) 132 # ラベルを入れるためのTensor(3(NUM_CLASSES)次元のラベルが任意の枚数(None)分入る) 133 labels_placeholder = tf.placeholder("float", shape=(None, NUM_CLASSES)) 134 # dropout率を入れる仮のTensor 135 keep_prob = tf.placeholder("float") 136 137 # inference()を呼び出してモデルを作る 138 logits = inference(images_placeholder, keep_prob) 139 # loss()を呼び出して損失を計算 140 loss_value = loss(logits, labels_placeholder) 141 # training()を呼び出して訓練して学習モデルのパラメーターを調整する 142 train_op = training(loss_value, FLAGS.learning_rate) 143 # 精度の計算 144 acc = accuracy(logits, labels_placeholder) 145 146 # 保存の準備 147 saver = tf.train.Saver() 148 # Sessionの作成(TensorFlowの計算は絶対Sessionの中でやらなきゃだめ) 149 sess = tf.Session() 150 # 変数の初期化(Sessionを開始したらまず初期化) 151 sess.run(tf.initialize_all_variables()) 152 # TensorBoard表示の設定(TensorBoardの宣言的な?) 153 summary_op = tf.summary.merge_all() 154 # train_dirでTensorBoardログを出力するpathを指定 155 summary_writer = tf.summary.FileWriter(FLAGS.train_dir, sess.graph_def) 156 157 158 # 実際にmax_stepの回数だけ訓練の実行していく 159 for step in range(FLAGS.max_steps): 160 for i in range(int(len(train_image)/FLAGS.batch_size)): 161 # batch_size分の画像に対して訓練の実行 162 batch = FLAGS.batch_size*i 163 # feed_dictでplaceholderに入れるデータを指定する 164 sess.run(train_op, feed_dict={ 165 images_placeholder: train_image[batch:batch+FLAGS.batch_size], 166 labels_placeholder: train_label[batch:batch+FLAGS.batch_size], 167 keep_prob: 0.5}) 168 169 # 1step終わるたびに精度を計算する 170 train_accuracy = sess.run(acc, feed_dict={ 171 images_placeholder: train_image, 172 labels_placeholder: train_label, 173 keep_prob: 1.0}) 174 print ("step %d, training accuracy %g"%(step, train_accuracy)) 175 176 # 1step終わるたびにTensorBoardに表示する値を追加する 177 summary_str = sess.run(summary_op, feed_dict={ 178 images_placeholder: train_image, 179 labels_placeholder: train_label, 180 keep_prob: 1.0}) 181 summary_writer.add_summary(summary_str, step) 182 183 # 訓練が終了したらテストデータに対する精度を表示する 184 print ("test accuracy %g"%sess.run(acc, feed_dict={ 185 images_placeholder: test_image, 186 labels_placeholder: test_label, 187 keep_prob: 1.0})) 188 189 # データを学習して最終的に出来上がったモデルを保存 190 # "model.ckpt"は出力されるファイル名 191 save_path = saver.save(sess, "model2.ckpt")

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

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

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

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

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

guest

回答1

0

自己解決

グローバル変数にしたらできた

投稿2017/08/06 07:28

daigakuse-

総合スコア67

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

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

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問