test_ops.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from __future__ import print_function
  15. import os, sys
  16. # add python path of PadleDetection to sys.path
  17. parent_path = os.path.abspath(os.path.join(__file__, *(['..'] * 4)))
  18. if parent_path not in sys.path:
  19. sys.path.append(parent_path)
  20. import unittest
  21. import numpy as np
  22. import paddle
  23. import paddle.fluid as fluid
  24. from paddle.fluid.dygraph import base
  25. import paddlex.ppdet.modeling.ops as ops
  26. from paddlex.ppdet.modeling.tests.test_base import LayerTest
  27. def make_rois(h, w, rois_num, output_size):
  28. rois = np.zeros((0, 4)).astype('float32')
  29. for roi_num in rois_num:
  30. roi = np.zeros((roi_num, 4)).astype('float32')
  31. roi[:, 0] = np.random.randint(0, h - output_size[0], size=roi_num)
  32. roi[:, 1] = np.random.randint(0, w - output_size[1], size=roi_num)
  33. roi[:, 2] = np.random.randint(roi[:, 0] + output_size[0], h)
  34. roi[:, 3] = np.random.randint(roi[:, 1] + output_size[1], w)
  35. rois = np.vstack((rois, roi))
  36. return rois
  37. def softmax(x):
  38. # clip to shiftx, otherwise, when calc loss with
  39. # log(exp(shiftx)), may get log(0)=INF
  40. shiftx = (x - np.max(x)).clip(-64.)
  41. exps = np.exp(shiftx)
  42. return exps / np.sum(exps)
  43. class TestCollectFpnProposals(LayerTest):
  44. def test_collect_fpn_proposals(self):
  45. multi_bboxes_np = []
  46. multi_scores_np = []
  47. rois_num_per_level_np = []
  48. for i in range(4):
  49. bboxes_np = np.random.rand(5, 4).astype('float32')
  50. scores_np = np.random.rand(5, 1).astype('float32')
  51. rois_num = np.array([2, 3]).astype('int32')
  52. multi_bboxes_np.append(bboxes_np)
  53. multi_scores_np.append(scores_np)
  54. rois_num_per_level_np.append(rois_num)
  55. with self.static_graph():
  56. multi_bboxes = []
  57. multi_scores = []
  58. rois_num_per_level = []
  59. for i in range(4):
  60. bboxes = paddle.static.data(
  61. name='rois' + str(i),
  62. shape=[5, 4],
  63. dtype='float32',
  64. lod_level=1)
  65. scores = paddle.static.data(
  66. name='scores' + str(i),
  67. shape=[5, 1],
  68. dtype='float32',
  69. lod_level=1)
  70. rois_num = paddle.static.data(
  71. name='rois_num' + str(i), shape=[None], dtype='int32')
  72. multi_bboxes.append(bboxes)
  73. multi_scores.append(scores)
  74. rois_num_per_level.append(rois_num)
  75. fpn_rois, rois_num = ops.collect_fpn_proposals(
  76. multi_bboxes,
  77. multi_scores,
  78. 2,
  79. 5,
  80. 10,
  81. rois_num_per_level=rois_num_per_level)
  82. feed = {}
  83. for i in range(4):
  84. feed['rois' + str(i)] = multi_bboxes_np[i]
  85. feed['scores' + str(i)] = multi_scores_np[i]
  86. feed['rois_num' + str(i)] = rois_num_per_level_np[i]
  87. fpn_rois_stat, rois_num_stat = self.get_static_graph_result(
  88. feed=feed, fetch_list=[fpn_rois, rois_num], with_lod=True)
  89. fpn_rois_stat = np.array(fpn_rois_stat)
  90. rois_num_stat = np.array(rois_num_stat)
  91. with self.dynamic_graph():
  92. multi_bboxes_dy = []
  93. multi_scores_dy = []
  94. rois_num_per_level_dy = []
  95. for i in range(4):
  96. bboxes_dy = base.to_variable(multi_bboxes_np[i])
  97. scores_dy = base.to_variable(multi_scores_np[i])
  98. rois_num_dy = base.to_variable(rois_num_per_level_np[i])
  99. multi_bboxes_dy.append(bboxes_dy)
  100. multi_scores_dy.append(scores_dy)
  101. rois_num_per_level_dy.append(rois_num_dy)
  102. fpn_rois_dy, rois_num_dy = ops.collect_fpn_proposals(
  103. multi_bboxes_dy,
  104. multi_scores_dy,
  105. 2,
  106. 5,
  107. 10,
  108. rois_num_per_level=rois_num_per_level_dy)
  109. fpn_rois_dy = fpn_rois_dy.numpy()
  110. rois_num_dy = rois_num_dy.numpy()
  111. self.assertTrue(np.array_equal(fpn_rois_stat, fpn_rois_dy))
  112. self.assertTrue(np.array_equal(rois_num_stat, rois_num_dy))
  113. def test_collect_fpn_proposals_error(self):
  114. def generate_input(bbox_type, score_type, name):
  115. multi_bboxes = []
  116. multi_scores = []
  117. for i in range(4):
  118. bboxes = paddle.static.data(
  119. name='rois' + name + str(i),
  120. shape=[10, 4],
  121. dtype=bbox_type,
  122. lod_level=1)
  123. scores = paddle.static.data(
  124. name='scores' + name + str(i),
  125. shape=[10, 1],
  126. dtype=score_type,
  127. lod_level=1)
  128. multi_bboxes.append(bboxes)
  129. multi_scores.append(scores)
  130. return multi_bboxes, multi_scores
  131. with self.static_graph():
  132. bbox1 = paddle.static.data(
  133. name='rois', shape=[5, 10, 4], dtype='float32', lod_level=1)
  134. score1 = paddle.static.data(
  135. name='scores', shape=[5, 10, 1], dtype='float32', lod_level=1)
  136. bbox2, score2 = generate_input('int32', 'float32', '2')
  137. self.assertRaises(
  138. TypeError,
  139. ops.collect_fpn_proposals,
  140. multi_rois=bbox1,
  141. multi_scores=score1,
  142. min_level=2,
  143. max_level=5,
  144. post_nms_top_n=2000)
  145. self.assertRaises(
  146. TypeError,
  147. ops.collect_fpn_proposals,
  148. multi_rois=bbox2,
  149. multi_scores=score2,
  150. min_level=2,
  151. max_level=5,
  152. post_nms_top_n=2000)
  153. paddle.disable_static()
  154. class TestDistributeFpnProposals(LayerTest):
  155. def test_distribute_fpn_proposals(self):
  156. rois_np = np.random.rand(10, 4).astype('float32')
  157. rois_num_np = np.array([4, 6]).astype('int32')
  158. with self.static_graph():
  159. rois = paddle.static.data(
  160. name='rois', shape=[10, 4], dtype='float32')
  161. rois_num = paddle.static.data(
  162. name='rois_num', shape=[None], dtype='int32')
  163. multi_rois, restore_ind, rois_num_per_level = ops.distribute_fpn_proposals(
  164. fpn_rois=rois,
  165. min_level=2,
  166. max_level=5,
  167. refer_level=4,
  168. refer_scale=224,
  169. rois_num=rois_num)
  170. fetch_list = multi_rois + [restore_ind] + rois_num_per_level
  171. output_stat = self.get_static_graph_result(
  172. feed={'rois': rois_np,
  173. 'rois_num': rois_num_np},
  174. fetch_list=fetch_list,
  175. with_lod=True)
  176. output_stat_np = []
  177. for output in output_stat:
  178. output_np = np.array(output)
  179. if len(output_np) > 0:
  180. output_stat_np.append(output_np)
  181. with self.dynamic_graph():
  182. rois_dy = base.to_variable(rois_np)
  183. rois_num_dy = base.to_variable(rois_num_np)
  184. multi_rois_dy, restore_ind_dy, rois_num_per_level_dy = ops.distribute_fpn_proposals(
  185. fpn_rois=rois_dy,
  186. min_level=2,
  187. max_level=5,
  188. refer_level=4,
  189. refer_scale=224,
  190. rois_num=rois_num_dy)
  191. output_dy = multi_rois_dy + [restore_ind_dy
  192. ] + rois_num_per_level_dy
  193. output_dy_np = []
  194. for output in output_dy:
  195. output_np = output.numpy()
  196. if len(output_np) > 0:
  197. output_dy_np.append(output_np)
  198. for res_stat, res_dy in zip(output_stat_np, output_dy_np):
  199. self.assertTrue(np.array_equal(res_stat, res_dy))
  200. def test_distribute_fpn_proposals_error(self):
  201. with self.static_graph():
  202. fpn_rois = paddle.static.data(
  203. name='data_error', shape=[10, 4], dtype='int32', lod_level=1)
  204. self.assertRaises(
  205. TypeError,
  206. ops.distribute_fpn_proposals,
  207. fpn_rois=fpn_rois,
  208. min_level=2,
  209. max_level=5,
  210. refer_level=4,
  211. refer_scale=224)
  212. paddle.disable_static()
  213. class TestROIAlign(LayerTest):
  214. def test_roi_align(self):
  215. b, c, h, w = 2, 12, 20, 20
  216. inputs_np = np.random.rand(b, c, h, w).astype('float32')
  217. rois_num = [4, 6]
  218. output_size = (7, 7)
  219. rois_np = make_rois(h, w, rois_num, output_size)
  220. rois_num_np = np.array(rois_num).astype('int32')
  221. with self.static_graph():
  222. inputs = paddle.static.data(
  223. name='inputs', shape=[b, c, h, w], dtype='float32')
  224. rois = paddle.static.data(
  225. name='rois', shape=[10, 4], dtype='float32')
  226. rois_num = paddle.static.data(
  227. name='rois_num', shape=[None], dtype='int32')
  228. output = ops.roi_align(
  229. input=inputs,
  230. rois=rois,
  231. output_size=output_size,
  232. rois_num=rois_num)
  233. output_np, = self.get_static_graph_result(
  234. feed={
  235. 'inputs': inputs_np,
  236. 'rois': rois_np,
  237. 'rois_num': rois_num_np
  238. },
  239. fetch_list=output,
  240. with_lod=False)
  241. with self.dynamic_graph():
  242. inputs_dy = base.to_variable(inputs_np)
  243. rois_dy = base.to_variable(rois_np)
  244. rois_num_dy = base.to_variable(rois_num_np)
  245. output_dy = ops.roi_align(
  246. input=inputs_dy,
  247. rois=rois_dy,
  248. output_size=output_size,
  249. rois_num=rois_num_dy)
  250. output_dy_np = output_dy.numpy()
  251. self.assertTrue(np.array_equal(output_np, output_dy_np))
  252. def test_roi_align_error(self):
  253. with self.static_graph():
  254. inputs = paddle.static.data(
  255. name='inputs', shape=[2, 12, 20, 20], dtype='float32')
  256. rois = paddle.static.data(
  257. name='data_error', shape=[10, 4], dtype='int32', lod_level=1)
  258. self.assertRaises(
  259. TypeError,
  260. ops.roi_align,
  261. input=inputs,
  262. rois=rois,
  263. output_size=(7, 7))
  264. paddle.disable_static()
  265. class TestROIPool(LayerTest):
  266. def test_roi_pool(self):
  267. b, c, h, w = 2, 12, 20, 20
  268. inputs_np = np.random.rand(b, c, h, w).astype('float32')
  269. rois_num = [4, 6]
  270. output_size = (7, 7)
  271. rois_np = make_rois(h, w, rois_num, output_size)
  272. rois_num_np = np.array(rois_num).astype('int32')
  273. with self.static_graph():
  274. inputs = paddle.static.data(
  275. name='inputs', shape=[b, c, h, w], dtype='float32')
  276. rois = paddle.static.data(
  277. name='rois', shape=[10, 4], dtype='float32')
  278. rois_num = paddle.static.data(
  279. name='rois_num', shape=[None], dtype='int32')
  280. output, _ = ops.roi_pool(
  281. input=inputs,
  282. rois=rois,
  283. output_size=output_size,
  284. rois_num=rois_num)
  285. output_np, = self.get_static_graph_result(
  286. feed={
  287. 'inputs': inputs_np,
  288. 'rois': rois_np,
  289. 'rois_num': rois_num_np
  290. },
  291. fetch_list=[output],
  292. with_lod=False)
  293. with self.dynamic_graph():
  294. inputs_dy = base.to_variable(inputs_np)
  295. rois_dy = base.to_variable(rois_np)
  296. rois_num_dy = base.to_variable(rois_num_np)
  297. output_dy, _ = ops.roi_pool(
  298. input=inputs_dy,
  299. rois=rois_dy,
  300. output_size=output_size,
  301. rois_num=rois_num_dy)
  302. output_dy_np = output_dy.numpy()
  303. self.assertTrue(np.array_equal(output_np, output_dy_np))
  304. def test_roi_pool_error(self):
  305. with self.static_graph():
  306. inputs = paddle.static.data(
  307. name='inputs', shape=[2, 12, 20, 20], dtype='float32')
  308. rois = paddle.static.data(
  309. name='data_error', shape=[10, 4], dtype='int32', lod_level=1)
  310. self.assertRaises(
  311. TypeError,
  312. ops.roi_pool,
  313. input=inputs,
  314. rois=rois,
  315. output_size=(7, 7))
  316. paddle.disable_static()
  317. class TestIoUSimilarity(LayerTest):
  318. def test_iou_similarity(self):
  319. b, c, h, w = 2, 12, 20, 20
  320. inputs_np = np.random.rand(b, c, h, w).astype('float32')
  321. output_size = (7, 7)
  322. x_np = make_rois(h, w, [20], output_size)
  323. y_np = make_rois(h, w, [10], output_size)
  324. with self.static_graph():
  325. x = paddle.static.data(name='x', shape=[20, 4], dtype='float32')
  326. y = paddle.static.data(name='y', shape=[10, 4], dtype='float32')
  327. iou = ops.iou_similarity(x=x, y=y)
  328. iou_np, = self.get_static_graph_result(
  329. feed={
  330. 'x': x_np,
  331. 'y': y_np,
  332. },
  333. fetch_list=[iou],
  334. with_lod=False)
  335. with self.dynamic_graph():
  336. x_dy = base.to_variable(x_np)
  337. y_dy = base.to_variable(y_np)
  338. iou_dy = ops.iou_similarity(x=x_dy, y=y_dy)
  339. iou_dy_np = iou_dy.numpy()
  340. self.assertTrue(np.array_equal(iou_np, iou_dy_np))
  341. class TestBipartiteMatch(LayerTest):
  342. def test_bipartite_match(self):
  343. distance = np.random.random((20, 10)).astype('float32')
  344. with self.static_graph():
  345. x = paddle.static.data(name='x', shape=[20, 10], dtype='float32')
  346. match_indices, match_dist = ops.bipartite_match(
  347. x, match_type='per_prediction', dist_threshold=0.5)
  348. match_indices_np, match_dist_np = self.get_static_graph_result(
  349. feed={'x': distance, },
  350. fetch_list=[match_indices, match_dist],
  351. with_lod=False)
  352. with self.dynamic_graph():
  353. x_dy = base.to_variable(distance)
  354. match_indices_dy, match_dist_dy = ops.bipartite_match(
  355. x_dy, match_type='per_prediction', dist_threshold=0.5)
  356. match_indices_dy_np = match_indices_dy.numpy()
  357. match_dist_dy_np = match_dist_dy.numpy()
  358. self.assertTrue(np.array_equal(match_indices_np, match_indices_dy_np))
  359. self.assertTrue(np.array_equal(match_dist_np, match_dist_dy_np))
  360. class TestYoloBox(LayerTest):
  361. def test_yolo_box(self):
  362. # x shape [N C H W], C=K * (5 + class_num), class_num=10, K=2
  363. np_x = np.random.random([1, 30, 7, 7]).astype('float32')
  364. np_origin_shape = np.array([[608, 608]], dtype='int32')
  365. class_num = 10
  366. conf_thresh = 0.01
  367. downsample_ratio = 32
  368. scale_x_y = 1.2
  369. # static
  370. with self.static_graph():
  371. # x shape [N C H W], C=K * (5 + class_num), class_num=10, K=2
  372. x = paddle.static.data(
  373. name='x', shape=[1, 30, 7, 7], dtype='float32')
  374. origin_shape = paddle.static.data(
  375. name='origin_shape', shape=[1, 2], dtype='int32')
  376. boxes, scores = ops.yolo_box(
  377. x,
  378. origin_shape, [10, 13, 30, 13],
  379. class_num,
  380. conf_thresh,
  381. downsample_ratio,
  382. scale_x_y=scale_x_y)
  383. boxes_np, scores_np = self.get_static_graph_result(
  384. feed={
  385. 'x': np_x,
  386. 'origin_shape': np_origin_shape,
  387. },
  388. fetch_list=[boxes, scores],
  389. with_lod=False)
  390. # dygraph
  391. with self.dynamic_graph():
  392. x_dy = fluid.layers.assign(np_x)
  393. origin_shape_dy = fluid.layers.assign(np_origin_shape)
  394. boxes_dy, scores_dy = ops.yolo_box(
  395. x_dy,
  396. origin_shape_dy, [10, 13, 30, 13],
  397. 10,
  398. 0.01,
  399. 32,
  400. scale_x_y=scale_x_y)
  401. boxes_dy_np = boxes_dy.numpy()
  402. scores_dy_np = scores_dy.numpy()
  403. self.assertTrue(np.array_equal(boxes_np, boxes_dy_np))
  404. self.assertTrue(np.array_equal(scores_np, scores_dy_np))
  405. def test_yolo_box_error(self):
  406. with self.static_graph():
  407. # x shape [N C H W], C=K * (5 + class_num), class_num=10, K=2
  408. x = paddle.static.data(
  409. name='x', shape=[1, 30, 7, 7], dtype='float32')
  410. origin_shape = paddle.static.data(
  411. name='origin_shape', shape=[1, 2], dtype='int32')
  412. self.assertRaises(
  413. TypeError,
  414. ops.yolo_box,
  415. x,
  416. origin_shape, [10, 13, 30, 13],
  417. 10.123,
  418. 0.01,
  419. 32,
  420. scale_x_y=1.2)
  421. paddle.disable_static()
  422. class TestPriorBox(LayerTest):
  423. def test_prior_box(self):
  424. input_np = np.random.rand(2, 10, 32, 32).astype('float32')
  425. image_np = np.random.rand(2, 10, 40, 40).astype('float32')
  426. min_sizes = [2, 4]
  427. with self.static_graph():
  428. input = paddle.static.data(
  429. name='input', shape=[2, 10, 32, 32], dtype='float32')
  430. image = paddle.static.data(
  431. name='image', shape=[2, 10, 40, 40], dtype='float32')
  432. box, var = ops.prior_box(
  433. input=input,
  434. image=image,
  435. min_sizes=min_sizes,
  436. clip=True,
  437. flip=True)
  438. box_np, var_np = self.get_static_graph_result(
  439. feed={
  440. 'input': input_np,
  441. 'image': image_np,
  442. },
  443. fetch_list=[box, var],
  444. with_lod=False)
  445. with self.dynamic_graph():
  446. inputs_dy = base.to_variable(input_np)
  447. image_dy = base.to_variable(image_np)
  448. box_dy, var_dy = ops.prior_box(
  449. input=inputs_dy,
  450. image=image_dy,
  451. min_sizes=min_sizes,
  452. clip=True,
  453. flip=True)
  454. box_dy_np = box_dy.numpy()
  455. var_dy_np = var_dy.numpy()
  456. self.assertTrue(np.array_equal(box_np, box_dy_np))
  457. self.assertTrue(np.array_equal(var_np, var_dy_np))
  458. def test_prior_box_error(self):
  459. with self.static_graph():
  460. input = paddle.static.data(
  461. name='input', shape=[2, 10, 32, 32], dtype='int32')
  462. image = paddle.static.data(
  463. name='image', shape=[2, 10, 40, 40], dtype='int32')
  464. self.assertRaises(
  465. TypeError,
  466. ops.prior_box,
  467. input=input,
  468. image=image,
  469. min_sizes=[2, 4],
  470. clip=True,
  471. flip=True)
  472. paddle.disable_static()
  473. class TestMulticlassNms(LayerTest):
  474. def test_multiclass_nms(self):
  475. boxes_np = np.random.rand(10, 81, 4).astype('float32')
  476. scores_np = np.random.rand(10, 81).astype('float32')
  477. rois_num_np = np.array([2, 8]).astype('int32')
  478. with self.static_graph():
  479. boxes = paddle.static.data(
  480. name='bboxes',
  481. shape=[None, 81, 4],
  482. dtype='float32',
  483. lod_level=1)
  484. scores = paddle.static.data(
  485. name='scores', shape=[None, 81], dtype='float32', lod_level=1)
  486. rois_num = paddle.static.data(
  487. name='rois_num', shape=[None], dtype='int32')
  488. output = ops.multiclass_nms(
  489. bboxes=boxes,
  490. scores=scores,
  491. background_label=0,
  492. score_threshold=0.5,
  493. nms_top_k=400,
  494. nms_threshold=0.3,
  495. keep_top_k=200,
  496. normalized=False,
  497. return_index=True,
  498. rois_num=rois_num)
  499. out_np, index_np, nms_rois_num_np = self.get_static_graph_result(
  500. feed={
  501. 'bboxes': boxes_np,
  502. 'scores': scores_np,
  503. 'rois_num': rois_num_np
  504. },
  505. fetch_list=output,
  506. with_lod=True)
  507. out_np = np.array(out_np)
  508. index_np = np.array(index_np)
  509. nms_rois_num_np = np.array(nms_rois_num_np)
  510. with self.dynamic_graph():
  511. boxes_dy = base.to_variable(boxes_np)
  512. scores_dy = base.to_variable(scores_np)
  513. rois_num_dy = base.to_variable(rois_num_np)
  514. out_dy, index_dy, nms_rois_num_dy = ops.multiclass_nms(
  515. bboxes=boxes_dy,
  516. scores=scores_dy,
  517. background_label=0,
  518. score_threshold=0.5,
  519. nms_top_k=400,
  520. nms_threshold=0.3,
  521. keep_top_k=200,
  522. normalized=False,
  523. return_index=True,
  524. rois_num=rois_num_dy)
  525. out_dy_np = out_dy.numpy()
  526. index_dy_np = index_dy.numpy()
  527. nms_rois_num_dy_np = nms_rois_num_dy.numpy()
  528. self.assertTrue(np.array_equal(out_np, out_dy_np))
  529. self.assertTrue(np.array_equal(index_np, index_dy_np))
  530. self.assertTrue(np.array_equal(nms_rois_num_np, nms_rois_num_dy_np))
  531. def test_multiclass_nms_error(self):
  532. with self.static_graph():
  533. boxes = paddle.static.data(
  534. name='bboxes', shape=[81, 4], dtype='float32', lod_level=1)
  535. scores = paddle.static.data(
  536. name='scores', shape=[81], dtype='float32', lod_level=1)
  537. rois_num = paddle.static.data(
  538. name='rois_num', shape=[40, 41], dtype='int32')
  539. self.assertRaises(
  540. TypeError,
  541. ops.multiclass_nms,
  542. boxes=boxes,
  543. scores=scores,
  544. background_label=0,
  545. score_threshold=0.5,
  546. nms_top_k=400,
  547. nms_threshold=0.3,
  548. keep_top_k=200,
  549. normalized=False,
  550. return_index=True,
  551. rois_num=rois_num)
  552. class TestMatrixNMS(LayerTest):
  553. def test_matrix_nms(self):
  554. N, M, C = 7, 1200, 21
  555. BOX_SIZE = 4
  556. nms_top_k = 400
  557. keep_top_k = 200
  558. score_threshold = 0.01
  559. post_threshold = 0.
  560. scores_np = np.random.random((N * M, C)).astype('float32')
  561. scores_np = np.apply_along_axis(softmax, 1, scores_np)
  562. scores_np = np.reshape(scores_np, (N, M, C))
  563. scores_np = np.transpose(scores_np, (0, 2, 1))
  564. boxes_np = np.random.random((N, M, BOX_SIZE)).astype('float32')
  565. boxes_np[:, :, 0:2] = boxes_np[:, :, 0:2] * 0.5
  566. boxes_np[:, :, 2:4] = boxes_np[:, :, 2:4] * 0.5 + 0.5
  567. with self.static_graph():
  568. boxes = paddle.static.data(
  569. name='boxes', shape=[N, M, BOX_SIZE], dtype='float32')
  570. scores = paddle.static.data(
  571. name='scores', shape=[N, C, M], dtype='float32')
  572. out, index, _ = ops.matrix_nms(
  573. bboxes=boxes,
  574. scores=scores,
  575. score_threshold=score_threshold,
  576. post_threshold=post_threshold,
  577. nms_top_k=nms_top_k,
  578. keep_top_k=keep_top_k,
  579. return_index=True)
  580. out_np, index_np = self.get_static_graph_result(
  581. feed={'boxes': boxes_np,
  582. 'scores': scores_np},
  583. fetch_list=[out, index],
  584. with_lod=True)
  585. with self.dynamic_graph():
  586. boxes_dy = base.to_variable(boxes_np)
  587. scores_dy = base.to_variable(scores_np)
  588. out_dy, index_dy, _ = ops.matrix_nms(
  589. bboxes=boxes_dy,
  590. scores=scores_dy,
  591. score_threshold=score_threshold,
  592. post_threshold=post_threshold,
  593. nms_top_k=nms_top_k,
  594. keep_top_k=keep_top_k,
  595. return_index=True)
  596. out_dy_np = out_dy.numpy()
  597. index_dy_np = index_dy.numpy()
  598. self.assertTrue(np.array_equal(out_np, out_dy_np))
  599. self.assertTrue(np.array_equal(index_np, index_dy_np))
  600. def test_matrix_nms_error(self):
  601. with self.static_graph():
  602. bboxes = paddle.static.data(
  603. name='bboxes', shape=[7, 1200, 4], dtype='float32')
  604. scores = paddle.static.data(
  605. name='data_error', shape=[7, 21, 1200], dtype='int32')
  606. self.assertRaises(
  607. TypeError,
  608. ops.matrix_nms,
  609. bboxes=bboxes,
  610. scores=scores,
  611. score_threshold=0.01,
  612. post_threshold=0.,
  613. nms_top_k=400,
  614. keep_top_k=200,
  615. return_index=True)
  616. paddle.disable_static()
  617. class TestBoxCoder(LayerTest):
  618. def test_box_coder(self):
  619. prior_box_np = np.random.random((81, 4)).astype('float32')
  620. prior_box_var_np = np.random.random((81, 4)).astype('float32')
  621. target_box_np = np.random.random((20, 81, 4)).astype('float32')
  622. # static
  623. with self.static_graph():
  624. prior_box = paddle.static.data(
  625. name='prior_box', shape=[81, 4], dtype='float32')
  626. prior_box_var = paddle.static.data(
  627. name='prior_box_var', shape=[81, 4], dtype='float32')
  628. target_box = paddle.static.data(
  629. name='target_box', shape=[20, 81, 4], dtype='float32')
  630. boxes = ops.box_coder(
  631. prior_box=prior_box,
  632. prior_box_var=prior_box_var,
  633. target_box=target_box,
  634. code_type="decode_center_size",
  635. box_normalized=False)
  636. boxes_np, = self.get_static_graph_result(
  637. feed={
  638. 'prior_box': prior_box_np,
  639. 'prior_box_var': prior_box_var_np,
  640. 'target_box': target_box_np,
  641. },
  642. fetch_list=[boxes],
  643. with_lod=False)
  644. # dygraph
  645. with self.dynamic_graph():
  646. prior_box_dy = base.to_variable(prior_box_np)
  647. prior_box_var_dy = base.to_variable(prior_box_var_np)
  648. target_box_dy = base.to_variable(target_box_np)
  649. boxes_dy = ops.box_coder(
  650. prior_box=prior_box_dy,
  651. prior_box_var=prior_box_var_dy,
  652. target_box=target_box_dy,
  653. code_type="decode_center_size",
  654. box_normalized=False)
  655. boxes_dy_np = boxes_dy.numpy()
  656. self.assertTrue(np.array_equal(boxes_np, boxes_dy_np))
  657. def test_box_coder_error(self):
  658. with self.static_graph():
  659. prior_box = paddle.static.data(
  660. name='prior_box', shape=[81, 4], dtype='int32')
  661. prior_box_var = paddle.static.data(
  662. name='prior_box_var', shape=[81, 4], dtype='float32')
  663. target_box = paddle.static.data(
  664. name='target_box', shape=[20, 81, 4], dtype='float32')
  665. self.assertRaises(TypeError, ops.box_coder, prior_box,
  666. prior_box_var, target_box)
  667. paddle.disable_static()
  668. class TestGenerateProposals(LayerTest):
  669. def test_generate_proposals(self):
  670. scores_np = np.random.rand(2, 3, 4, 4).astype('float32')
  671. bbox_deltas_np = np.random.rand(2, 12, 4, 4).astype('float32')
  672. im_shape_np = np.array([[8, 8], [6, 6]]).astype('float32')
  673. anchors_np = np.reshape(np.arange(4 * 4 * 3 * 4),
  674. [4, 4, 3, 4]).astype('float32')
  675. variances_np = np.ones((4, 4, 3, 4)).astype('float32')
  676. with self.static_graph():
  677. scores = paddle.static.data(
  678. name='scores', shape=[2, 3, 4, 4], dtype='float32')
  679. bbox_deltas = paddle.static.data(
  680. name='bbox_deltas', shape=[2, 12, 4, 4], dtype='float32')
  681. im_shape = paddle.static.data(
  682. name='im_shape', shape=[2, 2], dtype='float32')
  683. anchors = paddle.static.data(
  684. name='anchors', shape=[4, 4, 3, 4], dtype='float32')
  685. variances = paddle.static.data(
  686. name='var', shape=[4, 4, 3, 4], dtype='float32')
  687. rois, roi_probs, rois_num = ops.generate_proposals(
  688. scores,
  689. bbox_deltas,
  690. im_shape,
  691. anchors,
  692. variances,
  693. pre_nms_top_n=10,
  694. post_nms_top_n=5,
  695. return_rois_num=True)
  696. rois_stat, roi_probs_stat, rois_num_stat = self.get_static_graph_result(
  697. feed={
  698. 'scores': scores_np,
  699. 'bbox_deltas': bbox_deltas_np,
  700. 'im_shape': im_shape_np,
  701. 'anchors': anchors_np,
  702. 'var': variances_np
  703. },
  704. fetch_list=[rois, roi_probs, rois_num],
  705. with_lod=True)
  706. with self.dynamic_graph():
  707. scores_dy = base.to_variable(scores_np)
  708. bbox_deltas_dy = base.to_variable(bbox_deltas_np)
  709. im_shape_dy = base.to_variable(im_shape_np)
  710. anchors_dy = base.to_variable(anchors_np)
  711. variances_dy = base.to_variable(variances_np)
  712. rois, roi_probs, rois_num = ops.generate_proposals(
  713. scores_dy,
  714. bbox_deltas_dy,
  715. im_shape_dy,
  716. anchors_dy,
  717. variances_dy,
  718. pre_nms_top_n=10,
  719. post_nms_top_n=5,
  720. return_rois_num=True)
  721. rois_dy = rois.numpy()
  722. roi_probs_dy = roi_probs.numpy()
  723. rois_num_dy = rois_num.numpy()
  724. self.assertTrue(np.array_equal(np.array(rois_stat), rois_dy))
  725. self.assertTrue(np.array_equal(np.array(roi_probs_stat), roi_probs_dy))
  726. self.assertTrue(np.array_equal(np.array(rois_num_stat), rois_num_dy))
  727. if __name__ == '__main__':
  728. unittest.main()