【问题标题】:Add Custom Regularization to Tensorflow将自定义正则化添加到 TensorFlow
【发布时间】:2018-06-11 06:40:02
【问题描述】:

我正在使用 tensorflow 优化一个简单的最小二乘目标函数,如下所示:

这里,Y 是目标向量,X 是输入矩阵,向量w 表示要学习的权重。

示例场景:

如果我想增加初始目标函数以对w1 施加额外的约束(张量流变量wX1 中的第一个标量值代表特征矩阵X 的第一列),我将如何在张量流中实现这一点?

我能想到的一个解决方案是使用 tf.slice 来索引 $w$ 的第一个值,并将其添加到原始成本项之外,但我不相信它会对权重产生预期的影响。

我希望能提供有关在 tensorflow 中是否可以实现这样的事情的意见,如果可以,实现这一点的最佳方法可能是什么?

另一种选择是添加权重约束,并使用增强的拉格朗日目标来实现,但我想先探索正则化选项,然后再采用拉格朗日路线。

我对初始目标函数的当前代码没有额外的正则化如下:

train_x ,train_y are the training data, training targets respectively.
test_x  , test_y are the testing data, testing targets respectively.

#Sum of Squared Errs. Cost.
def costfunc(predicted,actual):
    return tf.reduce_sum(tf.square(predicted - actual))

#Mean Squared Error Calc.
def prediction(sess,X,y_,test_x,test_y):
    pred_y = sess.run(y_,feed_dict={X:test_x})
    mymse = tf.reduce_mean(tf.square(pred_y - test_y))
    mseval=sess.run(mymse)

    return mseval,pred_y


with tf.Session() as sess:

    X = tf.placeholder(tf.float32,[None,num_feat])  #Training Data 
    Y = tf.placeholder(tf.float32,[None,1]) #  Target Values 
    W = tf.Variable(tf.ones([num_feat,1]),name="weights")  

    init = tf.global_variables_initializer()

    sess.run(init)

    #Tensorflow ops and cost function definitions.
    y_ = tf.matmul(X,W) 
    cost_history = np.empty(shape=[1],dtype=float)
    out_of_sample_cost_history = np.empty(shape=[1],dtype=float)
    cost=costfunc(y_,Y) 
    learning_rate = 0.000001
    training_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)


    for epoch in range(training_epochs):
        sess.run(training_step,feed_dict={X:train_x,Y:train_y})
        cost_history = np.append(cost_history,sess.run(cost,feed_dict={X: train_x,Y: train_y}))
        out_of_sample_cost_history = np.append(out_of_sample_cost_history,sess.run(cost,feed_dict={X:test_x,Y:test_y}))


    MSETest,pred_test = prediction(sess,X,y_,test_x,test_y) #Predict on full testing set.

【问题讨论】:

    标签: python optimization tensorflow regression regularized


    【解决方案1】:

    tf.slice 可以。在优化过程中,w1 的梯度将被添加(因为梯度在分叉处相加)。另外,请查看 Tensorboard 上的图表(link 了解如何使用它)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-12
      • 2016-09-03
      • 1970-01-01
      • 1970-01-01
      • 2020-04-30
      相关资源
      最近更新 更多