2017-08-05 15 views
0

我已经使用TensorFlow编写了一个简单的二元分类器。但是,我得到的优化变量的唯一结果是NaN。这里的代码:无法获得简单的二元分类器

import tensorflow as tf 

# Input values 
x = tf.range(0., 40.) 
y = tf.constant([0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 
       1., 0., 0., 1., 0., 1., 0., 1., 1., 1., 
       1., 1., 0., 1., 1., 1., 0., 1., 1., 1., 
       1., 1., 1., 0., 1., 1., 1., 1., 1., 1.]) 

# Variables 
m = tf.Variable(tf.random_normal([])) 
b = tf.Variable(tf.random_normal([])) 

# Model and cost 
model = tf.nn.sigmoid(tf.add(tf.multiply(x, m), b)) 
cost = -1. * tf.reduce_sum(y * tf.log(model) + (1. - y) * (1. - tf.log(model))) 

# Optimizer 
learn_rate = 0.05 
num_epochs = 20000 
optimizer = tf.train.GradientDescentOptimizer(learn_rate).minimize(cost) 

# Initialize variables 
init = tf.global_variables_initializer() 

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

    # Fit all training data 
    for epoch in range(num_epochs): 
     sess.run(optimizer) 

    # Display results 
    print("m =", sess.run(m)) 
    print("b =", sess.run(b)) 

我试过不同的优化器,学习率和测试大小。但似乎没有任何工作。有任何想法吗?

+0

时代的数量看起来太多了。相反,你应该尝试100或者什么的。 – tagoma

+0

在此行尝试'reduce_mean'而不是'reduce_sum' cost = -1。 * tf.reduce_sum(y * tf.log(model)+(1. - y)*(1. - tf.log(model)))' –

+0

将'reduce_sum'改为'reduce_mean'没有帮助,但是减少时代的数量确实如此。离奇。谢谢,爱德华!如果您将评论发布为回复,我会将其标记为答案。 – user934904

回答

1

您初始化mb与标准偏差为1,但对于你的数据xy,你可以期望m比1显著小可以初始化b为零(这是很受欢迎的偏差项)和m具有小得多的标准偏差(例如0.0005)并且同时降低学习速率(例如到0.00000005)。你可以延迟NaN值改变这些值,但它们最终可能会发生,因为你的数据在我看来并没有被线性函数所描述。 plot

import tensorflow as tf 
import matplotlib.pyplot as plt 

# Input values 
x = tf.range(0., 40.) 
y = tf.constant([0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 
        1., 0., 0., 1., 0., 1., 0., 1., 1., 1., 
             1., 1., 0., 1., 1., 1., 0., 1., 1., 1., 
                 1., 1., 1., 0., 1., 1., 
                 1., 1., 1., 1.]) 

# Variables 
m = tf.Variable(tf.random_normal([], mean=0.0, stddev=0.0005)) 
b = tf.Variable(tf.zeros([])) 

# Model and cost 
model = tf.nn.sigmoid(tf.add(tf.multiply(x, m), b)) 
cost = -1. * tf.reduce_sum(y * tf.log(model) + (1. - y) * (1. - tf.log(model))) 

# Optimizer 
learn_rate = 0.00000005 
num_epochs = 20000 
optimizer = tf.train.GradientDescentOptimizer(learn_rate).minimize(cost) 

# Initialize variables 
init = tf.global_variables_initializer() 

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

    # Fit all training data 
    for epoch in range(num_epochs): 
     _, xs, ys = sess.run([optimizer, x, y]) 

    ms = sess.run(m) 
    bs = sess.run(b) 
    print(ms, bs) 
plt.plot(xs,ys) 
plt.plot(xs, ms * xs + bs) 
plt.savefig('tf_test.png') 
plt.show() 
plt.clf()