2017-07-06 66 views
0

我正在尝试学习Tensorflow。我正在做一个基本的例子 - 为方程y = x + 0.1建模,使用神经网络进行训练,然后进行预测。我实际上是采用S形方法(不理想),所以不使用标准的softmax/relu方式(这对我不起作用)。代码运行,但答案是错误的:批处理中的所有预测给出几乎相同的答案,如y_true = [[0.356],[0.356],[0.356],[0.356]],对于输入= [[0.1,0.2, 0.3,0.4]]。我究竟做错了什么?代码如下:Tensorflow-使用神经网络估计基本线性方程

import tensorflow as tf 
import numpy as np 

epochs = 1000 
# For equation y = b + 0.1, sample data below 
myImportedDatax_np = np.array([[.1],[.2],[.3],[.4]],dtype=float) 
myImportedDatay_np = np.array([[.2],[.3],[.4],[.5]],dtype=float) 

c = tf.constant(0.1, name='c') 
b = tf.placeholder(tf.float32, [None, 1], name='b') 
y = tf.add(b, c, name='y') 

y_true = tf.placeholder(tf.float32, [None, 1], name='y_true') 

W1 = tf.Variable(tf.random_normal([1, 3], stddev=0.03), name='W1') 
b1 = tf.Variable(tf.random_normal([3]), name='b1') 
W2 = tf.Variable(tf.random_normal([3, 1], stddev=0.03), name='W2') 
b2 = tf.Variable(tf.random_normal([1]), name='b2') 

hidden_out = tf.add(tf.matmul(b, W1), b1) 
hidden_out = tf.sigmoid(hidden_out) 

y_ = tf.sigmoid(tf.add(tf.matmul(hidden_out, W2), b2)) 

cost = tf.reduce_mean(tf.square(y_ - y_true)) 
optimiser = tf.train.GradientDescentOptimizer(0.005).minimize(cost) 

init_op = tf.initialize_all_variables() 

with tf.Session() as sess: 
    # initialise the variables 
    sess.run(init_op) 
    for epoch in range(epochs): 
     _, cost_now = sess.run([optimiser, cost], {b: myImportedDatax_np, y_true: myImportedDatay_np}) 
    print("Predicted values are:") 
    print(sess.run(y_, {b: myImportedDatax_np})) 

回答

2

有几件事情是你的代码错误:

  1. 你是一个回归问题,y = x + c,所以删除乙状结肠输出:

    y_ = tf.add(tf.matmul(hidden_out, W2), b2) 
    
  2. 单个隐藏层可以更好地为您服务,为您这么简单的任务您的多个隐藏单元将需要它训练更长的时间。

  3. 要处理2,增加你的时代到价值较高的说,万和你的学习速度也较高,比如0.1

编辑: 添加代码:

#increased the number of epoch 
epochs = 10000 
# For equation y = b + 0.1, sample data below 
myImportedDatax_np = np.array([[.1],[.2],[.3],[.4]],dtype=float) 
myImportedDatay_np = np.array([[.2],[.3],[.4],[.5]],dtype=float) 

c = tf.constant(0.1, name='c') 
b = tf.placeholder(tf.float32, [None, 1], name='b') 
y = tf.add(b, c, name='y') 

y_true = tf.placeholder(tf.float32, [None, 1], name='y_true') 

W1 = tf.Variable(tf.random_normal([1, 3], stddev=0.03), name='W1') 
b1 = tf.Variable(tf.random_normal([3]), name='b1') 
W2 = tf.Variable(tf.random_normal([3, 1], stddev=0.03), name='W2') 
b2 = tf.Variable(tf.random_normal([1]), name='b2') 

hidden_out = tf.add(tf.matmul(b, W1), b1) 
hidden_out = tf.sigmoid(hidden_out) 
# Removed the activation 
y_ = tf.add(tf.matmul(hidden_out, W2), b2) 

cost = tf.reduce_mean(tf.square(y_ - y_true) 

#changed the learning rate 
optimiser = tf.train.GradientDescentOptimizer(0.1).minimize(cost) 

init_op = tf.global_variables_initializer() 

#Predicted values are: 
#[[ 0.19917184] 
#[ 0.30153054] 
#[ 0.40164429] 
#[ 0.4976812 ]] 
+0

添加的代码中答案 –

+0

太棒了,它的工作原理。如你所说,巨大的差异在于大量的时代以及学习速度的提高。如果我在sigmoid中添加输出,结果可能相当不真实。 –