<jupyter_start><jupyter_text>時系列予測：日経平均株価の例<jupyter_code>! git clone https://github.com/mashyko/LSTM_RNN
%cd LSTM_RNN
import numpy as np
import pandas
import matplotlib.pyplot as plt
dataframe = pandas.read_csv('data/nikkei_data.csv', usecols=[1], engine='python', skipfooter=3)
dataset = dataframe.values
dataset = dataset.astype('float64')
plt.plot(dataset)
plt.show()
import matplotlib.pyplot as plt
import math
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM
#from keras.layers import LSTM
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
# fix random seed for reproducibility
np.random.seed(7)
# normalize the dataset
scaler = MinMaxScaler(feature_range=(0, 1))
dataset = scaler.fit_transform(dataset)
# split into train and test sets
train_size = int(len(dataset) * 0.7)
test_size = len(dataset) - train_size
train, test = dataset[0:train_size,:], dataset[train_size:len(dataset),:]
print(len(train), len(test))

# convert an array of values into a dataset matrix
def create_dataset(dataset, maxlen):
    dataX, dataY = [], []
    for i in range(len(dataset)-maxlen-1):
#        a = dataset[i:(i+look_back), 0]
        dataX.append(dataset[i:(i+maxlen),0])
        dataY.append(dataset[i + maxlen,0])
    return np.array(dataX), np.array(dataY)

# reshape into X=t,t-1,t-2 and Y=t+1
maxlen =20

trainX, trainY = create_dataset(train, maxlen)
testX, testY = create_dataset(test, maxlen)
print (trainX.shape[0])
print (trainX.shape[1])
print (trainY.shape[0])

print (trainX[:10,:])
print (trainY[:10])
# reshape input to be [samples, time steps, features]
trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1]))
print(trainX[:10,:])

# create and fit the LSTM network

#input_shape=(1, maxlen)

model = Sequential()
model.add(LSTM(20, input_shape=(1, maxlen)))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(trainX, trainY, epochs=100, batch_size=1, verbose=2)

# 予想を遂行する
trainPredict = model.predict(trainX)
testPredict = model.predict(testX)
# 予測を invert する
trainPredict = scaler.inverse_transform(trainPredict)
trainY = scaler.inverse_transform([trainY])
testPredict = scaler.inverse_transform(testPredict)
testY = scaler.inverse_transform([testY])
# 平方平均二乗誤差 (RMSE, root mean squared error) を計算する
trainScore = math.sqrt(mean_squared_error(trainY[0], trainPredict[:,0]))
print('Train Score: %.2f RMSE' % (trainScore))
testScore = math.sqrt(mean_squared_error(testY[0], testPredict[:,0]))
print('Test Score: %.2f RMSE' % (testScore))<jupyter_output>Train Score: 0.01 RMSE
Test Score: 0.01 RMSE<jupyter_text>http://tekenuko.hatenablog.com/entry/2017/07/25/005348<jupyter_code># shift train predictions for plotting
trainPredictPlot = np.empty_like(dataset)
trainPredictPlot[:, :] = np.nan
trainPredictPlot[maxlen:len(trainPredict)+maxlen, :] = trainPredict
# shift test predictions for plotting
testPredictPlot = np.empty_like(dataset)
testPredictPlot[:, :] = np.nan
testPredictPlot[len(trainPredict)+(maxlen*2)+1:len(dataset)-1, :] = testPredict
# plot baseline and predictions
plt.plot(scaler.inverse_transform(dataset), color ="g", label = "row")
plt.plot(trainPredictPlot,color="b", label="trainpredict")
plt.plot(testPredictPlot,color="m", label="testpredict")

plt.legend()
plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.14239953407105416, 'fraction_numerical': 0.02125800815375655, 'mean_word_length': 6.842465753424658, 'pattern_counts': {'":': 0, '<': 8, '<?xml version=': 0, '>': 8, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '443245', 'license': 'MIT', 'n_tokens_mistral': 1335, 'n_tokens_neox': 1265, 'n_words': 261, 'path': 'LSTM_nikkei.ipynb', 'repo_name': 'mashyko/LSTM_RNN', 'size': '3434'}