1

您好,这是我第一次使用 tensorflow,我尝试调整此处的示例TensorFlow-Examples以将此代码用于波士顿数据库的回归问题。基本上,我只更改成本函数、数据库、输入数和目标数,但是当我运行 MPL 时不会收敛(我使用非常低的速率)。我用亚当优化和下降梯度优化对其进行测试,但我有相同的行为。我很感激你的建议和想法......!!!

观察:当我在没有上述修改的情况下运行这个程序时,成本函数值总是降低。

这里是我运行模型时的演变,即使学习率非常低,成本函数也会振荡。在最坏的情况下,我希望模型收敛到一个值,例如 epoch 944 显示一个值 0.2267548,如果没有其他更好的值是find 那么这个值必须一直保持到优化完成。

纪元:0942 成本= 0.445707272

纪元:0943 成本= 0.389314095

纪元:0944 成本= 0.226754842

纪元:0945 成本= 0.404150135

纪元:0946 成本= 0.382190095

纪元:0947 成本= 0.897880572

纪元:0948 成本= 0.481954243

纪元:0949 成本= 0.269408980

纪元:0950 成本= 0.427961614

纪元:0951 成本= 1.206053280

纪元:0952 成本= 0.834200084

from __future__ import print_function

# Import MNIST data
#from tensorflow.examples.tutorials.mnist import input_data
#mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)

import tensorflow as tf
import  ToolInputData as input_data

ALL_DATA_FILE_NAME = "boston_normalized.csv"



##Load complete database, then this database is splitted in training,   validation and test set
completedDatabase = input_data.Databases(databaseFileName=ALL_DATA_FILE_NAME,     targetLabel="MEDV", trainPercentage=0.70, valPercentage=0.20, testPercentage=0.10,
                  randomState=42, inputdataShuffle=True, batchDataShuffle=True)


# Parameters
learning_rate = 0.0001
training_epochs = 1000
batch_size = 5
display_step = 1

# Network Parameters
n_hidden_1 = 10 # 1st layer number of neurons
n_hidden_2 = 10 # 2nd layer number of neurons

n_input = 13 # number of features of my database
n_classes = 1 # one target value (float)

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


# Create model
def multilayer_perceptron(x, weights, biases):
    # Hidden layer with RELU activation
    layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])
    layer_1 = tf.nn.relu(layer_1)
    # Hidden layer with RELU activation
    layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])
    layer_2 = tf.nn.relu(layer_2)
    # Output layer with linear activation
    out_layer = tf.matmul(layer_2, weights['out']) + biases['out']
   return out_layer

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

# Construct model
pred = multilayer_perceptron(x, weights, biases)

# Define loss and optimizer
cost = tf.reduce_mean(tf.square(pred-y))
#cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y))
optimizer =  tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)

# Initializing the variables
init = tf.initialize_all_variables()

# Launch the graph
with tf.Session() as sess:
    sess.run(init)

    # Training cycle
    for epoch in range(training_epochs):
        avg_cost = 0.
        total_batch = int(completedDatabase.train.num_examples/batch_size)
        # Loop over all batches
        for i in range(total_batch):
            batch_x, batch_y = completedDatabase.train.next_batch(batch_size)
            # Run optimization op (backprop) and cost op (to get loss value)
            _, c = sess.run([optimizer, cost], 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))
    print("Optimization Finished!")    
4

2 回答 2

0

几点。

你的模型很浅,只有两层。当然,您需要更多数据来训练更大的模型,所以我不知道您在波士顿数据集中有多少数据。

你的标签是什么?这将更好地告知平方误差是否更适合您的模型。

你的学习率也很低。

于 2016-10-06T16:03:04.720 回答
0

您说您的标签在 [0,1] 范围内,但我看不到预测在同一范围内。为了使它们与标签具有可比性,您应该在返回之前将它们转换为相同的范围,例如使用 sigmoid 函数:

out_layer = tf.matmul(...)
out = tf.sigmoid(out_layer)
return out

也许这可以解决稳定性问题。您可能还想稍微增加批量大小,例如每批 20 个示例。如果这提高了性能,您可能可以稍微提高学习率。

于 2017-04-23T17:27:24.237 回答