请问topk接口如何设置动态变化的k值?
环境
- PaddlePaddle 1.4.1
- Python 3.5
- Ubuntu 16.04
问题
我项目中需要统计有意义的标签的数据,然后再求topk 的,但是topk的k值好像不能设置变量,如下代码,我该如何操作?
def cls_ohem2(label):
# 真实标签对应的概率
zeros = np.zeros_like(label, dtype=np.float32)
ones = np.ones_like(label, dtype=np.float32)
# 统计neg和pos的数量
valid_inds = np.where(label < zeros, zeros, ones)
num_valid = np.sum(valid_inds)
# 选取70%的数据
num_keep_radio = 0.7
keep_num = np.array(num_valid * num_keep_radio).astype(np.int32)
print(keep_num)
return keep_num
keep_num = create_tmp_var(name='keep_num', dtype='int32', shape=[1])
keep_num = fluid.layers.py_func(func=cls_ohem2, x=[label], out=[keep_num])
keep_num = fluid.layers.cast(keep_num, dtype='float32')
loss, _ = fluid.layers.topk(input=loss, k=keep_num)
loss = fluid.layers.reduce_mean(loss)
topk 支持variable,你的keep_num被cast为float32的,k应该是int类型的
@zhaoyuchen2018 我这样转换了
def cls_ohem2(label):
# 真实标签对应的概率
zeros = np.zeros_like(label, dtype=np.float32)
ones = np.ones_like(label, dtype=np.float32)
# 统计neg和pos的数量
valid_inds = np.where(label < zeros, zeros, ones)
num_valid = np.sum(valid_inds)
# 选取70%的数据
num_keep_radio = 0.7
keep_num = np.array(num_valid * num_keep_radio).astype(np.int32)
print(keep_num)
return keep_num
keep_num = create_tmp_var(name='keep_num', dtype='int32', shape=[1])
keep_num = fluid.layers.py_func(func=cls_ohem2, x=[label], out=[keep_num])
keep_num = fluid.layers.cast(keep_num, dtype='int64')
loss, _ = fluid.layers.topk(input=loss, k=keep_num)
loss = fluid.layers.reduce_mean(loss)
报错,py_func这个接口不知道为啥不能转换,
@zhaoyuchen2018 topk下面这样的操作是正确的吗?可以这样操做吗?
loss = fluid.layers.cross_entropy(input=cls_prob, label=label_filter_invalid)
loss, _ = fluid.layers.topk(input=loss, k=keep_num)
@yeyupiaoling 从API上看可以的,现在有什么问题吗
@zhaoyuchen2018 这个是我完整的损失函数
def cls_ohem(cls_prob, label):
# # 只把pos的label设定为1,其余都为0
def my_where1(label):
zeros = np.zeros_like(label, dtype=np.int64)
label_filter_invalid = np.where(np.less(label, zeros), zeros, label)
return label_filter_invalid
label_filter_invalid = create_tmp_var(name='label_filter_invalid', dtype='int64', shape=label.shape)
label_filter_invalid = fluid.layers.py_func(func=my_where1, x=[label], out=label_filter_invalid)
loss = fluid.layers.cross_entropy(input=cls_prob, label=label_filter_invalid)
def cls_ohem2(label):
# 真实标签对应的概率
zeros = np.zeros_like(label, dtype=np.float32)
ones = np.ones_like(label, dtype=np.float32)
# 统计neg和pos的数量
valid_inds = np.where(label < zeros, zeros, ones)
num_valid = np.sum(valid_inds)
# 选取70%的数据
num_keep_radio = 0.7
keep_num = np.array(num_valid * num_keep_radio).astype(np.int32)
print(keep_num)
return keep_num
keep_num = create_tmp_var(name='keep_num', dtype='int32', shape=[1])
keep_num = fluid.layers.py_func(func=cls_ohem2, x=[label], out=[keep_num])
keep_num = fluid.layers.cast(keep_num, dtype='int64')
loss, _ = fluid.layers.topk(input=loss, k=keep_num)
loss = fluid.layers.reduce_mean(loss)
return loss
报错信息:
Traceback (most recent call last):
File "D:/yeyupiaoling/PyCharm/PaddlePaddle-MTCNN/train/train_PNet.py", line 14, in <module>
image, label, bbox_target, landmark_target, label_cost, bbox_loss, landmark_loss, accuracy, conv4_1, conv4_2, conv4_3 = P_Net()
File "D:\yeyupiaoling\PyCharm\PaddlePaddle-MTCNN\train\model.py", line 76, in P_Net
label_cost = cls_ohem(cls_prob=cls_prob, label=label)
File "D:\yeyupiaoling\PyCharm\PaddlePaddle-MTCNN\train\model.py", line 283, in cls_ohem
keep_num = fluid.layers.cast(keep_num, dtype='int64')
File "C:\Users\1596\AppData\Local\Programs\Python\Python35\lib\site-packages\paddle\fluid\layers\tensor.py", line 182, in cast
attrs={'in_dtype': x.dtype,
AttributeError: 'list' object has no attribute 'dtype'
出错的是这个fluid.layers.cast(keep_num, dtype='int64'),cast的参数应该是一个variable,不是一个list
@zhaoyuchen2018 所以我上面也提到这个问题
报错,py_func这个接口不知道为啥不能转换,
那应该如何处理呢?
试一下 keep_num=fluid.layers.py_func(func=cls_ohem2, x=label, out=keep_num)
@zhaoyuchen2018 我改成这样了,刚才的错误就没有了,但是程序突然退出了,什么错误都没有输出,应该是windows没有输出。
keep_num = create_tmp_var(name='keep_num', dtype='int32', shape=[0])
keep_num = fluid.layers.py_func(func=cls_ohem2, x=label, out=keep_num)
keep_num = fluid.layers.cast(keep_num, dtype='int32')
loss, _ = fluid.layers.topk(input=loss, k=keep_num)
loss = fluid.layers.reduce_mean(loss)
只有这句话
Process finished with exit code -1073740940 (0xC0000374)
@zhaoyuchen2018 我使用Ubuntu试了一下 报错
7fb1f01f8000-7fb1f01f9000 rw-p 00018000 00:00 75324 /lib/x86_64-linux-gnu/libpthread-2.23.so
7fb1f01f9000-7fb1f01fd000 rw-p 00000000 00:00 0
7fb1f0200000-7fb1f0225000 r-xp 00000000 00:00 75323 /lib/x86_64-linux-gnu/ld-2.23.so
7fb1f0225000-7fb1f0226000 r-xp 00025000 00:00 75323 /lib/x86_64-linux-gnu/ld-2.23.so
7fb1f0260000-7fb1f0421000 rw-p 00000000 00:00 0
7fb1f0425000-7fb1f0426000 r--p 00025000 00:00 75323 /lib/x86_64-linux-gnu/ld-2.23.so
7fb1f0426000-7fb1f0427000 rw-p 00026000 00:00 75323 /lib/x86_64-linux-gnu/ld-2.23.so
7fb1f0427000-7fb1f0428000 rw-p 00000000 00:00 0
7fb1f0430000-7fb1f0431000 rwxp 00000000 00:00 0
7fb1f0438000-7fb1f05d0000 r--p 00000000 00:00 57321 /usr/lib/locale/locale-archive
7fb1f05d0000-7fb1f05d1000 rw-p 00000000 00:00 0
7fb1f05e0000-7fb1f05e1000 rw-p 00000000 00:00 0
7fb1f05f0000-7fb1f05f1000 rw-p 00000000 00:00 0
7fb1f0600000-7fb1f0601000 rw-p 00000000 00:00 0
7fb1f0610000-7fb1f0611000 rw-p 00000000 00:00 0
7fb1f0620000-7fb1f0621000 rw-p 00000000 00:00 0
7fb1f0629000-7fb1f0630000 r--s 00000000 00:00 75198 /usr/lib/x86_64-linux-gnu/gconv/gconv-modules.cache
7fffcd5b7000-7fffcddb7000 rw-p 00000000 00:00 0 [stack]
7fffcdf5e000-7fffcdf5f000 r-xp 00000000 00:00 0 [vdso]
*** Aborted at 1559814099 (unix time) try "date -d @1559814099" if you are using GNU date ***
PC: @ 0x0 (unknown)
*** SIGABRT (@0x65) received by PID 101 (TID 0x7fb1f05e0700) from PID 101; stack trace: ***
@ 0x7fb1efff1390 (unknown)
@ 0x7fb1efc45428 gsignal
@ 0x7fb1efc4702a abort
@ 0x7fb1efc877ea (unknown)
@ 0x7fb1efc9037a (unknown)
@ 0x7fb1efc9453c cfree
@ 0x7fb1d48238bb _ZNK6paddle9operators10TopkKernelINS_8platform8CPUPlaceEfE7ComputeERKNS_9framework16ExecutionContextE._omp_fn.0
@ 0x7fb1d4827a1a paddle::operators::TopkKernel<>::Compute()
@ 0x7fb1d4828103 _ZNSt17_Function_handlerIFvRKN6paddle9framework16ExecutionContextEEZNKS1_24OpKernelRegistrarFunctorINS0_8platform8CPUPlaceELb0ELm0EJNS0_9operators10TopkKernelIS8_fEENSA_IS8_dEEEEclEPKcSF_iEUlS4_E_E9_M_invokeERKSt9_Any_dataS4_
@ 0x7fb1d5313a96 paddle::framework::OperatorWithKernel::RunImpl()
@ 0x7fb1d5314594 paddle::framework::OperatorWithKernel::RunImpl()
@ 0x7fb1d531276b paddle::framework::OperatorBase::Run()
@ 0x7fb1d42ccf3e paddle::framework::Executor::RunPreparedContext()
@ 0x7fb1d42cff1f paddle::framework::Executor::Run()
@ 0x7fb1d41583ce _ZZN8pybind1112cpp_function10initializeIZN6paddle6pybindL18pybind11_init_coreERNS_6moduleEEUlRNS2_9framework8ExecutorERKNS6_11ProgramDescEPNS6_5ScopeEibbRKSt6vectorISsSaISsEEE96_vIS8_SB_SD_ibbSI_EINS_4nameENS_9is_methodENS_7siblingEEEEvOT_PFT0_DpT1_EDpRKT2_ENUlRNS_6detail13function_callEE1_4_FUNES10_
@ 0x7fb1d41970fe pybind11::cpp_function::dispatcher()
@ 0x4ea137 PyCFunction_Call
@ 0x53c176 PyEval_EvalFrameEx
@ 0x53fc97 (unknown)
@ 0x53bc93 PyEval_EvalFrameEx
@ 0x53fc97 (unknown)
@ 0x53b83f PyEval_EvalFrameEx
@ 0x53fc97 (unknown)
@ 0x5409bf PyEval_EvalCode
@ 0x60cb42 (unknown)
@ 0x60efea PyRun_FileExFlags
@ 0x60f7dc PyRun_SimpleFileExFlags
@ 0x640256 Py_Main
@ 0x4d0001 main
@ 0x7fb1efc30830 __libc_start_main
@ 0x5d6999 _start
@ 0x0 (unknown)
Aborted (core dumped)
看coredump是topk计算的时候出错了,可以打印一下topk的输入看看是多少
@zhaoyuchen2018 您好 topk 的 input是
[[0.6700775 ]
[0.693747 ]
[0.69301224]
[0.7074372 ]
[0.7992326 ]
[0.72812045]
[0.7355523 ]
[0.7648116 ]
[0.59001243]
[0.5689244 ]
[0.67671394]
[0.5500078 ]
[0.7261787 ]
[0.6296523 ]
[0.8291486 ]
[0.6954007 ]
[0.598718 ]
[0.7377669 ]
[0.7702262 ]
[0.82846904]
[0.71853405]
[0.5965401 ]
[0.69748455]
[0.76739144]
[0.76131326]
[0.7664091 ]
[0.6324115 ]
[0.84517527]
[0.85355633]
[0.7141142 ]
[0.69909906]
[0.86924976]
[0.90430635]
[0.590687 ]
[0.7313982 ]
[0.7124466 ]
[0.70039177]
[0.7269521 ]
[0.872542 ]
[0.6306449 ]
[0.6703477 ]
[0.6364614 ]
[0.68620867]
[0.6221381 ]
[0.72795415]
[0.66355854]
[0.69705933]
[0.6934133 ]
[0.7722714 ]
[0.7510166 ]
[0.7344718 ]
[0.740004 ]
[0.52138114]
[0.80896086]
[0.8480674 ]
[0.7124495 ]
[0.67082393]
[0.6867498 ]
[0.6317535 ]
[0.6954882 ]
[0.7218874 ]
[0.71404696]
[0.75859237]
[0.6674785 ]
[0.72674656]
[0.74079645]
[0.5476208 ]
[0.7175897 ]
[0.5717071 ]
[0.69918305]
[0.88470155]
[0.62579983]
[0.715444 ]
[0.99158996]
[0.6995909 ]
[0.7147626 ]
[0.7439415 ]
[0.575649 ]
[0.88300025]
[0.54699534]
[0.6942796 ]
[0.71934587]
[0.80004513]
[0.57836443]
[0.77139807]
[0.7332156 ]
[0.652708 ]
[0.7782768 ]
[0.5440566 ]
[0.7499437 ]
[0.7877618 ]
[0.605641 ]
[0.95632225]
[0.6740086 ]
[0.6570157 ]
[0.75570357]
[0.664059 ]
[0.63050807]
[0.65822256]
[0.8775672 ]
[0.70775634]
[0.74692255]
[0.7187877 ]
[0.5993015 ]
[0.7311135 ]
[0.73226875]
[0.76944906]
[0.65537846]
[0.7332761 ]
[0.8988396 ]
[0.7089458 ]
[0.6372558 ]
[0.89795786]
[0.63643026]
[0.81051886]
[0.70302373]
[0.7077041 ]
[0.66492873]
[0.6723665 ]
[0.719695 ]
[0.9670727 ]
[0.8602567 ]
[0.93993556]
[0.6616607 ]
[0.75838655]
[0.7886654 ]
[0.71104664]
[0.7430986 ]
[0.7567478 ]
[0.69179696]
[0.75252056]
[0.7750985 ]
[0.7324069 ]
[0.72888255]
[0.7991416 ]
[0.69823533]
[0.6662678 ]
[0.8040517 ]
[0.8477792 ]
[0.6930785 ]
[0.70582235]
[0.6668653 ]
[0.69579774]
[0.69005525]
[0.7793102 ]
[0.6763303 ]
[0.69347334]
[0.6847814 ]
[0.74059767]
[0.7500229 ]
[0.62577397]
[0.7839745 ]
[0.6325352 ]
[0.7881667 ]
[0.7269836 ]
[0.82507885]
[0.8369697 ]
[0.837202 ]
[0.6244013 ]
[0.68953735]
[0.7091262 ]
[0.71818995]
[0.79432774]
[0.63084686]
[0.6715005 ]
[0.67573124]
[0.65746915]
[0.6170599 ]
[0.62682074]
[0.7071603 ]
[0.7487202 ]
[0.8030292 ]
[0.60119826]
[0.7479353 ]
[0.7602143 ]
[0.8533068 ]
[0.82693756]
[0.79285896]
[0.719782 ]
[0.69670045]
[0.68171376]
[0.6374928 ]
[0.6818403 ]
[0.67609435]
[0.75922567]
[0.6924921 ]
[0.72358227]
[0.73506707]
[0.7026128 ]
[0.6412829 ]
[0.8045003 ]
[0.77025485]
[0.7837167 ]
[0.5803312 ]
[0.6489468 ]
[0.8193252 ]
[0.72998583]
[0.69376105]
[0.72067773]
[0.635944 ]
[0.7626754 ]
[0.68097824]
[0.77303416]
[0.7594408 ]
[0.6225478 ]
[0.7348391 ]
[0.6023737 ]
[0.68848884]
[0.64876777]
[0.7636494 ]
[0.7342571 ]
[0.849993 ]
[0.68947905]
[0.7542419 ]
[0.79021084]
[0.7384664 ]
[0.68522346]
[0.6917922 ]
[0.72351027]
[0.6455935 ]
[1.0095582 ]
[0.66079116]
[0.8460905 ]
[0.7618728 ]
[0.7875096 ]
[0.7583084 ]
[0.7480836 ]
[0.81380755]
[0.74354786]
[0.72617567]
[0.7056841 ]
[0.7262455 ]
[0.73189336]
[0.94608235]
[0.74237823]
[0.6007193 ]
[0.7171672 ]
[0.67947304]
[0.6520099 ]
[0.6851271 ]
[0.63552517]
[0.60299546]
[0.6499209 ]
[0.8561353 ]
[0.5944042 ]
[0.65666175]
[0.6796306 ]
[0.6885019 ]
[0.65661323]
[0.71597576]
[0.77402043]
[0.7690053 ]
[0.68915117]
[0.78928524]
[0.7664544 ]
[0.7698725 ]
[0.78067654]
[0.72093594]
[0.7730508 ]
[0.87419444]
[0.71901387]
[0.6628682 ]
[0.84826565]
[0.68048894]
[0.61794764]
[0.7840849 ]
[0.68250984]
[0.6355145 ]
[0.77440953]
[0.768551 ]
[0.6838051 ]
[0.7379912 ]
[0.67161065]
[0.8062841 ]
[0.6159257 ]
[0.6412254 ]
[0.64087427]
[0.7452292 ]
[0.6839147 ]
[0.69582826]
[0.72118616]
[0.7024998 ]
[0.65151334]
[0.6644692 ]
[0.6101692 ]
[0.8397084 ]
[0.69634324]
[0.7533175 ]
[0.7213531 ]
[0.61457366]
[0.7825223 ]
[0.6827612 ]
[0.77807134]
[0.67607164]
[0.7002548 ]
[0.7558534 ]
[0.69824326]
[0.6712833 ]
[0.7367064 ]
[0.55032057]
[0.7313399 ]
[0.61760104]
[0.73615634]
[0.70716554]
[0.7227552 ]
[0.80285764]
[0.70625484]
[0.5667885 ]
[0.69197214]
[0.73489136]
[0.75154686]
[0.73132193]
[0.6878106 ]
[0.7149633 ]
[0.9193721 ]
[0.7536942 ]
[0.64134264]
[0.9941715 ]
[0.7097261 ]
[0.6971603 ]
[0.73340607]
[0.5836641 ]
[0.6418816 ]
[0.71027315]
[0.6159967 ]
[0.65234125]
[0.5970481 ]
[0.5507543 ]
[0.8554042 ]
[0.738468 ]
[0.67821926]
[0.75363433]
[0.66852355]
[0.79740083]
[0.7518644 ]
[0.8038023 ]
[0.6865158 ]
[0.6770407 ]
[0.71430933]
[0.7088358 ]
[0.6258881 ]
[0.76924956]
[0.6851242 ]
[0.6409307 ]
[0.8375389 ]
[0.854668 ]
[0.7177612 ]
[0.71006656]
[0.7009162 ]
[0.5066931 ]
[0.6486771 ]
[0.6728813 ]
[0.7522487 ]
[0.7361135 ]
[0.63732386]
[0.69216394]
[0.65146923]
[0.82831335]
[0.68636763]
[0.7186093 ]
[0.627574 ]
[0.6513062 ]
[0.66762096]
[0.690623 ]
[0.5921318 ]
[0.7763984 ]
[0.7531681 ]
[0.7945476 ]
[0.7410368 ]
[0.7446611 ]
[0.65416104]
[0.61570024]
[0.61420953]
[0.7495417 ]
[0.658115 ]
[0.6967359 ]
[0.8562746 ]
[0.68242204]
[0.98553246]
[0.6648919 ]
[0.59862643]
[0.7011096 ]
[0.7080566 ]
[0.89197165]]
k值是:184, batch size是384
@zhaoyuchen2018 这个是什么问题呢?
Traceback (most recent call last):
File "D:/yeyupiaoling/PyCharm/PaddlePaddle-MTCNN/train/train_PNet.py", line 50, in <module>
bbox_loss, landmark_loss, temp])
File "C:\Users\1596\AppData\Local\Programs\Python\Python35\lib\site-packages\paddle\fluid\executor.py", line 565, in run
use_program_cache=use_program_cache)
File "C:\Users\1596\AppData\Local\Programs\Python\Python35\lib\site-packages\paddle\fluid\executor.py", line 642, in _run
exe.run(program.desc, scope, 0, True, True, fetch_var_name)
paddle.fluid.core.EnforceNotMet: Invoke operator top_k error.
Python Callstacks:
File "C:\Users\1596\AppData\Local\Programs\Python\Python35\lib\site-packages\paddle\fluid\framework.py", line 1654, in append_op
attrs=kwargs.get("attrs", None))
File "C:\Users\1596\AppData\Local\Programs\Python\Python35\lib\site-packages\paddle\fluid\layer_helper.py", line 43, in append_op
return self.main_program.current_block().append_op(*args, **kwargs)
File "C:\Users\1596\AppData\Local\Programs\Python\Python35\lib\site-packages\paddle\fluid\layers\nn.py", line 5012, in topk
attrs=attrs)
File "D:\yeyupiaoling\PyCharm\PaddlePaddle-MTCNN\train\model.py", line 295, in cls_ohem
loss, _ = fluid.layers.topk(input=loss, k=keep_num)
File "D:\yeyupiaoling\PyCharm\PaddlePaddle-MTCNN\train\model.py", line 76, in P_Net
label_cost, temp = cls_ohem(cls_prob=cls_prob, label=label)
File "D:/yeyupiaoling/PyCharm/PaddlePaddle-MTCNN/train/train_PNet.py", line 14, in <module>
image, label, bbox_target, landmark_target, label_cost, bbox_loss, landmark_loss, accuracy, conv4_1, conv4_2, conv4_3, temp = P_Net()
C++ Callstacks:
`num_col_dims` must be between (0, rank_of_tensor). at [D:\1.4.1\paddle\paddle/fluid/framework/eigen.h:82]
PaddlePaddle Call Stacks:
Windows not support stack backtrace yet.
用下面代码可以跑通 动态的topn
# -*- coding: utf-8 -*-
import os
import sys
import paddle
import paddle.fluid as fluid
import numpy as np
def thresh_where_op(x, threshvalue, trueval):
#阈值变量
thresh = fluid.layers.fill_constant([1], dtype='int64', value=threshvalue)
thresh.stop_gradient = True
#label中小于0的部分
ifcond = fluid.layers.less_than(x=x, y=thresh)
#将label中小于0的部分,赋值为 trueval, 其余的保持不变
ie = fluid.layers.IfElse(ifcond)
with ie.true_block():
x1 = ie.input(x)
fillval = fluid.layers.fill_constant_batch_size_like(x1,[-1,1], dtype=np.int64,value=trueval)
ie.output(fillval)
with ie.false_block():
x2 = ie.input(x)
ie.output(x2)
res = ie()
#返回 新的label
newlabel = res[0]
return newlabel, ifcond
def test_loss():
batchsize = 10
keepratio = 0.7
input = fluid.layers.data(name='input', shape=[5], dtype='float32')
out = fluid.layers.fc(input=input, size=2)
label = fluid.layers.data(name='label', shape=[1], dtype='int64')
#将小于零的label替换为-100, 在计算交叉熵时忽略掉,
newlabel,ifcond = thresh_where_op(label, 0, -100)
#bool to float
castifcond = fluid.layers.cast(ifcond, np.float32)
# count(samplenum) * keepratio
keepnum = (batchsize - fluid.layers.reduce_sum(castifcond))*keepratio
# 转换为整数
keepnum = fluid.layers.cast(keepnum, np.int32)
keepnum.stop_gradient = True
#计算损失
loss = fluid.layers.softmax_with_cross_entropy(out, newlabel, ignore_index=-100)
#reshape ,准备求top
loss = fluid.layers.reshape(loss, [1, -1])
#topk
toploss, topindex = fluid.layers.topk(loss, k = keepnum, name='topk')
#topk损失求均值
meanloss = fluid.layers.reduce_mean(toploss)
place = fluid.CPUPlace()
exe = fluid.Executor(place)
exe.run(fluid.default_startup_program())
#print_variable()
inputdata = np.random.rand(10,5).astype(np.float32)
labeldata = np.array([0,0,0,1,1,1,1,1,0,0], np.int64).reshape((-1,1))
#labeldata = np.array([-1,-2,0,1,1,1,1,1,0,0], np.int64).reshape((-1,1))
outputlist = exe.run(
fluid.default_main_program(),
feed={'input': inputdata, 'label': labeldata},
fetch_list=['label', newlabel.name, keepnum.name, toploss.name])
print outputlist
test_loss()
@lgone2000 感谢,参考以上的代码,我解决了积累很长时间的问题。