使用TensorFlow和Python进行价值预测

3

我有一个数据集,其中包含股票价格列表。我需要使用tensorflow和python来预测收盘价。

Q1:我有以下代码,它将前2000条记录作为训练数据,将2001到20000条记录作为测试数据,但我不知道如何更改代码以预测今天和未来一天的收盘价?请给予建议!

#!/usr/bin/env python2

import numpy as np
import pandas as pd
import tensorflow as tf
import matplotlib.pyplot as plt

def feature_scaling(input_pd, scaling_meathod):
    if scaling_meathod == 'z-score':
       scaled_pd = (input_pd - input_pd.mean()) / input_pd.std()
    elif scaling_meathod == 'min-max':
       scaled_pd = (input_pd - input_pd.min()) / (input_pd.max() - 
    input_pd.min())
    return scaled_pd

def input_reshape(input_pd, start, end, batch_size, batch_shift, n_features):
    temp_pd = input_pd[start-1: end+batch_size-1]
    output_pd = map(lambda y : temp_pd[y:y+batch_size], xrange(0, end-start+1, batch_shift))
    output_temp = map(lambda x : np.array(output_pd[x]).reshape([-1]), xrange(len(output_pd)))
    output = np.reshape(output_temp, [-1, batch_size, n_features])
    return output

def target_reshape(input_pd, start, end, batch_size, batch_shift, n_step_ahead, m_steps_pred):
    temp_pd = input_pd[start+batch_size+n_step_ahead-2: end+batch_size+n_step_ahead+m_steps_pred-2]
    print temp_pd
    output_pd = map(lambda y : temp_pd[y:y+m_steps_pred], xrange(0, end-start+1, batch_shift))
    output_temp = map(lambda x : np.array(output_pd[x]).reshape([-1]), xrange(len(output_pd)))
    output = np.reshape(output_temp, [-1,1])
    return output

def lstm(input, n_inputs, n_steps, n_of_layers, scope_name): 
    num_layers = n_of_layers
    input = tf.transpose(input,[1, 0, 2])
    input = tf.reshape(input,[-1, n_inputs])  
    input = tf.split(0, n_steps, input)
    with tf.variable_scope(scope_name):
    cell = tf.nn.rnn_cell.BasicLSTMCell(num_units=n_inputs) 
    cell = tf.nn.rnn_cell.MultiRNNCell([cell]*num_layers)
    output, state = tf.nn.rnn(cell, input, dtype=tf.float32)    yi1
    output = output[-1] 
    return output    

    feature_to_input = ['open price', 'highest price', 'lowest price', 'close price','turnover', 'volume','mean price']
    feature_to_predict = ['close price']
    feature_to_scale = ['volume']
    sacling_meathod = 'min-max'

    train_start = 1 
    train_end = 1000
    test_start = 1001
    test_end = 20000

    batch_size = 100
    batch_shift = 1
    n_step_ahead = 1
    m_steps_pred = 1
    n_features = len(feature_to_input)

    lstm_scope_name = 'lstm_prediction'
    n_lstm_layers = 1
    n_pred_class = 1
    learning_rate = 0.1
    EPOCHS = 1000
    PRINT_STEP = 100

    read_data_pd = pd.read_csv('./stock_price.csv')
    temp_pd = feature_scaling(input_pd[feature_to_scale],sacling_meathod)
    input_pd[feature_to_scale] = temp_pd
    train_input_temp_pd = input_pd[feature_to_input]
    train_input_nparr = input_reshape(train_input_temp_pd, 
    train_start, train_end, batch_size, batch_shift, n_features)

    train_target_temp_pd = input_pd[feature_to_predict]
    train_target_nparr = target_reshape(train_target_temp_pd, train_start, train_end, batch_size, batch_shift, n_step_ahead, m_steps_pred)

    test_input_temp_pd = input_pd[feature_to_input]
    test_input_nparr = input_reshape(test_input_temp_pd, test_start, test_end, batch_size, batch_shift, n_features)

    test_target_temp_pd = input_pd[feature_to_predict]
    test_target_nparr = target_reshape(test_target_temp_pd, test_start, test_end, batch_size, batch_shift, n_step_ahead, m_steps_pred)

    tf.reset_default_graph()

    x_ = tf.placeholder(tf.float32, [None, batch_size, n_features])
    y_ = tf.placeholder(tf.float32, [None, 1])
    lstm_output = lstm(x_, n_features, batch_size, n_lstm_layers, lstm_scope_name)

    W = tf.Variable(tf.random_normal([n_features, n_pred_class]))                                                                                                    
    b = tf.Variable(tf.random_normal([n_pred_class]))
    y = tf.matmul(lstm_output, W) + b
    cost_func = tf.reduce_mean(tf.square(y - y_))
    train_op = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost_func)

    optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)
    init = tf.initialize_all_variables()        
    with tf.Session() as sess:
        sess.run(init)
        for ii in range(EPOCHS):
            sess.run(train_op, feed_dict={x_:train_input_nparr, y_:train_target_nparr})
            if ii % PRINT_STEP == 0:
               cost = sess.run(cost_func, feed_dict={x_:train_input_nparr, y_:train_target_nparr})
               print 'iteration =', ii, 'training cost:', cost

