raw文件对比脚本(transpose、view与permute的异同)

1。计算两个feature之间的相似度,对比两个raw文件的差异。

(使用余玄相似性对比,越接近1越相似。)

import numpy as np
import cv2
import torch
import torch.nn as nn
import os
import random
import argparse
import copy

if __name__ == "__main__":
    #'''
    result_PC_path_8 = "/home/szhang/project/data/test/test100/PC/outs_raw/8/8_59.raw"
    result_8155_path_8 = "/home/szhang/project/data/test/test100/8155test/detection_CPU_DSP_0527/output/CPU/Result_0/190.raw"
    result_PC_Data_8 = np.fromfile(result_PC_path_8, dtype=np.float32)
    result_8155_Data_8 = np.fromfile(result_8155_path_8, dtype=np.float32)

    result_PC_path_16 = "/home/szhang/project/data/test/test100/PC/outs_raw/16/16_59.raw"
    result_8155_path_16 = "/home/szhang/project/data/test/test100/8155test/detection_CPU_DSP_0527/output/CPU/Result_0/labels.raw"
    result_PC_Data_16 = np.fromfile(result_PC_path_16, dtype=np.float32)
    result_8155_Data_16 = np.fromfile(result_8155_path_16, dtype=np.float32)

    result_PC_path_32 = "/home/szhang/project/data/test/test100/PC/outs_raw/32/32_59.raw"
    result_8155_path_32 = "/home/szhang/project/data/test/test100/8155test/detection_CPU_DSP_0527/output/CPU/Result_0/boxes.raw"
    result_PC_Data_32 = np.fromfile(result_PC_path_32, dtype=np.float32)
    result_8155_Data_32 = np.fromfile(result_8155_path_32, dtype=np.float32)

    result_PC_Data  = [result_PC_Data_8, result_PC_Data_16, result_PC_Data_32]
    result_8155_Data = [result_8155_Data_8, result_8155_Data_16, result_8155_Data_32]
    '''
    result_PC_path = "/home/szhang/project/data/test/test100/PC/pre_img_data/ch1_20181211_002304_0107_1020_053preprocess.raw"
    result_8155_path = "/home/szhang/project/data/test/test100/8155test/snpe_raws/ch1_20181211_002304_0107_1020_053preprocess.raw"
    result_PC_Data = np.fromfile(result_PC_path, dtype=np.float32)
    result_8155_Data = np.fromfile(result_8155_path, dtype=np.float32)

    result_PC_Data  = [result_PC_Data]
    result_8155_Data = [result_8155_Data]
    '''

    # width8, width16, width32 = [512 // i for i in [8,16,32]]
    # height8, height16, height32 = [192 // i for i in [8,16,32]]
    # channels = (8+4+1)*3

    # result_PC_Data = result_PC_Data.reshape(height8, width8, channels).transpose(2, 0, 1)
    # result_8155_Data = result_8155_Data.reshape(height8, width8, channels).transpose(2, 0, 1)
    result = []
    for i in range(3):
        a = torch.from_numpy(result_PC_Data[i]).unsqueeze(0)
        b = torch.from_numpy(result_8155_Data[i]).unsqueeze(0)

        cos = nn.CosineSimilarity(dim=1)
        pcsim_feat_S = cos(a, b)
        result.append(pcsim_feat_S)

torch.squeeze() 函数主要是对数据的维度进行压缩,去掉维数为1的的维度。
torch.unsqueeze()这个函数主要是对数据维度进行扩充。给指定位置加上维数为一的维度。

2.Pytorch之permute函数

#YOLO输出的outs维度NHWC
result32_path = '/home/szhan/test/test100/8155test/8155test_img_result/32.raw'
result32Data = np.fromfile(result32_path, dtype=np.float32)
channels = (cfg.model.bbox_head.num_classes + 5) * 3
#这里要transpose一下,因为result32Data 是NHWC不会改变内存中的数据排布,transpose可以改变内存排布要和下面的result_raw.view代码对应上。
result32Data = result32Data.reshape(height32, width32, channels).transpose(2, 0, 1)  #这里的transpose是numpy的函数,与下面要讲的torch的transpose函数不同。

prediction_raw = result_raw.view(num_anchors_per_scale,num_attrib,num_grid_h,num_grid_w).permute(0, 2, 3, 1).contiguous()

1 先看看官方中英文doc:

 torch.Tensor.permute (Python method, in torch.Tensor)

