をTensorflowするカスタム正則を追加します。は、私は次のような単純な最小二乗目的関数を最適化するためにtensorflowを使用しています
ここを、Y
がターゲットベクトルで、X
は、入力行列とベクトルw
を表しています学習されるべき重み。
シナリオ例:
、、Iはtensorflow変数w
にw1
(最初のスカラ値に追加の制約を課すこと初期目的関数を増強したい場合
とX1
が表しますフィーチャマトリックスX
の最初の列)、テンソルフローでこれをどのように達成できますか?私は考えることができる
一つの解決策は、インデックスにW $ $の最初の値をtf.sliceを使用すると、元のコストの用語に加えて、これを追加することですが、私はそれを持っていると確信していないです重みに対する所望の効果。
このような何かがテンソルフローで可能かどうかについては、私は感謝しています。もしそうなら、これを実装する最良の方法は何でしょうか?
代替のオプションは、ウェイト制約を追加し、拡張ラグランジュの目的を使用することですが、ラグランジアンルートに進む前に正規化オプションを最初に調べることができます。
追加正則なしで初期の目的関数のための私が持っている現在のコードは以下の通りです:
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.