枚举参考文件夹中的文件,并与待比较文件件中的同名文件比较是否一致。

#! /usr/bin/python3.6
# -*- coding:utf-8 -*- import os
import sys
import json
import numpy as np
from sqlalchemy import false def cmp_file(ref_file: str, dst_file: str) -> bool:
ref_base_name = os.path.basename(ref_file)
dst_base_name = os.path.basename(dst_file)
assert os.path.exists(ref_file), f"ref file not exist: {ref_base_name}"
if not os.path.exists(dst_file):
print(f'dst file not exist: {dst_base_name}')
return false ref_data = np.fromfile(ref_file, dtype=np.ubyte, count=-1)
dst_data = np.fromfile(dst_file, dtype=np.ubyte, count=-1)
is_equal = np.array_equal(ref_data, dst_data)
print(is_equal, ": ", ref_base_name)
return is_equal def cmp_dir(ref_dir: str, dst_dir: str) -> None:
print(f'\n==========>>> Start compare {ref_dir} and {dst_dir}')
ref_names = os.listdir(ref_dir)
for name in ref_names:
ref_file = os.path.join(ref_dir, name)
dst_file = os.path.join(dst_dir, name)
cmp_file(ref_file, dst_file) def main():
if len(sys.argv) < 2:
print('usage: dump_dir_cmp.py dir_config.json')
return json_file = sys.argv[1]
with open(json_file) as fp:
js_data = json.load(fp)
for dst_dir in js_data['dst_dirs']:
cmp_dir(js_data['ref_dir'], dst_dir) if (__name__ == '__main__'):
main()

配置样例:

{
"ref_dir": "./dump_data/NPU_DUMPF001_P0/tensorflow_squeezenet_task0_loop0",
"dst_dirs": [
"./dump_data/NPU_DUMPF002_P0/tensorflow_squeezenet_task0_loop0",
"./dump_data/NPU_DUMPF002_P0/tensorflow_squeezenet_task1_loop0",
"./dump_data/NPU_DUMPF002_P0/tensorflow_squeezenet_task2_loop0",
"./dump_data/NPU_DUMPF002_P0/tensorflow_squeezenet_task3_loop0",
"./dump_data/NPU_DUMPF002_P0/tensorflow_squeezenet_task4_loop0",
"./dump_data/NPU_DUMPF002_P0/tensorflow_squeezenet_task5_loop0"
]
}

样例2(re匹配):

