【发布时间】:2016-02-16 16:21:37
【问题描述】:
作为一个玩具示例,我试图从 100 个无噪声数据点拟合函数 f(x) = 1/x。 matlab 默认实现非常成功,均方差约为 10^-10,并且插值完美。
我实现了一个包含 10 个 sigmoid 神经元的隐藏层的神经网络。我是神经网络的初学者,所以要提防愚蠢的代码。
import tensorflow as tf
import numpy as np
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
#Can't make tensorflow consume ordinary lists unless they're parsed to ndarray
def toNd(lst):
lgt = len(lst)
x = np.zeros((1, lgt), dtype='float32')
for i in range(0, lgt):
x[0,i] = lst[i]
return x
xBasic = np.linspace(0.2, 0.8, 101)
xTrain = toNd(xBasic)
yTrain = toNd(map(lambda x: 1/x, xBasic))
x = tf.placeholder("float", [1,None])
hiddenDim = 10
b = bias_variable([hiddenDim,1])
W = weight_variable([hiddenDim, 1])
b2 = bias_variable([1])
W2 = weight_variable([1, hiddenDim])
hidden = tf.nn.sigmoid(tf.matmul(W, x) + b)
y = tf.matmul(W2, hidden) + b2
# Minimize the squared errors.
loss = tf.reduce_mean(tf.square(y - yTrain))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
# For initializing the variables.
init = tf.initialize_all_variables()
# Launch the graph
sess = tf.Session()
sess.run(init)
for step in xrange(0, 4001):
train.run({x: xTrain}, sess)
if step % 500 == 0:
print loss.eval({x: xTrain}, sess)
均方差以 ~2*10^-3 结束,因此比 matlab 差大约 7 个数量级。可视化
xTest = np.linspace(0.2, 0.8, 1001)
yTest = y.eval({x:toNd(xTest)}, sess)
import matplotlib.pyplot as plt
plt.plot(xTest,yTest.transpose().tolist())
plt.plot(xTest,map(lambda x: 1/x, xTest))
plt.show()
我们可以看到拟合在系统上是不完美的: 而 matlab 用肉眼看起来很完美,差异均匀 我试图用 TensorFlow 复制 Matlab 网络的图表:
顺便说一句,该图似乎暗示了一个 tanh 而不是 sigmoid 激活函数。可以确定的是,我在文档中的任何地方都找不到它。但是,当我尝试在 TensorFlow 中使用 tanh 神经元时,拟合很快就会失败,变量为 nan。我不知道为什么。
Matlab 使用 Levenberg–Marquardt 训练算法。贝叶斯正则化在均方为 10^-12 的情况下更加成功(我们可能处于浮点算术的领域)。
为什么 TensorFlow 实现如此糟糕,我能做些什么来让它变得更好?
【问题讨论】:
-
我还没有研究过张量流,对此很抱歉,但是你正在用
toNd函数做一些奇怪的事情。np.linspace已经返回一个ndarray,而不是一个列表,如果你想将一个列表转换为一个ndarray,你需要做的就是np.array(my_list),如果你只需要额外的轴,你可以做new_array = my_array[np.newaxis, :]。它可能只是没有达到零错误,因为它应该这样做。大多数数据都有噪音,你不一定希望它的训练误差为零。从“reduce_mean”判断,它可能使用了交叉验证。 -
@AdamAcosta
toNd绝对是我缺乏经验的权宜之计。我之前试过np.array,问题似乎是np.array([5,7]).shape是(2,)而不是(2,1)。my_array[np.newaxis, :]似乎纠正了这一点,谢谢!我不使用 python,而是每天使用 F#。 -
@AdamAcostaI 我不认为
reduce_mean进行交叉验证。来自文档:Computes the mean of elements across dimensions of a tensor。 Matlab 进行交叉验证,在我看来,与没有交叉验证相比,这应该会降低训练样本的拟合度,对吗? -
是的,交叉验证通常会阻止完美匹配。很抱歉没有真正的答案。张量流的知识仍然很少。我最近看到很多关于它的问题,但没有太多答案。 Udacity 正在开发一门关于它的课程,作为他们新的机器学习工程师纳米学位的一部分。我发誓我不为 Udacity 工作,但它可能值得研究!
标签: python matlab neural-network tensorflow