首先,90% 用于训练,10% 用于测试。 - aerin
1
这个问题是如此伟大的库(如 TensorFlow)对机器学习社区造成的“损害”的一个很好的例子。它们使得库变得如此强大,以至于每个人都期望仅使用5行代码就可以预测人类的未来(如果你知道如何做到的话)。 - Imanol Luengo
一个全知的存在(即那个“知道如何”的人)甚至不需要五行代码就能预测人类的未来 :) - Anton Tykhyy
2个回答

5
简单来说,预测(也称为“评分”或“推理”)是通过仅运行输入的前向传递并收集每个输入向量的得分来实现的。这与测试的过程流程相同。不同之处在于模型使用的四个阶段:
1. 训练:从训练数据集中学习;根据需要调整权重。 2. 测试:评估模型的性能;如果准确性已经收敛,则停止训练。 3. 验证:评估训练模型的准确性。如果不符合接受标准,则更改一些内容并重新开始训练。 4. 预测:您已通过验证-发布模型供目标应用程序使用。
所有四个步骤都遵循相同的前向逻辑流程;训练包括反向传播;其他步骤则不包括。只需按照仅前向的流程进行操作,即可获得所需的结果形式。
我担心您的数据分区:仅将10%用于培训,90%用于测试,没有用于验证。更典型的分割比例是50-30-20或大致在该范围内。

5
不可以;Stack Overflow不是一个代码编写服务。我给了你解决问题的方法;你应该自己实现攻击。如果不行,就在那个具体的编程问题上发布一个问题。 - Prune
感谢您的评论。由于代码删除了时间列,我该如何预测1天后的值? - vaj oja
另外一个问题是,代码使用 parameters_to_input = ['open price', 'highest price', 'lowest price', 'close price','turnover', 'volume','mean price'] 中的参数来预测未来某一列(例如未来的收盘价)的值。但是,如果将来没有这些参数值,我该如何预测收盘价? - vaj oja
显然,你不会只训练模型预测下一天的结果,而是要训练模型以成对的值来预测接下来的两天。 - Prune
@Igor:Caffe中的功能流程是通过长时间间隔(例如1000次迭代)进行内部测试运行来训练,以指示收敛。但是,“测试”确实是一个超载的术语:预测/打分运行属于Caffe的“test”命令-因此您完全可以这样使用“test”。我所在的深度学习领域在部署期间不再使用“测试”一词。 - Prune
显示剩余2条评论

1

问题1:您应该更改LSTM参数,以返回一个大小为2的序列,这将是当天和第二天的预测。

问题2:很明显,您的模型欠拟合数据,在您10%的训练数据和90%的测试数据中非常明显!您应该像之前的回答建议的那样更加平衡比例。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接