将自定义规则化添加到Tensorflow

时间:2017-12-31 22:26:47

标签: python optimization tensorflow regression regularized

我正在使用张量流来优化简单的最小二乘目标函数,如下所示:

enter image description here

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

示例场景:

enter image description hereenter image description hereenter image description here

如果我想扩充初始目标函数以对w1施加额外约束(张量流变量w中的第一个标量值,X1表示要素的第一列矩阵X),我如何在tensorflow中实现这一点?

enter image description here

我能想到的一个解决方案是使用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.

1 个答案:

答案 0 :(得分:0)

tf.slice会这样做。在优化过程中,将添加w1的渐变(因为渐变在叉子处加起来)。另外,请检查Tensorboard上的图表(link如何使用它。)