機(jī)器學(xué)習(xí) LSTM預(yù)測(cè)股票走勢(shì)

直接上代碼

#######

# coding=utf-8

importpandasaspd

importnumpyasnp

importmatplotlib.pyplotasplt

importtensorflowastf

rnn_unit =10# 隱層數(shù)量

input_size =7

output_size =1

lr =0.0006# 學(xué)習(xí)率

# ——————————————————導(dǎo)入數(shù)據(jù)——————————————————————

f =open('/Users/zhangmenren/Desktop/機(jī)器學(xué)習(xí)/dataset_2.csv')

df = pd.read_csv(f)# 讀入股票數(shù)據(jù)

data = df.iloc[:,2:10].values# 取第3-10列

# 獲取訓(xùn)練集

defget_train_data(batch_size=1, time_step=20, train_begin=0, train_end=5800):

batch_index = []

data_train = data[train_begin:train_end]

normalized_train_data = (data_train - np.mean(data_train,axis=0)) / np.std(data_train,axis=0)# 標(biāo)準(zhǔn)化

train_x, train_y = [], []# 訓(xùn)練集

foriinrange(len(normalized_train_data) - time_step):

ifi % batch_size ==0:

batch_index.append(i)

x = normalized_train_data[i:i + time_step, :7]

y = normalized_train_data[i:i + time_step,7, np.newaxis]

train_x.append(x.tolist())

train_y.append(y.tolist())

batch_index.append((len(normalized_train_data) - time_step))

returnbatch_index, train_x, train_y

# 獲取測(cè)試集

defget_test_data(time_step=1, test_begin=5800):

data_test = data[test_begin:]

mean = np.mean(data_test,axis=0)

std = np.std(data_test,axis=0)

normalized_test_data = (data_test - mean) / std# 標(biāo)準(zhǔn)化

size = (len(normalized_test_data) + time_step -1) // time_step# 有size個(gè)sample

test_x, test_y = [], []

foriinrange(size -1):

x = normalized_test_data[i * time_step:(i +1) * time_step, :7]

y = normalized_test_data[i * time_step:(i +1) * time_step,7]

test_x.append(x.tolist())

test_y.extend(y)

test_x.append((normalized_test_data[(i +1) * time_step:, :7]).tolist())

test_y.extend((normalized_test_data[(i +1) * time_step:,7]).tolist())

returnmean, std, test_x, test_y

# ——————————————————定義神經(jīng)網(wǎng)絡(luò)變量——————————————————

# 輸入層、輸出層權(quán)重、偏置

weights = {

'in': tf.Variable(tf.random_normal([input_size, rnn_unit])),

'out': tf.Variable(tf.random_normal([rnn_unit,1]))

}

biases = {

'in': tf.Variable(tf.constant(0.1,shape=[rnn_unit, ])),

'out': tf.Variable(tf.constant(0.1,shape=[1, ]))

}

# ——————————————————定義神經(jīng)網(wǎng)絡(luò)變量——————————————————

deflstm(X):

batch_size = tf.shape(X)[0]

time_step = tf.shape(X)[1]

w_in = weights['in']

b_in = biases['in']

input = tf.reshape(X, [-1, input_size])# 需要將tensor轉(zhuǎn)成2維進(jìn)行計(jì)算,計(jì)算后的結(jié)果作為隱藏層的輸入

input_rnn = tf.matmul(input, w_in) + b_in

input_rnn = tf.reshape(input_rnn, [-1, time_step, rnn_unit])# 將tensor轉(zhuǎn)成3維牵辣,作為lstm cell的輸入

cell = tf.nn.rnn_cell.BasicLSTMCell(rnn_unit)

init_state = cell.zero_state(batch_size,dtype=tf.float32)

output_rnn, final_states = tf.nn.dynamic_rnn(cell, input_rnn,initial_state=init_state,dtype=tf.float32)

output = tf.reshape(output_rnn, [-1, rnn_unit])

w_out = weights['out']

b_out = biases['out']

pred = tf.matmul(output, w_out) + b_out

returnpred, final_states

# ————————————————訓(xùn)練模型————————————————————

deftrain_lstm(batch_size=10, time_step=20, train_begin=2000, train_end=5800):

X = tf.placeholder(tf.float32,shape=[None, time_step, input_size])

Y = tf.placeholder(tf.float32,shape=[None, time_step, output_size])

batch_index, train_x, train_y = get_train_data(batch_size, time_step, train_begin, train_end)

withtf.variable_scope("sec_lstm"):

pred, _ = lstm(X)

loss = tf.reduce_mean(tf.square(tf.reshape(pred, [-1]) - tf.reshape(Y, [-1])))

train_op = tf.train.AdamOptimizer(lr).minimize(loss)

saver = tf.train.Saver(tf.global_variables(),max_to_keep=15)

withtf.Session()assess:

sess.run(tf.global_variables_initializer())

foriinrange(100000):# 這個(gè)迭代次數(shù),可以更改违施,越大預(yù)測(cè)效果會(huì)更好谋竖,但需要更長(zhǎng)時(shí)間

