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

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

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

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

機械学習

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

Python

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

Q&A

解決済

1回答

4718閲覧

TensorFlowによるRNNの関数近似がsin波、cos波以外でうまくいきません

tororo

総合スコア7

Python 3.x

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

機械学習

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

Python

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

0グッド

1クリップ

投稿2017/01/10 00:31

参考サイト
↑のサイトを参考にTensorFlowを用いてRNNに様々な関数を近似させようとしているのですが以下のコード(参考サイトのコードをほぼそのまま使用)だとsin波とcos波の学習はうまくいくのですが、他の関数の学習が全くうまくいきません。
具体的には今回y=√x を学習させ、予測させようとしています。

Python

1import tensorflow as tf 2import numpy as np 3import random 4 5def make_mini_batch(train_data, size_of_mini_batch, length_of_sequences): 6 inputs = np.empty(0) 7 outputs = np.empty(0) 8 for _ in range(size_of_mini_batch): 9 index = random.randint(0, len(train_data) - length_of_sequences) 10 part = train_data[index:index + length_of_sequences] 11 inputs = np.append(inputs, part[:, 0]) 12 outputs = np.append(outputs, part[-1, 1]) 13 inputs = inputs.reshape(-1, length_of_sequences, 1) 14 outputs = outputs.reshape(-1, 1) 15 return (inputs, outputs) 16 17def make_prediction_initial(train_data, index, length_of_sequences): 18 return train_data[index:index + length_of_sequences, 0] 19 20train_data_path = "/home/~/RNN_code/normal_sqrt1.npy" 21num_of_input_nodes = 1 22num_of_hidden_nodes = 3 23num_of_output_nodes = 1 24length_of_sequences = 50 25num_of_training_epochs = 2000 26length_of_initial_sequences = 50 27num_of_prediction_epochs = 100 28size_of_mini_batch = 100 29learning_rate = 0.008 30forget_bias = 1.0 31print("train_data_path = %s" % train_data_path) 32print("num_of_input_nodes = %d" % num_of_input_nodes) 33print("num_of_hidden_nodes = %d" % num_of_hidden_nodes) 34print("num_of_output_nodes = %d" % num_of_output_nodes) 35print("length_of_sequences = %d" % length_of_sequences) 36print("num_of_training_epochs = %d" % num_of_training_epochs) 37print("length_of_initial_sequences = %d" % length_of_initial_sequences) 38print("num_of_prediction_epochs = %d" % num_of_prediction_epochs) 39print("size_of_mini_batch = %d" % size_of_mini_batch) 40print("learning_rate = %f" % learning_rate) 41print("forget_bias = %f" % forget_bias) 42 43train_data = np.load(train_data_path) 44print("train_data:", train_data) 45 46# 乱数シードを固定する。 47random.seed(0) 48np.random.seed(0) 49tf.set_random_seed(0) 50 51optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate) #GDM 52 53with tf.Graph().as_default(): 54 input_ph = tf.placeholder(tf.float32, [None, length_of_sequences, num_of_input_nodes], name="input") 55 supervisor_ph = tf.placeholder(tf.float32, [None, num_of_output_nodes], name="supervisor") 56 istate_ph = tf.placeholder(tf.float32, [None, num_of_hidden_nodes * 2], name="istate") 57 58 with tf.name_scope("inference") as scope: 59 weight1_var = tf.Variable(tf.truncated_normal([num_of_input_nodes, num_of_hidden_nodes], stddev=0.1), name="weight1") 60 weight2_var = tf.Variable(tf.truncated_normal([num_of_hidden_nodes, num_of_output_nodes], stddev=0.1), name="weight2") 61 bias1_var = tf.Variable(tf.truncated_normal([num_of_hidden_nodes], stddev=0.1), name="bias1") 62 bias2_var = tf.Variable(tf.truncated_normal([num_of_output_nodes], stddev=0.1), name="bias2") 63 64 in1 = tf.transpose(input_ph, [1, 0, 2]) # (batch, sequence, data) -> (sequence, batch, data) 65 in2 = tf.reshape(in1, [-1, num_of_input_nodes]) # (sequence, batch, data) -> (sequence * batch, data) 66 in3 = tf.matmul(in2, weight1_var) + bias1_var 67 in4 = tf.split(0, length_of_sequences, in3) # sequence * (batch, data) 68 69 cell = tf.nn.rnn_cell.BasicLSTMCell(num_of_hidden_nodes, forget_bias=forget_bias, state_is_tuple=False) 70 rnn_output, states_op = tf.nn.rnn(cell, in4, initial_state=istate_ph) 71 output_op = tf.matmul(rnn_output[-1], weight2_var) + bias2_var 72 73 with tf.name_scope("loss") as scope: 74 square_error = tf.reduce_mean(tf.square(output_op - supervisor_ph)) 75 loss_op = square_error 76 tf.scalar_summary("loss", loss_op) 77 78 with tf.name_scope("training") as scope: 79 training_op = optimizer.minimize(loss_op) 80 81 summary_op = tf.merge_all_summaries() 82 init = tf.initialize_all_variables() 83 84 with tf.Session() as sess: 85 saver = tf.train.Saver() 86 summary_writer = tf.train.SummaryWriter("data_sqrt", graph=sess.graph) 87 sess.run(init) 88 89 for epoch in range(num_of_training_epochs): 90 inputs, supervisors = make_mini_batch(train_data, size_of_mini_batch, length_of_sequences) 91 92 train_dict = { 93 input_ph: inputs, 94 supervisor_ph: supervisors, 95 istate_ph: np.zeros((size_of_mini_batch, num_of_hidden_nodes * 2)), 96 } 97 sess.run(training_op, feed_dict=train_dict) 98 99 if (epoch + 1) % 10 == 0: 100 summary_str, train_loss = sess.run([summary_op, loss_op], feed_dict=train_dict) 101 summary_writer.add_summary(summary_str, epoch) 102 print("train#%d, train loss: %e" % (epoch + 1, train_loss)) 103 104#ここまで訓練。ここから予測 105 inputs = make_prediction_initial(train_data, 0, length_of_initial_sequences) 106 outputs = np.empty(0) 107 states = np.zeros((num_of_hidden_nodes * 2)), 108 109 print("initial:", inputs) 110 np.save("initial_sqrt.npy", inputs) 111 112 for epoch in range(num_of_prediction_epochs): 113 pred_dict = { 114 input_ph: inputs.reshape((1, length_of_sequences, 1)), 115 istate_ph: states, 116 } 117 output, states = sess.run([output_op, states_op], feed_dict=pred_dict) 118 print("prediction#%d, output: %f" % (epoch + 1, output)) 119 120 inputs = np.delete(inputs, 0) 121 inputs = np.append(inputs, output) 122 outputs = np.append(outputs, output) 123 print("outputs:", outputs) 124 np.save("output_sqrt.npy", outputs) 125 126 saver.save(sess, "data_sqrt/model") 127''' 128The MIT License (MIT) 129 130Copyright (C) 2016 Yuya Kato (Nayutaya Inc.) 131 132Permission is hereby granted, free of charge, to any person obtaining a copy 133of this software and associated documentation files (the "Software"), to deal 134in the Software without restriction, including without limitation the rights 135to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 136copies of the Software, and to permit persons to whom the Software is 137furnished to do so, subject to the following conditions: 138 139The above copyright notice and this permission notice shall be included in all 140copies or substantial portions of the Software. 141 142THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 143IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 144FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 145AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 146LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 147OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 148SOFTWARE. 149''' 150 151

