我已经使用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))
我尝试了不同的优化器,学习率和测试规模。但是似乎没有任何作用。有任何想法吗?
最佳答案
您可以使用标准偏差1初始化m
和b
,但是对于数据x
和y
,可以预期m
显着小于1。可以将b
初始化为零(这是和m
的标准偏差要小得多(例如0.0005),并且同时降低学习率(例如降至0.00000005)。您可以延迟更改这些值的NaN值,但是它们可能最终会出现,因为我认为您的数据不能由线性函数很好地描述。
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()
关于machine-learning - 无法使简单的二进制分类器工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45525264/