首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >输入到tensorflow in_top_k应该是1级还是2级?

输入到tensorflow in_top_k应该是1级还是2级?
EN

Stack Overflow用户
提问于 2018-10-10 04:12:01
回答 1查看 986关注 0票数 1

我试着用in_top_k函数做实验,看看这个函数到底在做什么。但我发现了一些令人困惑的行为。

首先,我编写了如下代码

代码语言:javascript
复制
import numpy as np
import tensorflow as tf

target = tf.constant(np.random.randint(2, size=30).reshape(30,-1), dtype=tf.int32, name="target")
pred = tf.constant(np.random.rand(30,1), dtype=tf.float32, name="pred")
result = tf.nn.in_top_k(pred, target, 1)

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    targetVal = target.eval()
    predVal = pred.eval()
    resultVal = result.eval()

然后生成以下错误:

代码语言:javascript
复制
ValueError: Shape must be rank 1 but is rank 2 for 'in_top_k/InTopKV2' (op: 'InTopKV2') with input shapes: [30,1], [30,1], [].

然后我把代码更改为

代码语言:javascript
复制
import numpy as np
import tensorflow as tf
target = tf.constant(np.random.randint(2, size=30), dtype=tf.int32, name="target")
pred = tf.constant(np.random.rand(30,1).reshape(-1), dtype=tf.float32, name="pred")
result = tf.nn.in_top_k(pred, target, 1)

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    targetVal = target.eval()
    predVal = pred.eval()
    resultVal = result.eval()

但现在错误变成了

代码语言:javascript
复制
ValueError: Shape must be rank 2 but is rank 1 for 'in_top_k/InTopKV2' (op: 'InTopKV2') with input shapes: [30], [30], [].

那么输入是1级还是2级呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-10 05:33:43

对于in_top_ktargets需要为1级(类指数)和predictions级别2(每个类的分数)。这可以很容易地看到从医生那里

这意味着这两条错误消息实际上每次都会抱怨不同的输入(目标是第一次,预测是第二次)。无论哪种方式,下面的片段应该更类似于它:

代码语言:javascript
复制
import numpy as np
import tensorflow as tf

target = tf.constant(np.random.randint(2, size=30), dtype=tf.int32, name="target")
pred = tf.constant(np.random.rand(30,1), dtype=tf.float32, name="pred")
result = tf.nn.in_top_k(pred, target, 1)

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    targetVal = target.eval()
    predVal = pred.eval()
    resultVal = result.eval()

在这里,我们基本上结合了“两个片段的优点”:第一个片段的预测和第二个片段中的目标。然而,就我理解文档的方式而言,即使对于二进制分类,我们也需要两个预测值,每个类一个。所以就像

代码语言:javascript
复制
import numpy as np
import tensorflow as tf

target = tf.constant(np.random.randint(2, size=30), dtype=tf.int32, name="target")
pred = tf.constant(np.random.rand(30,1), dtype=tf.float32, name="pred")
pred = tf.concat((1-pred, pred), axis=1)
result = tf.nn.in_top_k(pred, target, 1)

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    targetVal = target.eval()
    predVal = pred.eval()
    resultVal = result.eval()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52732523

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档