5分鐘用keras實驗LSTM時間序列預測最簡單版,簡單就是一切!能運行就是一切!

輸入測試數據,這裏以sin函數爲例:

data = np.sin(x)
print(data)

[0.         0.14943813 0.29552021 ... 0.96101339 0.90890233 0.83637928]
這個函數你可以隨便寫,也可以展開應用,開個腦洞:

一,把一首歌的單聲部時序錄入,如果是多聲部,如鋼琴,錄入多次運行多次好了。

比如理查德的經典和絃套路,夢中婚禮,星空,6253進行,都可以理解爲是時間序列,預測和絃是簡單的,還可以預測具體的音階時長,最後做一萬首理查德風格的鋼琴曲!汪峯,許巍,Yiruma,肖邦都可以!~

聲音可以描述成12分律,用相對音高,首調來描述,Do Re Mi Fa So La Si分別對應,0和12同唱名

0,2,4,5,7,9,11,12 然後可以轉成MusicXML,放到OVE,GuitaPro 裏播放。

二,古詩,小說亦何嘗不是時間序列?錄入三國演義,全唐詩,會輸出什麼?

三,圖片亦何嘗不是時間序列?錄入大量Ru1mm圖片,會輸出什麼?

import matplotlib.pyplot as plt
import numpy as np
from numpy import newaxis
from keras.models import Sequential
from keras.layers.core import Dense, Activation
from keras.layers.recurrent import LSTM
import os

os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"

step = 0.15
steps = 750
x = np.arange(0, steps, step)
data = np.sin(x)
print(data)
SEQ_LENGTH = 100
sequence_length = SEQ_LENGTH + 1
result = []

for index in range(len(data) - sequence_length):
    result.append(data[index: index + sequence_length])
result = np.array(result)

row = round(0.9 * result.shape[0])


train = result[:int(row), :]

np.random.shuffle(train)
x_train = train[:, :-1]
y_train = train[:, -1]
x_test = result[int(row):, :-1]
y_test = result[int(row):, -1]

# LSTM層的輸入必須是三維的
x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))
print(x_train)

# Neural Network model
HIDDEN_DIM = 512
LAYER_NUM = 10
model = Sequential()
model.add(LSTM(50, input_shape=(x_train.shape[1], x_train.shape[2]), return_sequences=True))
model.add(LSTM(100, return_sequences=False))
model.add(Dense(1))
model.add(Activation('linear'))
model.compile(loss="mse", optimizer="rmsprop")
model.summary()
BATCH_SIZE = 32
epoch = 1
model.fit(x_train, y_train, batch_size=BATCH_SIZE, verbose=1, epochs=epoch, validation_split=0.05)

# start with first frame
curr_frame = x_test[0]

# start with zeros
# curr_frame = np.zeros((100,1))

predicted = []
for i in range(len(x_test)):
    predicted.append(model.predict(curr_frame[newaxis, :, :])[0, 0])
    curr_frame = curr_frame[1:]
    curr_frame = np.insert(curr_frame, [SEQ_LENGTH - 1], predicted[-1], axis=0)
predicted1 = model.predict(x_test)
predicted1 = np.reshape(predicted1, (predicted1.size,))

plt.figure(1)
plt.subplot(211)
plt.plot(predicted)
plt.plot(y_test)
plt.subplot(212)
plt.plot(predicted1)
plt.plot(y_test)
plt.show()

簡單纔是一切的開始,模仿纔是一切的開始!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章