【问题标题】:How to predict new data using a trained simple feed forward neural network in tensorflow如何在 tensorflow 中使用经过训练的简单前馈神经网络预测新数据
【发布时间】:2017-09-01 06:46:29
【问题描述】:

如果这听起来像个愚蠢的问题,请原谅我。假设我有一个用形状为 [m, n] 的数据训练的神经网络,我如何用形状为 [1, 3] 的数据测试训练好的网络

这是我目前拥有的代码:

n_hidden_1 = 1024
n_hidden_2 = 1024
n = len(test_data[0]) - 1
m = len(test_data)

alpha = 0.005
training_epoch = 1000
display_epoch = 100

train_X = np.array([i[:-1:] for i in test_data]).astype('float32')
train_X = normalize_data(train_X)
train_Y = np.array([i[-1::] for i in test_data]).astype('float32')
train_Y = normalize_data(train_Y)

X = tf.placeholder(dtype=np.float32, shape=[m, n])
Y = tf.placeholder(dtype=np.float32, shape=[m, 1])

weights = {
    'h1': tf.Variable(tf.random_normal([n, n_hidden_1])),
    'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),
    'out': tf.Variable(tf.random_normal([n_hidden_2, 1]))
}
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([1])),
}

layer_1 = tf.add(tf.matmul(X, weights['h1']), biases['b1'])
layer_1 = tf.nn.sigmoid(layer_1)
layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])
layer_2 = tf.nn.sigmoid(layer_2)

activation = tf.matmul(layer_2, weights['out']) + biases['out']
cost = tf.reduce_sum(tf.square(activation - Y)) / (2 * m)
optimizer = tf.train.GradientDescentOptimizer(alpha).minimize(cost)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for epoch in range(training_epoch):
        sess.run([optimizer, cost], feed_dict={X: train_X, Y: train_Y})
        cost_ = sess.run(cost, feed_dict={X: train_X, Y: train_Y})
        if epoch % display_epoch == 0:
            print('Epoch:', epoch, 'Cost:', cost_)

如何测试新数据?对于回归,我知道我可以对数据使用类似的东西[0.4, 0.5, 0.1]

predict_x = np.array([0.4, 0.5, 0.1], dtype=np.float32).reshape([1, 3])
predict_x = (predict_x - mean) / std
predict_y = tf.add(tf.matmul(predict_x, W), b)
result = sess.run(predict_y).flatten()[0]

我如何对神经网络做同样的事情?

【问题讨论】:

  • 尺寸[m, n] 代表什么? m 的样本数和n 的特征数是多少?
  • @kaufmanu 是的 720 by 3

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


【解决方案1】:

如果你使用

X = tf.placeholder(dtype=np.float32, shape=[None, n])
Y = tf.placeholder(dtype=np.float32, shape=[None, 1])

这两个占位符的第一个维度将具有可变大小,即在训练时(例如 720)与测试时(例如 1)可能不同。这通常被称为具有“可变批量大小”,因为在训练和测试期间具有不同批量大小是很常见的。

在这一行:

cost = tf.reduce_sum(tf.square(activation - Y)) / (2 * m)

您正在使用m,它现在是可变的。要使这条线适用于可变批量大小(因为 m 在执行图表之前现在是未知的),您应该执行以下操作:

m = tf.shape(X)[0]
cost = tf.reduce_sum(tf.square(activation - Y)) / (tf.multiply(m, 2))

tf.shape 评估 X 的动态形状,即它在运行时的形状。

【讨论】:

    猜你喜欢
    • 2021-01-14
    • 2015-06-04
    • 1970-01-01
    • 2017-05-23
    • 2020-03-15
    • 1970-01-01
    • 1970-01-01
    • 2020-09-10
    • 2018-11-15
    相关资源
    最近更新 更多