1.1 permute(dims)

将tensor的维度换位。

参数: - dims (int …*) - 换位顺序

例:

>>> x = torch.randn(2, 3, 5) 
>>> x.size() 
torch.Size([2, 3, 5]) 
>>> x.permute(2, 0, 1).size() 
torch.Size([5, 2, 3])

1.2 permute(*dims) → Tensor

Permute the dimensions of this tensor.

Parameters: *dims (int…) – The desired ordering of dimensions

Example:

>>> x = torch.randn(2, 3, 5) 
>>> x.size() 
torch.Size([2, 3, 5]) 
>>> x.permute(2, 0, 1).size() 
torch.Size([5, 2, 3])

2 pytorch permute的使用

permute函数功能还是比较简单的,下面主要介绍几个细节点:

2.1 transpose与permute的异同

Tensor.permute(a,b,c,d, …):permute函数可以对任意高维矩阵进行转置,但没有 torch.permute() 这个调用方式, 只能 Tensor.permute():

>>> torch.randn(2,3,4,5).permute(3,2,0,1).shape
torch.Size([5, 4, 2, 3])

torch.transpose(Tensor, a,b):transpose只能操作2D矩阵的转置,有两种调用方式;

另:连续使用transpose也可实现permute的效果:

>>> torch.randn(2,3,4,5).transpose(3,0).transpose(2,1).transpose(3,2).shape
torch.Size([5, 4, 2, 3])
>>> torch.randn(2,3,4,5).transpose(1,0).transpose(2,1).transpose(3,1).shape
torch.Size([3, 5, 2, 4])

从以上操作中可知,permute相当于可以同时操作于tensor的若干维度,transpose只能同时作用于tensor的两个维度;

2.2 permute函数与contiguous、view函数之关联

contiguous:view只能作用在contiguous的variable上,如果在view之前调用了transpose、permute等,就需要调用contiguous()来返回一个contiguous copy;

一种可能的解释是:有些tensor并不是占用一整块内存,而是由不同的数据块组成,而tensor的view()操作依赖于内存是整块的,这时只需要执行contiguous()这个函数,把tensor变成在内存中连续分布的形式;

判断ternsor是否为contiguous,可以调用torch.Tensor.is_contiguous()函数:

import torch 
x = torch.ones(10, 10) 
x.is_contiguous()                                 # True 
x.transpose(0, 1).is_contiguous()                 # False
x.transpose(0, 1).contiguous().is_contiguous()    # True

另:在pytorch的最新版本0.4版本中,增加了torch.reshape(),与 numpy.reshape() 的功能类似,大致相当于 tensor.contiguous().view(),这样就省去了对tensor做view()变换前,调用contiguous()的麻烦;
因此,view()和reshape()函数不改变内存中的数据排布,但是permute()和transpose()函数可以改变内存中的数据排布。

3 permute与view函数功能demo

import torch
import numpy as np

a=np.array([[[1,2,3],[4,5,6]]])
unpermuted=torch.tensor(a)
print(unpermuted.size())              #  ——>  torch.Size([1, 2, 3])

permuted=unpermuted.permute(2,0,1)
print(permuted.size())                #  ——>  torch.Size([3, 1, 2])

view_test = unpermuted.view(1,3,2)
print(view_test.size())               #  ——>  torch.Size([1, 3, 2])

利用函数 permute(2,0,1) 可以把 Tensor([[[1,2,3],[4,5,6]]]) 转换成:

tensor([[[ 1,  4]],
        [[ 2,  5]],
        [[ 3,  6]]])     # print(permuted)    

如果使用view(1,3,2) 可以得到:

tensor([[[ 1,  2],
         [ 3,  4],
         [ 5,  6]]])   # print(view_test)

tensor数据如何保存成txt文件

bn_weights为一个tensor:

save_bn_weights = bn_weights.cpu().numpy()   #tensor张量转numpy数组
save_bn_weights=save_bn_weights.tolist()     #numpy数组转python的list
strNums=[str(x_i) for x_i in save_bn_weights]#python的list中数据是float32类型的,需要转成字符串str类型。
str1=",".join(strNums)                       #将字符串以逗号“,”间隔排布
f_save = open('/home/szhang/project/gitlab/git/mmdetection-dev/bn_weights.txt', 'w')
f_save.write(str1)
f_save.close()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值