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))
我試過不同的優化器,學習率和測試大小。但似乎沒有任何工作。有任何想法嗎?
時代的數量看起來太多了。相反,你應該嘗試100或者什麼的。 – tagoma
在此行嘗試'reduce_mean'而不是'reduce_sum' cost = -1。 * tf.reduce_sum(y * tf.log(model)+(1. - y)*(1. - tf.log(model)))' –
將'reduce_sum'改爲'reduce_mean'沒有幫助,但是減少時代的數量確實如此。離奇。謝謝,愛德華!如果您將評論發佈爲回覆,我會將其標記爲答案。 – user934904