我想在 tensorflow 中使用外部优化器接口来使用牛顿优化器,因为 tf.train 只有一阶梯度下降优化器。同时,我想使用 tf.keras.layers 构建我的网络,因为在构建大型复杂网络时,它比使用 tf.Variables 更容易。我将通过以下简单的一维线性回归示例展示我的问题:
import tensorflow as tf
from tensorflow.keras import backend as K
import numpy as np
#generate data
no = 100
data_x = np.linspace(0,1,no)
data_y = 2 * data_x + 2 + np.random.uniform(-0.5,0.5,no)
data_y = data_y.reshape(no,1)
data_x = data_x.reshape(no,1)
# Make model using keras layers and train
x = tf.placeholder(dtype=tf.float32, shape=[None,1])
y = tf.placeholder(dtype=tf.float32, shape=[None,1])
output = tf.keras.layers.Dense(1, activation=None)(x)
loss = tf.losses.mean_squared_error(data_y, output)
optimizer = tf.contrib.opt.ScipyOptimizerInterface(loss, method="L-BFGS-B")
sess = K.get_session()
sess.run(tf.global_variables_initializer())
tf_dict = {x : data_x, y : data_y}
optimizer.minimize(sess, feed_dict = tf_dict, fetches=[loss], loss_callback=lambda x: print("Loss:", x))
运行它时,损失根本没有改变。当使用 tf.train 中的任何其他优化器时,它工作正常。此外,当使用 tf.layers.Dense() 而不是 tf.keras.layers.Dense() 时,它确实可以使用 ScipyOptimizerInterface。所以真正的问题是 tf.keras.layers.Dense() 和 tf.layers.Dense() 之间有什么区别。我看到 tf.layers.Dense() 创建的变量是 tf.float32_ref 类型,而 tf.keras.layers.Dense() 创建的变量是 tf.float32 类型。就我现在而言,_ref 表明这个张量是可变的。所以也许这就是问题所在?但是话又说回来,来自 tf.train 的任何其他优化器都可以与 keras 层一起正常工作。
谢谢