0

我正在使用 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.
4

1 回答 1

0

tf.slice会做。并且在优化期间,w1将添加梯度(因为梯度在分叉处相加)。另外,请查看 Tensorboard 上的图表(有关如何使用它的链接)。

于 2018-01-01T04:37:30.127 回答