gpt4 book ai didi

machine-learning - 无法让简单的二元分类器工作

转载 作者:行者123 更新时间:2023-11-30 09:50:46 25 4
gpt4 key购买 nike

我使用 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 初始化 mb,但是对于您的数据 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()

关于machine-learning - 无法让简单的二元分类器工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45525264/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com