#! /usr/bin/python3.6
# -*- coding:utf-8 -*-
# cmp_dump_pickle_dir.py import os
import re
import sys
import numpy as np
from numpy.linalg import norm
import pickle
import shutil
from sklearn.metrics.pairwise import cosine_similarity def vec_similarity(v1: np.array, v2: np.array):
sim = cosine_similarity(v1.reshape(1, v1.size), v2.reshape(1, v2.size))
return sim[0][0]
# norm2 = norm(v1) * norm(v2)
# cosine = np.dot(v1,v2) / norm2
# return cosine def re_find_file(dir: str, op_name: str) -> str:
for fname in os.listdir(dir): # 分组匹配: (...|...)
re_dst = re.search(f"{op_name}_(out_[\S]*|out\d).bin$", fname)
if re_dst is not None:
return re_dst.group()
return None def cmp_file(ref_file: str, dst_file: str, dtype: str) -> bool:
ref_base_name = os.path.basename(ref_file)
dst_base_name = os.path.basename(dst_file)
assert os.path.exists(ref_file), f"ref file not exist: {ref_base_name}"
assert os.path.exists(dst_file), f"dst file not exist: {dst_base_name}" ref_data = np.fromfile(ref_file, dtype=dtype, count=-1)
dst_data = np.fromfile(dst_file, dtype=dtype, count=-1)
if dtype == 'float32' or dtype == 'float16':
sim = vec_similarity(ref_data, dst_data)
print(sim > 0.95, f", simularity={sim} : ", ref_base_name)
return (sim > 0.95) is_equal = np.array_equal(ref_data, dst_data)
print(is_equal, ": ", ref_base_name)
return is_equal def cmp_dir(ref_dir: str, dst_dir: str) -> None:
print(f'\n==========>>> Start compare {ref_dir} and {dst_dir}')
patten = re.compile(r"_op_out_[\S]*.bin$")
ref_names = os.listdir(ref_dir)
not_exist_ops = []
for ref_name in ref_names:
assert re.match(r"[\S]*_op_out_[\S]*.bin$", ref_name) is not None, f"bad file name: {ref_name}"
dtype = ref_name[ref_name.rfind('_') + 1:ref_name.rfind('.')]
mdl_name = ref_name[0:patten.search(ref_name).span()[0]]
dst_name = re_find_file(dst_dir, mdl_name)
if dst_name is None:
not_exist_ops.append(mdl_name)
continue ref_file = os.path.join(ref_dir, ref_name)
dst_file = os.path.join(dst_dir, dst_name)
cmp_file(ref_file, dst_file, dtype=dtype) print(f'\nNot exist ops: {not_exist_ops}') def dump_pickle_file(pickle_file: str, out_bin_dir: str, force_dtype_u8: bool) -> None:
def is_float_type(data_buff: np.ndarray) -> bool:
return data_buff.dtype == np.float16 or data_buff.dtype == np.float32 with open(pickle_file, "rb") as f:
op_ref = pickle.load(f)
for i, (key, value) in enumerate(op_ref.items()):
data_buff = value.flatten()
# print("layer: ", key, " shape: ", value.shape, " type: ", value.dtype, " size: ", value.size)
dtype = 'uint8' if force_dtype_u8 and is_float_type(data_buff) else data_buff.dtype
print("pickle key: %30s, size: %7d, dtype: %s" % (key, value.itemsize * value.size, data_buff.dtype))
data_buff.tofile(os.path.join(out_bin_dir, key.replace("/", "_") + f"_op_out_{dtype}.bin")) #print("op ref: type ", type(op_ref), op_ref.size)
#print("op shape: type ", op_ref['data'].shape) def mkdir(dir: str) -> None:
if os.path.exists(dir):
shutil.rmtree(dir)
os.mkdir(dir) def main():
assert len(sys.argv) >= 4, 'usage: dump_dir_cmp.py pickle_file pickle_out_dir dst_dump_dir [force_dtype_u8]'
force_dtype_u8 = True if len(sys.argv) >= 5 and sys.argv[4] == 'force_dtype_u8' else False #np.seterr('raise')
mkdir(sys.argv[2])
dump_pickle_file(sys.argv[1], sys.argv[2], force_dtype_u8)
cmp_dir(sys.argv[2], sys.argv[3]) if (__name__ == '__main__'):
main()

