为什么我用这个神经网络得到错误/不连贯的结果?

时间:2018-05-17 13:32:11

标签: python python-3.x tensorflow machine-learning neural-network

我正在努力创建一个神经网络来预测外汇货币对EURUSD的未来价值,了解过去16小时内的价值。

起初,我从2000年到2017年的每分钟都有价值。 要创建用于训练的标记数据,我已将这些分钟细分为960组,并按以下方式计算每个时期的标签:

为了对i 期间的标签进行校准,我从i + 1 期间获取数据并检查是否在i + 1 期间< / em>期间价格高于或低于i 期间最后一分钟价格的某个百分比。

简而言之,我有大约6300对标记数据,每个输入值为960,输出类别为3。 (头等舱价格上涨超过X,二等价格下跌超过X,三等价格保持在中间位置)

大约33%的训练数据属于第一类,另外33%属于第二类,最后33%属于第三类。

您可以在此处找到数据:https://ufile.io/m15fa

我的问题在于输出。我无法获得任何有用的预测。 在训练之后,每次执行脚本时,网络都会对同一类中的所有测试数据进行分类,这几乎会改变脚本的每次执行。

这里是代码:

import tensorflow as tf
import json

print("Loading data...")
f = open('out_x.txt', 'r')
input_data_x = json.load(f)
print("1/2 loaded...")
f = open('out_y.txt', 'r')
input_data_y = json.load(f)
print("Done loading data.")

# Parameters
learning_rate = 0.005
training_epochs = 10
batch_size = 10
num_examples = 5500
display_step = 1

print("------------------------------------")
print("learning_rate:",learning_rate)
print("training_epochs:",training_epochs)
print("batch_size:",batch_size)
print("num_examples:",num_examples)
print("data_x:",len(input_data_x))
print("data_y:",len(input_data_y))
print("------------------------------------")

# Network Parameters
n_input = 960
n_hidden_1 = 500 # 1st layer number of neurons
n_classes = 3 

# tf Graph input
X = tf.placeholder("float", [None, n_input])
Y = tf.placeholder("float", [None, n_classes])

# Store layers weight & bias
weights = {
    'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),
    'out': tf.Variable(tf.random_normal([n_hidden_1, n_classes]))
}
biases = {
    'b1': tf.Variable(tf.random_normal([n_hidden_1])),
    'out': tf.Variable(tf.random_normal([n_classes]))
}


# Create model
def multilayer_perceptron(x):
    # Hidden fully connected layer 
    layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])
    layer_1 = tf.nn.relu(layer_1)
    # Output fully connected layer with a neuron for each class
    out_layer = tf.matmul(layer_1, weights['out']) + biases['out']
    return out_layer

# Construct model
logits = multilayer_perceptron(X)

# Define loss asnd optimizer
loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
    logits=logits, labels=Y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
train_op = optimizer.minimize(loss_op)
# Initializing the variables
init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)

    # Training cycle
    for epoch in range(training_epochs):
        avg_cost = 0.
        total_batch = int(num_examples/batch_size)
        # Loop over all batches
        for i in range(total_batch):

            batch_x = input_data_x[i*batch_size : (i+1)*batch_size]
            batch_y = input_data_y[i*batch_size : (i+1)*batch_size]
            # Run optimization op (backprop) and cost op (to get loss value)
            _, c = sess.run([train_op, loss_op], feed_dict={X: batch_x,
                                                            Y: batch_y})
            # Compute average loss
            avg_cost += c / total_batch
        # Display logs per epoch step
        if epoch % display_step == 0:
            print("Epoch:", '%04d' % (epoch+1), "cost={:.9f}".format(avg_cost))
            # Test model
            pred = tf.nn.softmax(logits)  # Apply softmax to logits
            correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(Y, 1))
            # Calculate accuracy
            accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
            print("Accuracy:", accuracy.eval({X: input_data_x[total_batch*batch_size :], Y: input_data_y[total_batch*batch_size :]}))


    print("Optimization Finished!")

    # Test model
    pred = tf.nn.softmax(logits)  # Apply softmax to logits
    prediction = tf.argmax(pred, 1)
    # Calculate accuracy
    output= sess.run(prediction,feed_dict={X: input_data_x})


    # Not-so-beautiful-code to try to debug the problem
    # You can remove it

    i0 = 0
    i1 = 0
    i2 = 0

    for x in output:
        if x == 0: i0 +=1
        elif x == 1: i1 +=1
        elif x == 2: i2 +=1
        #else: print(x)
        print(x, end='')



    print(i0, i1, i2)       

请帮我解决这个问题

更新 我试图添加激活功能(relu,sigmoid)但没有成功。我还试图添加另一个隐藏层,但事情不会发生变化。

0 个答案:

没有答案