简体   繁体   English

在TensorFlow中修改成本函数

[英]Modifying the cost function in TensorFlow

I want to modify the following cost function in a way that it adds extra weight to the samples where the prediction is higher than the true output! 我想修改以下成本函数,以便为预测高于真实输出的样本增加额外的权重!

cost = tf.reduce_sum(tf.pow(logits-Y, 2))/(2*batch_size) 成本= tf.reduce_sum(tf.pow(logits-Y,2))/(2 * batch_size)

I found it to be tricky in Tensorflow operations! 我在Tensorflow操作中发现它很棘手! I want to use Tensorflow operations to do the following codes (written by numpy): 我想使用Tensorflow操作执行以下代码(由numpy编写):

batch_szie = 100
label = np.random.normal(size=batch_szie)
cost = (np.sum(np.power((2*label [label >=0]),2)) + np.sum(np.power((2*label [label <0]),2)))/batch_szie 

Please note that the first two lines are just for simulating the label = logits-Y . 请注意,前两行仅用于模拟label = logits-Y

Any help/suggestion? 任何帮助/建议吗? Thanks :) 谢谢 :)

Here I found an answer to this question. 在这里,我找到了这个问题的答案。 However, I think there should be easier and more concise ways. 但是,我认为应该有更简单,更简洁的方法。

batch_size = 4
labels = tf.constant ([1,-1,2,1])
pos_index = tf.where(tf.greater_equal(labels, 0))
pos_index = tf.reshape(pos_index, [-1])
pos_label = 5 * tf.gather(labels, pos_index)
neg_index = tf.where(tf.less_equal(labels, 0))
neg_index = tf.reshape(neg_index, [-1])
neg_label = tf.gather(labels, neg_index)
cost = (tf.reduce_sum(tf.pow(pos_label, 2)) + tf.reduce_sum(tf.pow(neg_label, 2)))/(2*batch_size)
with tf.Session() as sess:
     print(sess.run(cost))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM