东方耀AI技术分享

 找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
热搜: 活动 交友 discuz
查看: 10810|回复: 2
打印 上一主题 下一主题

[课堂笔记] pytorch转caffe成功之后的验证

[复制链接]

1365

主题

1856

帖子

1万

积分

管理员

Rank: 10Rank: 10Rank: 10

积分
14437
QQ
跳转到指定楼层
楼主
发表于 2020-8-10 11:27:25 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
pytorch转caffe成功之后的验证

思路:用同一张图片作为输入,经过相同的预处理
各自模型的前向计算,比较输出的结果是否相同?






  1. import torch
  2. import numpy as np
  3. from config import get_config_lite
  4. from Learner import face_learner
  5. import torch.nn.functional as F
  6. from torch.nn import CrossEntropyLoss
  7. from torchvision import transforms as trans
  8. import os
  9. import cv2

  10. os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
  11. # 选择哪一块gpu,如果是-1,就是调用cpu
  12. os.environ['CUDA_VISIBLE_DEVICES'] = "0"


  13. # 看同一张图片 输入后  torch与caffe的输出的512维度向量
  14. img_path = "/home/jingyun/py2_caffe_face_works/onnx2caffe-master/model/10.jpg"

  15. # conf = get_config_dfy(training=False)
  16. conf = get_config_lite(training=False)
  17. # conf = get_config_dfy(training=False)
  18. print("easydict的配置参数:", conf)
  19. learner = face_learner(conf, inference=True)

  20. fixed_str = "2020-08-09-11-00_accuracy:0.9094341157427415_step:1324780_final.pth"
  21. learner.load_state(conf, fixed_str, model_only=True, from_save_folder=True)
  22. learner.model.eval()

  23. test_transform = trans.Compose([
  24.     trans.ToTensor(),
  25.     trans.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
  26. ])


  27. img = cv2.imread(img_path)
  28. print("cv2.imread之后:", img.shape)
  29. # 图片的预处理
  30. img = test_transform(img)


  31. print("torch预处理后:", img.size())
  32. img = torch.unsqueeze(img, dim=0)
  33. print("torch 扩展维度后:", img.size(), type(img))


  34. with torch.no_grad():
  35.     result = learner.model(img.to(conf.device))
  36.     print("result_512:", result.size())
  37.     result = result.cpu().numpy()[0]
  38.     print(type(result), result.shape, result)
  39.     # result是否归一化了: 25.143478
  40.     print("result是否归一化了:", np.linalg.norm(result))
  41.     # numpy l2_norm()的实现
  42.     result = np.divide(result, np.linalg.norm(result))
  43.     print(result)

  44. # torch的结果:
  45. #  4.18923460e-02 -4.78874184e-02 -2.89320014e-02 -5.47427386e-02
  46. #  -2.47906484e-02  2.65899673e-03 -5.64723015e-02 -1.81384571e-02
  47. #  -5.86921759e-02 -1.66410357e-02  5.65116517e-02 -5.67275733e-02
  48. #   2.84908544e-02 -3.57359536e-02 -2.56096441e-02 -1.55471719e-03



  49. # caffe的结果:
  50. # 4.18923870e-02 -4.78875041e-02 -2.89320182e-02 -5.47428243e-02
  51. #  -2.47906558e-02  2.65889615e-03 -5.64723164e-02 -1.81384161e-02
  52. #  -5.86921349e-02 -1.66409668e-02  5.65117151e-02 -5.67275919e-02
  53. #   2.84908172e-02 -3.57360132e-02 -2.56096572e-02 -1.55465060e-03]

复制代码


  1. # -*- coding: utf-8 -*-
  2. from __future__ import print_function, division
  3. __author__ = u'东方耀 微信:dfy_88888'
  4. __date__ = '2020/8/10 上午10:34'
  5. __product__ = 'PyCharm'
  6. __filename__ = 'caffe_inference_extract_512_feature'


  7. import caffe
  8. import os
  9. import cv2
  10. import numpy as np

  11. os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
  12. # 选择哪一块gpu,如果是-1,就是调用cpu
  13. os.environ['CUDA_VISIBLE_DEVICES'] = "0"


  14. deploy = "./caffe_model/FaceRecog_dfy06-sim.prototxt"
  15. trained_model = "./caffe_model/FaceRecog_dfy06-sim.caffemodel"
  16. caffe.set_mode_gpu()
  17. caffe.set_device(0)

  18. net_caffe = caffe.Net(deploy, 1, weights=trained_model)


  19. # 看同一张图片 输入后  torch与caffe的输出的512维度向量
  20. img_path = "/home/jingyun/py2_caffe_face_works/onnx2caffe-master/model/10.jpg"

  21. img = cv2.imread(img_path)
  22. print("cv2.imread after", img.shape)
  23. # brg (0-255)

  24. # test_transform = trans.Compose([
  25. #     trans.ToTensor(),
  26. #     trans.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
  27. # ])


  28. # 图片的预处理
  29. img2 = img.copy()
  30. # img = test_transform(img)

  31. img2 = img2 / 255.0
  32. img2 = (img2 - 0.5) / 0.5
  33. img2 = np.transpose(img2, axes=[2, 0, 1])

  34. # cv2.imread after (112, 112, 3)
  35. # torch预处理后: (3, 112, 112)
  36. # print("torch预处理后:", img.size(), img)
  37. # [-0.7333, -0.8588, -0.8824,  ..., -0.2863,  0.4196,  0.8588],
  38. #          [-0.7176, -0.8431, -0.8745,  ..., -0.3569,  0.3569,  0.8588],
  39. #          [-0.7176, -0.8431, -0.8745,  ..., -0.4667,  0.2471,  0.8196],
  40. #          ...,
  41. #          [ 0.5765,  0.5765,  0.5529,  ...,  0.6941,  0.7020,  0.7176],
  42. #          [ 0.5765,  0.5686,  0.5529,  ...,  0.7020,  0.7020,  0.7255],
  43. #          [ 0.5686,  0.5686,  0.5529,  ...,  0.7020,  0.7098,  0.7255]
  44. img2 = np.expand_dims(img2, axis=0)
  45. print("numpy预处理后:", img2.shape)
  46. # img = torch.unsqueeze(img, dim=0)
  47. # print("torch 扩展维度后:", img.size(), type(img))

  48. net_caffe.blobs["input0"].data[...] = img2

  49. result = net_caffe.forward()['output0'][0]

  50. print("result_caffe:", result.shape, type(result))
  51. # result是否归一化了: 25.14348
  52. print("result是否归一化了:", np.linalg.norm(result))
  53. result = np.divide(result, np.linalg.norm(result))
  54. print(result)

  55. # 4.18923870e-02 -4.78875041e-02 -2.89320182e-02 -5.47428243e-02
  56. #  -2.47906558e-02  2.65889615e-03 -5.64723164e-02 -1.81384161e-02
  57. #  -5.86921349e-02 -1.66409668e-02  5.65117151e-02 -5.67275919e-02
  58. #   2.84908172e-02 -3.57360132e-02 -2.56096572e-02 -1.55465060e-03]