forstepinrange(len(batch_index) -1):

_, loss_ = sess.run([train_op, loss],feed_dict={X: train_x[batch_index[step]:batch_index[step +1]],

Y: train_y[batch_index[step]:batch_index[step +1]]})

print("Number of iterations:", i," loss:", loss_)

#print("model_save: ", saver.save(sess, 'model_save2/modle.ckpt'))

saver.save(sess,"save/model.ckpt")

# 我是在window下跑的,這個(gè)地址是存放模型的地方遭庶,模型參數(shù)文件名為modle.ckpt

# 在Linux下面用 'model_save2/modle.ckpt'

print("The train has finished")

train_lstm()

# ————————————————預(yù)測(cè)模型————————————————————

defprediction(time_step=20):

X = tf.placeholder(tf.float32,shape=[None, time_step, input_size])

mean, std, test_x, test_y = get_test_data(time_step)

withtf.variable_scope("sec_lstm",reuse=True):

pred, _ = lstm(X)

saver = tf.train.Saver(tf.global_variables())

withtf.Session()assess:

# 參數(shù)恢復(fù)

module_file = tf.train.latest_checkpoint('save/')

#saver.restore(sess, module_file)

print("1111111",module_file)

saver.restore(sess, module_file)

test_predict = []

forstepinrange(len(test_x) -1):

prob = sess.run(pred,feed_dict={X: [test_x[step]]})

predict = prob.reshape((-1))

test_predict.extend(predict)

test_y = np.array(test_y) * std[7] + mean[7]

test_predict = np.array(test_predict) * std[7] + mean[7]

acc = np.average(np.abs(test_predict - test_y[:len(test_predict)]) / test_y[:len(test_predict)])# 偏差程度

print("The accuracy of this predict:", acc)

# 以折線圖表示結(jié)果

plt.figure()

plt.plot(list(range(len(test_predict))), test_predict,color='b', )

plt.plot(list(range(len(test_y))), test_y,color='r')

plt.show()

prediction()

原文參考鏈接:https://www.2cto.com/kf/201702/604190.html

###########預(yù)測(cè)結(jié)果###########


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末宁仔,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子峦睡,更是在濱河造成了極大的恐慌翎苫,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,198評(píng)論 6 514
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件榨了,死亡現(xiàn)場(chǎng)離奇詭異煎谍,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)龙屉,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,334評(píng)論 3 398
  • 文/潘曉璐 我一進(jìn)店門呐粘,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人转捕,你說我怎么就攤上這事作岖。” “怎么了五芝?”我有些...
    開封第一講書人閱讀 167,643評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵痘儡,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我枢步,道長(zhǎng)沉删,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,495評(píng)論 1 296
  • 正文 為了忘掉前任醉途,我火速辦了婚禮丑念,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘结蟋。我一直安慰自己脯倚,他們只是感情好趋惨,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,502評(píng)論 6 397
  • 文/花漫 我一把揭開白布爬坑。 她就那樣靜靜地躺著谦趣,像睡著了一般昔瞧。 火紅的嫁衣襯著肌膚如雪挟憔。 梳的紋絲不亂的頭發(fā)上琼稻,一...
    開封第一講書人閱讀 52,156評(píng)論 1 308
  • 那天幻馁,我揣著相機(jī)與錄音庇配,去河邊找鬼尼夺。 笑死尊残,一個(gè)胖子當(dāng)著我的面吹牛炒瘸,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播寝衫,決...
    沈念sama閱讀 40,743評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼顷扩,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了慰毅?” 一聲冷哼從身側(cè)響起隘截,我...
    開封第一講書人閱讀 39,659評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎汹胃,沒想到半個(gè)月后婶芭,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,200評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡着饥,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,282評(píng)論 3 340
  • 正文 我和宋清朗相戀三年犀农,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片宰掉。...
    茶點(diǎn)故事閱讀 40,424評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡呵哨,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出贵扰,到底是詐尸還是另有隱情仇穗,我是刑警寧澤流部,帶...
    沈念sama閱讀 36,107評(píng)論 5 349
  • 正文 年R本政府宣布戚绕,位于F島的核電站,受9級(jí)特大地震影響枝冀,放射性物質(zhì)發(fā)生泄漏舞丛。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,789評(píng)論 3 333
  • 文/蒙蒙 一果漾、第九天 我趴在偏房一處隱蔽的房頂上張望球切。 院中可真熱鬧,春花似錦绒障、人聲如沸吨凑。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,264評(píng)論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)鸵钝。三九已至,卻和暖如春庐镐,著一層夾襖步出監(jiān)牢的瞬間恩商,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,390評(píng)論 1 271
  • 我被黑心中介騙來泰國(guó)打工必逆, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留怠堪,地道東北人揽乱。 一個(gè)月前我還...
    沈念sama閱讀 48,798評(píng)論 3 376
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像粟矿,于是被迫代替她去往敵國(guó)和親凰棉。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,435評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容