tf.sigmoid() 用于较大值时溢出
tf.sigmoid() overflow when used for bigger values
我一直在尝试使用我在 Matlab 中学到的张量流在 python 中制作单变量逻辑回归模型(Andrew ng 在 Coursera 上的 ML 课程)。该模型收敛,但仅当初始 theta0 nad theta1 变量定义为较小(约 1.00)时,但 returns 如果初始值设置为 100.00,则收敛值为 nan。
当学习率增加时也会发生同样的事情。
python代码是
import tensorflow as tf
import numpy as np
import os
import matplotlib.pyplot as plt
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
epoch = 100000
x_data = (np.random.rand(100)*100).astype(np.float64)
y_data = np.vectorize(lambda y: 0.00 if y < 50.00 else 1.00)(x_data)
theta0 = tf.Variable(1, dtype=tf.float64)
theta1 = tf.Variable(-1, dtype=tf.float64)
hypothesis = theta0 + (theta1 * x_data)
hypothesis = tf.sigmoid(hypothesis)
term1 = -(y_data * tf.log(hypothesis))
term2 = -((1-y_data) * tf.log(1-hypothesis))
loss = tf.reduce_mean(term1 + term2)
optimizer = tf.train.GradientDescentOptimizer(0.006).minimize(loss)
init_var = tf.global_variables_initializer()
train_data = []
with tf.Session() as sess:
sess.run(init_var)
for i in range(epoch):
train_data.append(sess.run([optimizer, theta0, theta1, loss])[1:])
if i%100==0:
print("Epoch ", i, ":", sess.run([theta0, theta1, loss]))
对于所描述的代码行为的解释和更正,或者甚至是针对上述目的的更好的代码,我们将不胜感激。
你应该使用 tf.nn.sigmoid_cross_entropy_with_logits
而不是使用 sigmoid 然后做一个日志来计算损失。 sigmoid_cross_entropy_with_logits 有一些内部逻辑来帮助防止数值 underflow/overflow.
我一直在尝试使用我在 Matlab 中学到的张量流在 python 中制作单变量逻辑回归模型(Andrew ng 在 Coursera 上的 ML 课程)。该模型收敛,但仅当初始 theta0 nad theta1 变量定义为较小(约 1.00)时,但 returns 如果初始值设置为 100.00,则收敛值为 nan。 当学习率增加时也会发生同样的事情。 python代码是
import tensorflow as tf
import numpy as np
import os
import matplotlib.pyplot as plt
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
epoch = 100000
x_data = (np.random.rand(100)*100).astype(np.float64)
y_data = np.vectorize(lambda y: 0.00 if y < 50.00 else 1.00)(x_data)
theta0 = tf.Variable(1, dtype=tf.float64)
theta1 = tf.Variable(-1, dtype=tf.float64)
hypothesis = theta0 + (theta1 * x_data)
hypothesis = tf.sigmoid(hypothesis)
term1 = -(y_data * tf.log(hypothesis))
term2 = -((1-y_data) * tf.log(1-hypothesis))
loss = tf.reduce_mean(term1 + term2)
optimizer = tf.train.GradientDescentOptimizer(0.006).minimize(loss)
init_var = tf.global_variables_initializer()
train_data = []
with tf.Session() as sess:
sess.run(init_var)
for i in range(epoch):
train_data.append(sess.run([optimizer, theta0, theta1, loss])[1:])
if i%100==0:
print("Epoch ", i, ":", sess.run([theta0, theta1, loss]))
对于所描述的代码行为的解释和更正,或者甚至是针对上述目的的更好的代码,我们将不胜感激。
你应该使用 tf.nn.sigmoid_cross_entropy_with_logits
而不是使用 sigmoid 然后做一个日志来计算损失。 sigmoid_cross_entropy_with_logits 有一些内部逻辑来帮助防止数值 underflow/overflow.