复制代码







让天下人人学会人工智能!人工智能的前景一片大好!
回复

使用道具 举报

1365

主题

1856

帖子

1万

积分

管理员

Rank: 10Rank: 10Rank: 10

积分
14437
QQ
沙发
 楼主| 发表于 2020-8-10 14:57:57 | 只看该作者
  1. #coding:utf-8

  2. import caffe
  3. import cv2
  4. import numpy as np
  5. from scipy.spatial.distance import pdist
  6. import numpy as np
  7. from PIL import Image
  8. from collections import namedtuple
  9. import time
  10. net = caffe.Net('FaceRecog_dfy06-sim.prototxt', 'FaceRecog_dfy06-sim.caffemodel',caffe.TEST)
  11. def caffeGetFeature(imgPath):
  12.         bgr = cv2.imread(imgPath)
  13.         #cv2.imshow("BGR",img)
  14.         #cv2.waitKey(0)

  15.         # BGR 0 1 2
  16.         # RGB 2
  17.         rgb = bgr[...,::-1]
  18.         # scale = 1 / 128.0 = 0.0078125
  19.         rgb = (rgb - 128.0) / 128.0
  20.         rgb = np.transpose(rgb, axes=[2, 0, 1])
  21.         # rgb = rgb.transpose((2,1,0))
  22.         # rgb = np.swapaxes(rgb, 0, 2)
  23.         # rgb = np.swapaxes(rgb, 1, 2)
  24.         # rgb = rgb[None,:] # add singleton dimension
  25.         rgb = np.expand_dims(rgb, axis=0)

  26.         #cv2.imshow("RGB",rgb)
  27.         #cv2.waitKey(0)
  28.         #print (rgb)
  29.         # out = net.forward_all( data = rgb ) # out is probability
  30.         net.blobs["input0"].data[...] = rgb

  31.         result = net.forward()['output0'][0]
  32.         #print(out['fc1'][0])
  33.         # a = out['output0'][0]
  34.         return result


  35. print("caffe forword result:", caffeGetFeature("./images/10.jpg"))
复制代码
让天下人人学会人工智能!人工智能的前景一片大好!
回复

使用道具 举报

1365

主题

1856

帖子

1万

积分

管理员

Rank: 10Rank: 10Rank: 10

积分
14437
QQ
板凳
 楼主| 发表于 2020-8-10 15:00:24 | 只看该作者

-2.36872983e+00  -1.75416946e+00   2.15635824e+00  -4.48371619e-02
  -5.19178569e-01  -7.63961196e-01   4.42535505e-02   4.14647192e-01
   4.16591078e-01   4.52785224e-01   6.10753894e-01  -1.32915735e+00
   2.55063891e+00   4.76892054e-01  -3.57504308e-01  -1.64712965e+00
  -3.39873940e-01   1.36864388e+00  -1.14875889e+00  -2.29086727e-01
   1.20023048e+00   3.08750719e-01   5.54423034e-01   1.23881590e+00
   9.36651051e-01   7.87511617e-02   1.13178682e+00   7.52464712e-01
   9.71228063e-01  -9.95164633e-01  -3.82107556e-01   7.82528222e-01
   9.88112748e-01  -8.99936497e-01  -1.86793208e-01  -2.27842927e+00
  -8.61048102e-01   4.04678315e-01  -1.56575155e+00  -1.47956216e+00
  -1.26751435e+00  -7.26402700e-02   1.32661295e+00  -2.19057918e+00
   7.20586538e-01  -5.92324138e-01  -7.70517468e-01  -1.42683581e-01
让天下人人学会人工智能!人工智能的前景一片大好!
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|人工智能工程师的摇篮 ( 湘ICP备2020019608号-1 )

GMT+8, 2024-5-4 23:56 , Processed in 0.164683 second(s), 18 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表