TFLearnっていう、TensorFlowをもっと簡単に使えるライブラリがあるということなので、それも入れてみた。 http://tflearn.org/
TFlearnで使うグラフの定義ですが、今回は線形モデルだとわかっているものとして、単に入力層から線形結合させたものを定義します。あと、バイアスも使わないので、bias=Falseとしておきます。
ただ、regressionについては、デフォルトのままだとあまりよい結果がでなかったので、SGDメソッドを使って学習率を徐々に下げていくよう調整を行いました。
# Graph definition
layer_in = tflearn.input_data(shape=[None, N])
layer1 = tflearn.fully_connected(layer_in, 1, activation='linear', bias=False)
sgd = tflearn.optimizers.SGD(learning_rate=0.01, lr_decay=0.95, decay_step=100)
regression = tflearn.regression(layer1, optimizer=sgd, loss='mean_square')
import numpy as np
import pandas as pd
import tensorflow as tf
import tflearn
file = 'USDJPY5 Ichimoku.txt'
ohlc = pd.read_csv(file, index_col='Time', parse_dates=True)
close = ohlc.Close.values
ind1 = ohlc.Ind1.values
N = 2
X = np.empty((0,N))
Y = np.empty((0,1))
for i in range(200):
if abs(close[i]-close[i+1]) >= 1.0:
X = np.vstack((X, close[i:i+N]))
Y = np.vstack((Y, ind1[i+N-1:i+N]))
# Graph definition
layer_in = tflearn.input_data(shape=[None, N])
layer1 = tflearn.fully_connected(layer_in, 1, activation='linear', bias=False)
sgd = tflearn.optimizers.SGD(learning_rate=0.01, lr_decay=0.95, decay_step=100)
regression = tflearn.regression(layer1, optimizer=sgd, loss='mean_square')
# Model training
m = tflearn.DNN(regression)
m.fit(X, Y, n_epoch=10000, snapshot_epoch=False, run_id='Ichimokulearn')
# Weights
print('\nweights')
for i in range(N):
print('W['+str(i)+'] =' ,m.get_weights(layer1.W)[i])
Training Step: 10000 | total loss: 3.34792 | time: 0.011s
| SGD | epoch: 10000 | loss: 3.34792 -- iter: 31/31
weights
W[0] = [ 0.63396788]
W[1] = [ 0.37587214]
そもそもニューラルネットワークは、正確な数値予測のためではなく、結構アバウトな予測を行うためのものみたいです。
そこで、こんどは指標値に平均0、標準偏差0.1のガウスノイズを付加したものを教師データとしてみました。
import numpy as np
import pandas as pd
import tensorflow as tf
import tflearn
file = 'USDJPY5 Ichimoku.txt'
ohlc = pd.read_csv(file, index_col='Time', parse_dates=True)
close = ohlc.Close.values
ind1 = ohlc.Ind1.values
N = 2
X = np.empty((0,N))
Y = np.empty((0,1))
for i in range(200):
if abs(close[i]-close[i+1]) >= 1.0:
X = np.vstack((X, close[i:i+N]))
noise = np.random.normal(0,0.1)
Y = np.vstack((Y, ind1[i+N-1:i+N]+noise))
# Graph definition
layer_in = tflearn.input_data(shape=[None, N])
layer1 = tflearn.fully_connected(layer_in, 1, activation='linear', bias=False)
sgd = tflearn.optimizers.SGD(learning_rate=0.01, lr_decay=0.95, decay_step=100)
regression = tflearn.regression(layer1, optimizer=sgd, loss='mean_square')
# Model training
m = tflearn.DNN(regression)
m.fit(X, Y, n_epoch=10000, snapshot_epoch=False, run_id=' Ichimokulearn')
# Weights
print('\nweights')
for i in range(N):
print('W['+str(i)+'] =' ,m.get_weights(layer1.W)[i])
Training Step: 10000 | total loss: 0.50975 | time: 0.011s
| SGD | epoch: 10000 | loss: 0.50975 -- iter: 31/31
weights
W[0] = [ 0.66791338]
W[1] = [ 0.33452979]