tensorflowでニューラルネットワークの学習器の保存について質問させていただきます。
python_train.pyがニューラルネットワークを学習させるプログラムで、
python_test.pyが学習させたニューラルネットワークをテストさせるプログラムになります。
以下にコードを記載しています。
※汚いコードですみません。。。
python
1#python_train.py 2 3# coding: utf-8 4 5import tensorflow as tf 6import numpy as np 7import pandas as pd 8import glob 9import os 10import math 11from AdaBound import AdaBoundOptimizer 12 13def read_file(filename): 14 ds_tmp = [] 15 with open(filename, 'r') as f: 16 print(filename) 17 for i in f: 18 txt = i.split() 19 del txt[0] 20 txt = [ float(s) for s in txt] 21 ds_tmp.append(txt) 22 23 ds = np.array(ds_tmp) 24 return ds 25 26 27def process(label,path,Range): 28 train_filename = path + "input_train_{}_rev.txt".format(label) 29 test_filename = path + "input_val_{}.txt".format(label) 30 train_data = read_file(train_filename) 31 test_data = read_file(test_filename) 32 y_train = train_data[:, 5:]/50.0 33 x_train = train_data[:, :5] 34 y_test = test_data[:, 5:]/50.0 35 x_test = test_data[:, :5] 36 37 num_examples = y_train.shape[0] 38 num_input = x_train.shape[1] 39 bias_with_x = np.insert(x_train, 0, 1, axis=1).astype(np.float32) 40 bias_with_x_test = np.insert(x_test, 0, 1, axis=1).astype(np.float32) 41 42 #パラメータの設定 43 num_hidden1 = 30 44 num_hidden2 = 30 45 training_steps = 25000 46 learning_rate = 0.005 47 lambda_2 = 0.00000001 48 MAE_train_ave = 0 49 MAE_test_ave = 0 50 MAE_val_ave = 0 51 52 for seed in range(1,2): 53 losses = [] 54 55 with tf.Session() as sess: 56 # SET UP ALL THE TENSORS, VARIABLES, AND OPERATIONS. 57 input = tf.constant(bias_with_x) 58 target = tf.constant(np.transpose([y_train]).astype(np.float32)) 59 60 # 重みの初期化 61 shape = [num_input+1, num_hidden1] 62 n = shape[0] * shape[1] 63 stddev = math.sqrt(1.0 / n) 64 initial = tf.truncated_normal(shape=shape, stddev=stddev) 65 initial = tf.truncated_normal(shape=shape, stddev=stddev, seed=seed) 66 weights = tf.Variable(initial, name="weights") 67 68 shape = [num_hidden1, num_hidden2] 69 n = shape[0] * shape[1] 70 stddev = math.sqrt(1.0 / n) 71 initial = tf.truncated_normal(shape=shape, stddev=stddev) 72 initial = tf.truncated_normal(shape=shape, stddev=stddev, seed=seed) 73 weights1 = tf.Variable(initial, name="weights1") 74 75 shape = [num_hidden2, 1] 76 n = shape[0] * shape[1] 77 stddev = math.sqrt(1.0 / n) 78 initial = tf.truncated_normal(shape=shape, stddev=stddev) 79 initial = tf.truncated_normal(shape=shape, stddev=stddev, seed=seed) 80 weights2 = tf.Variable(initial, name="weights2") 81 82 # 層の中の計算(活性化関数, 正則化, 損失関数) 83 y1 = tf.sigmoid(tf.matmul(input, weights)) 84 y2 = tf.sigmoid(tf.matmul(y1, weights1)) 85 yhat = tf.sigmoid(tf.matmul(y2, weights2)) 86 yerror = tf.subtract(yhat, target) 87 loss1 = tf.nn.l2_loss(yerror) 88 L2_sqr = tf.nn.l2_loss(weights) + tf.nn.l2_loss(weights1) + tf.nn.l2_loss(weights2) 89 loss = loss1 + lambda_2 * L2_sqr 90 91 update_weights = AdaBoundOptimizer(learning_rate=0.01, final_lr=0.1, 92 beta1=0.9, beta2=0.999, 93 amsbound=False).minimize(loss) 94 95 tf.global_variables_initializer().run() 96 97 for i in range(training_steps): 98 update_weights.run() 99 losses.append(loss.eval()) 100 101 # 学習器保存 102 saver = tf.train.Saver() 103 saver.save(sess, "../../nn_train/nn/sig_h2_n30/BED600444/{}km/in5_BED600444_h2_n30_{}".format(Range, seed)) 104 105 # 検証データ 106 input_test = tf.constant(bias_with_x_test) 107 target_test = tf.constant(np.transpose([y_test]).astype(np.float32)) 108 y1_test = tf.sigmoid(tf.matmul(input_test, weights)) 109 y2_test = tf.sigmoid(tf.matmul(y1_test, weights1)) 110 yhat_test = tf.sigmoid(tf.matmul(y2_test, weights2)) 111 112 113 # Training is done, get the final values for the graphs 114 betas = weights.eval() 115 yhat = yhat.eval() 116 error = np.sqrt(((y_train-yhat)*(y_train-yhat)).mean()) 117 118 size = len(y_train) 119 MAE = (np.sum(np.abs(y_train-yhat)))/size 120 121 yhat_test = yhat_test.eval() 122 size = len(y_test) 123 MAE_val = (np.sum(np.abs(y_test-yhat_test)))/size 124 125 MAE_train_ave += MAE 126 MAE_val_ave += MAE_val 127 128 Train = MAE_train_ave 129 Val = MAE_val_ave 130 print('train_error : %s' % Train) 131 print('val_error : %s' % Val) 132 133 return Train, Val 134 135 136def main(): 137 count = 0 138 bool = True 139 while bool: 140 with open('../../../../text/in5_ver3/point/rev/label_BED600444.txt', 'r') as label: 141 a_list = [line.rstrip() for line in label] 142 143 for label in a_list: 144 ini = process(label, '../../../../text/in5_ver3/point/rev/', 3) 145 count += 1 146 147 with open('../../../../text/in5/4km/point/rev/label_BED600444.txt', 'r') as label: 148 a_list = [line.rstrip() for line in label] 149 150 for label in a_list: 151 r4 = process(label, '../../../../text/in5/4km/point/rev/', 4) 152 count += 1 153 154 with open('../../../../text/in5/2km/point/rev/label_BED600444.txt', 'r') as label: 155 a_list = [line.rstrip() for line in label] 156 157 for label in a_list: 158 r2 = process(label, '../../../../text/in5/2km/point/rev/', 2) 159 count += 1 160 161 print(min(r2[1], ini[1], r4[1]), count) 162 163if __name__ == '__main__': 164 main()
python
1#python_test.py 2 3import tensorflow as tf 4import numpy as np 5import pandas as pd 6import glob 7import os 8import math 9 10 11def read_file(filename): 12 ds_tmp = [] 13 with open(filename, 'r') as f: 14 print(filename) 15 for i in f: 16 txt = i.split() 17 del txt[0] 18 txt = [ float(s) for s in txt ] 19 ds_tmp.append(txt) 20 21 ds = np.array(ds_tmp) 22 return ds 23 24def process(label, path): 25 test_filename = path + "input_train_{}_rev.txt".format(label) 26 test_data = read_file(test_filename) 27 y_test = test_data[:, 5:]/50.0 28 x_test = test_data[:, :5] 29 30 bias_with_x_test = np.insert(x_test, 0, 1, axis=1).astype(np.float32) 31 input_test = tf.constant(bias_with_x_test) 32 target_test = tf.constant(np.transpose([y_test]).astype(np.float32)) 33 34 with tf.Session() as sess: 35 # 復元 36 saver = tf.train.import_meta_graph('./in5_BED600444_h2_n30_1.meta') 37 saver.restore(sess, tf.train.latest_checkpoint('./')) 38 graph = tf.get_default_graph() 39 weights = graph.get_tensor_by_name("weights:0") 40 weights1 = graph.get_tensor_by_name("weights1:0") 41 weights2 = graph.get_tensor_by_name("weights2:0") 42 print(sess.run('weights:0')) 43 44 # テスト地点の計算 45 y1_test = tf.sigmoid(tf.matmul(input_test, weights)) 46 y2_test = tf.sigmoid(tf.matmul(y1_test, weights1)) 47 yhat_test = tf.sigmoid(tf.matmul(y2_test, weights2)) 48 49 size = len(y_test) 50 MAE_test = (np.sum(np.abs(y_test-yhat_test))) 51 y = sess.run(MAE_test) 52 53 return y 54 55def main(): 56 with open('../../../../../../../text/in5/5km/point/rev/label_BED600444.txt', 'r') as label: 57 a_list = [line.rstrip() for line in label] 58 59 for label in a_list: 60 test_error = process(label, '../../../../../../../text/in5/5km/point/rev/') 61 62 print('test_error : %s' % test_error.mean()) 63 64if __name__ == '__main__': 65 main() 66
python_train.pyで学習させた重みをtf.train.Saver()
で保存したのち、
きちんと保存できているか同じデータを使って確認したところ、
train_error
が異なりました。
tf.train.Saver()
を入れる箇所が違うのかと思い、
他にも入れる箇所を変えてみましたが変わりませんでした。
分かる方がいましたら、回答いただけると助かります。
※ご回答いただいた内容に質問させていただくこともあるかと思いますので、
※よろしければご返信いただければと思います。
回答1件
あなたの回答
tips
プレビュー