python小练习:涉及print,json,numpy的更多相关文章

  1. Python之数据序列化(json、pickle、shelve)

    本节内容 前言 json模块 pickle模块 shelve模块 总结 一.前言 1. 现实需求 每种编程语言都有各自的数据类型,其中面向对象的编程语言还允许开发者自定义数据类型(如:自定义类),Py ...

  2. 【转】Python之数据序列化(json、pickle、shelve)

    [转]Python之数据序列化(json.pickle.shelve) 本节内容 前言 json模块 pickle模块 shelve模块 总结 一.前言 1. 现实需求 每种编程语言都有各自的数据类型 ...

  3. Python小数据保存,有多少中分类?不妨看看他们的类比与推荐方案...

    小数据存储 我们在编写代码的时候,经常会涉及到数据存储的情况,如果是爬虫得到的大数据,我们会选择使用数据库,或者excel存储.但如果只是一些小数据,或者说关联性较强且存在存储后复用的数据,我们该如何 ...

  4. 让你瞬间萌比的35个python小技巧

    今天在看python算法的时候,看到一篇关于python的小技巧.瞬间萌比了,原来python也可以这样玩,太神奇了.萌比的是原来这么简单的东西自己都不知道,虽然会写.废话不多说了,开始上菜. 1.拆 ...

  5. 5个常常被大家忽略的Python小技巧

    下面我挑选出的这几个技巧常常会被人们忽略,但它们在日常编程中能真正的给我们带来不少帮助. 1. 字典推导(Dictionary comprehensions)和集合推导(Set comprehensi ...

  6. Python 小程序,对文件操作及其它

    以下是自己写的几个对文件操作的小程序,里面涉及到文件操作,列表(集合,字典)的运用等.比方说,从文件里读取一行数据.分别存放于列表中,再对列表进行操作.如去掉里面的反复项.排序等操作. 常见对文件里行 ...

  7. 小学生都能学会的python(小数据池)

    小学生都能学会的python(小数据池) 1. 小数据池. 目的:缓存我们字符串,整数,布尔值.在使用的时候不需要创建过多的对象 缓存:int, str, bool. int: 缓存范围 -5~256 ...

  8. Python 小案例实战 —— 简易银行存取款查询系统

    Python 小案例实战 -- 简易银行存取款查询系统 涉及知识点 包的调用 字典.列表的混合运用 列表元素索引.追加 基本的循环与分支结构 源码 import sys import time ban ...

  9. 这42个Python小例子,太走心

    告别枯燥,60秒学会一个Python小例子.奔着此出发点,我在过去1个月,将平时经常使用的代码段换为小例子,分享出来后受到大家的喜欢. 一.基本操作 1 链式比较 i = 3print(1 <  ...

  10. Python学习day18-常用模块之NumPy

    figure:last-child { margin-bottom: 0.5rem; } #write ol, #write ul { position: relative; } img { max- ...

随机推荐

  1. day05-线程的应用04

    7.线程的应用03 7.4坦克大战5.0版 增加功能: 我方坦克在发射的子弹消亡之后,才能发射新的子弹==>拓展:发射多颗子弹怎么办,控制一次最多只能发射5颗子弹 让敌人坦克发射的子弹消亡之后, ...

  2. ELK日志报警插件ElastAlert并配置钉钉报警

    文章转载自:https://www.cnblogs.com/uglyliu/p/13118386.html ELK日志报警插件ElastAlert 它通过将Elasticsearch与两种类型的组件( ...

  3. 6.第五篇 安装keepalived与Nginx

    文章转载自:https://mp.weixin.qq.com/s?__biz=MzI1MDgwNzQ1MQ==&mid=2247483796&idx=1&sn=347664de ...

  4. Elasticsearch:如何把Elasticsearch中的数据导出为CSV格式的文件

    本教程向您展示如何将数据从Elasticsearch导出到CSV文件. 想象一下,您想要在Excel中打开一些Elasticsearch中的数据,并根据这些数据创建数据透视表. 这只是一个用例,其中将 ...

  5. 使用KubeOperator扩展k8s集群的worker节点

    官方文档网址:https://kubeoperator.io/docs/installation/install/ 背景说明 原先是一个三节点的k8s集群,一个master,三个woker(maste ...

  6. 9. Fluentd部署:日志

    Fluentd是用来处理其他系统产生的日志的,它本身也会产生一些运行时日志.Fluentd包含两个日志层:全局日志和插件级日志.每个层次的日志都可以进行单独配置. 日志级别 Fluentd的日志包含6 ...

  7. vue基础之MV*和它们之间的不同

    vue中的设计思想 vue中的设计思想主要是MV*模式,由最早的MVC(model-view-controller)框架,到后面的MVP(model-view-presenter),甚至到最后的MVV ...

  8. C#-3 深入理解类

    一 类的概述(类是逻辑相关的数据和函数的封装,通常代表真实世界中或概念上的事物) 类是一种能存储数据并执行代码的数据结构,包含数据成员和函数成员. 数据成员存储类或类的实例相关的数据: 函数成员执行代 ...

  9. Java程序设计(三)作业

    题目1:用户输入学号,如果是以ccutsoft开头,并且后边是4位数字,前两位大于06小于等于当前年份.判断用户输入是否合法.ccutsoft_0801. 1 //题目1:用户输入学号,如果是以abc ...

  10. PTA 1126 Eulerian Path

    无向连通图,输出每个顶点的度并判断Eulerian.Semi-Eulerian和Non-Eulerian这3种情况,我们直接记录每个点所连接的点,这样直接得到它的度,然后利用深度优先和visit数组来 ...