training_dataの生成はjupyter notebookで次のようにしています。

python

1 2# coding: utf-8 3 4# In[3]: 5import pandas as pd 6import numpy as np 7import math 8get_ipython().magic('matplotlib inline') 9 10# In[4]: 11# サイクルあたりのステップ数 12steps_per_cycle = 50 13# 生成するサイクル数 14number_of_cycles = 100 15 16# In[5]: 17df = pd.DataFrame(np.arange(steps_per_cycle * number_of_cycles + 1), columns=["t"]) 18df.head() 19 20# In[6]: 21df["sqrt_t"] = df.t.apply(lambda x: math.sqrt(x)) 22 23# In[7]: 24df[["sqrt_t"]].plot() 25 26# In[8]: 27df[["sqrt_t"]].head(steps_per_cycle * 2).plot() 28 29# In[9]: 30df["sqrt_t+1"] = df["sqrt_t"].shift(-1) 31 32# In[10]: 33df.tail() 34 35# In[11]: 36df.dropna(inplace=True) 37 38# In[12]: 39df.tail() 40 41# In[13]: 42df[["sqrt_t", "sqrt_t+1"]].head(steps_per_cycle).plot() 43 44# In[14]: 45matrix = df[["sqrt_t", "sqrt_t+1"]].as_matrix() 46matrix 47 48# In[15]: 49np.save("normal_sqrt1.npy", matrix) 50

ハイパーパラメータをどう調節しても以下の画像のようにひとつ目の予測から正しくない予測をしてしまっています。
###予測結果

なぜうまくいかないのか、どうすればうまくいくのか教えていただけると助かります。

###補足情報(言語/FW/ツール等のバージョンなど)
TensorFlowのバージョンは0.9.0です。
Ubuntu16.04LTSで動かしてます。
Python3.5です。

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

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

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

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

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

guest

回答1

0

ベストアンサー

あまり細かく試していないのですが、以下の変更で手元では学習できるようになりました。

  • Optimizer を AdamOptimizer に
  • LSTM → GRU (これは以下のLayer Normalizationのコードが手元にGRUにしかなかったためで大きな意味はありません)
  • GRUCellにLayer Normalizationを適用
  • GRU ユニット数 3 → 40
  • GRU レイヤ数 1 → 3
  • ミニバッチサイズ 1 → 10
  • 学習回数 2000 → 4000 epoch

Layer Normalization はRNN、特にLSTMやGRUの学習を早くするテクニックです。
単純に、LSTMのユニット数を上げて、レイヤ数を増やし、ミニバッチサイズを下げ、学習回数を上げれば解決するかもしれません。

text

1... 2train#50, train loss: 1.941867e+03 3train#60, train loss: 1.319855e+03 4train#70, train loss: 1.785704e+03 5train#80, train loss: 1.282928e+03 6train#90, train loss: 1.629336e+03 7train#100, train loss: 2.194734e+03 8... 9train#3900, train loss: 3.676242e+00 10train#3910, train loss: 1.784934e+00 11train#3920, train loss: 1.184075e+01 12train#3930, train loss: 1.822354e+00 13train#3940, train loss: 1.167687e-02 14train#3950, train loss: 8.048839e+00 15train#3960, train loss: 9.416826e-02 16train#3970, train loss: 1.455322e-01 17train#3980, train loss: 4.303871e-01 18train#3990, train loss: 7.033576e-01 19train#4000, train loss: 3.479579e+00

コードの提供はご容赦ください。

投稿2017/01/10 23:06

MasashiKimura

総合スコア1150

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

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

tororo

2017/01/12 22:23

ありがとうございます。 おかげさまで解決できました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.50%

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

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

質問する

関連した質問