TensorFlow 中的基本神经网络

Basic neural network in TensorFlow

我正在尝试在 TensorFlow 中实现一个非常基本的神经网络,但我遇到了一些问题。这是一个非常基本的网络,它以值(小时数或睡眠时间和学习时间)作为输入并预测测试分数(我在 you-tube 上找到了这个例子)。所以基本上我只有一个包含三个单元的隐藏层,每个单元计算一个激活函数(sigmoid),成本函数是误差平方和,我使用梯度下降来最小化它。所以问题是,当我用训练数据训练网络并尝试使用相同的训练数据进行一些预测时,结果并不完全匹配,而且它们看起来也很奇怪,因为看起来彼此相同。

import tensorflow as tf
import numpy as np
import input_data

sess = tf.InteractiveSession()

# create a 2-D version of input for plotting
trX = np.matrix(([3,5], [5,1],[10,2]), dtype=float)
trY = np.matrix(([85], [82], [93]), dtype=float) # 3X1 matrix
trX = trX / np.max(trX, axis=0)
trY = trY / 100 # 100 is the maximum score allowed

teX = np.matrix(([3,5]), dtype=float)
teY = np.matrix(([85]), dtype=float)
teX = teX/np.amax(teX, axis=0)
teY = teY/100

def init_weights(shape):
    return tf.Variable(tf.random_normal(shape, stddev=0.01))

def model(X, w_h, w_o):
    z2 = tf.matmul(X, w_h)
    a2 = tf.nn.sigmoid(z2) # this is a basic mlp, think 2 stacked logistic regressions
    z3 = tf.matmul(a2, w_o)
    yHat = tf.nn.sigmoid(z3)
    return yHat # note that we dont take the softmax at the end because our cost fn does that for us

X = tf.placeholder("float", [None, 2])
Y = tf.placeholder("float", [None, 1])

W1 = init_weights([2, 3]) # create symbolic variables
W2 = init_weights([3, 1])

sess.run(tf.initialize_all_variables())

py_x = model(X, W1, W2)

cost = tf.reduce_mean(tf.square(py_x - Y))
train_op = tf.train.GradientDescentOptimizer(0.5).minimize(cost) # construct an optimizer
predict_op = py_x

sess.run(train_op, feed_dict={X: trX, Y: trY})

print sess.run(predict_op, feed_dict={X: trX})

sess.close()

它产生:

[[ 0.51873487] [ 0.51874501] [ 0.51873082]]

相信应该和训练数据结果差不多。

我对神经网络和机器学习还很陌生,所以请原谅我的任何错误,提前致谢。

你的网络没有训练的主要原因是声明:

sess.run(train_op, feed_dict={X: trX, Y: trY})

…只执行一次。在 TensorFlow 中,运行 train_op(或从 Optimizer.minimize() 返回的任何操作只会使网络采取单个梯度下降步骤。您应该在循环中执行它以执行迭代训练,并且权重最终会收敛。

其他两个提示:(i) 如果在每个步骤中输入训练数据的 子集 而不是整个数据集,则可能会实现更快的收敛; (ii) 0.5 的学习率可能太高了(尽管这取决于数据)。