python小练习:涉及print,json,numpy
枚举参考文件夹中的文件,并与待比较文件件中的同名文件比较是否一致。
#! /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的更多相关文章
- Python之数据序列化(json、pickle、shelve)
本节内容 前言 json模块 pickle模块 shelve模块 总结 一.前言 1. 现实需求 每种编程语言都有各自的数据类型,其中面向对象的编程语言还允许开发者自定义数据类型(如:自定义类),Py ...
- 【转】Python之数据序列化(json、pickle、shelve)
[转]Python之数据序列化(json.pickle.shelve) 本节内容 前言 json模块 pickle模块 shelve模块 总结 一.前言 1. 现实需求 每种编程语言都有各自的数据类型 ...
- Python小数据保存,有多少中分类?不妨看看他们的类比与推荐方案...
小数据存储 我们在编写代码的时候,经常会涉及到数据存储的情况,如果是爬虫得到的大数据,我们会选择使用数据库,或者excel存储.但如果只是一些小数据,或者说关联性较强且存在存储后复用的数据,我们该如何 ...
- 让你瞬间萌比的35个python小技巧
今天在看python算法的时候,看到一篇关于python的小技巧.瞬间萌比了,原来python也可以这样玩,太神奇了.萌比的是原来这么简单的东西自己都不知道,虽然会写.废话不多说了,开始上菜. 1.拆 ...
- 5个常常被大家忽略的Python小技巧
下面我挑选出的这几个技巧常常会被人们忽略,但它们在日常编程中能真正的给我们带来不少帮助. 1. 字典推导(Dictionary comprehensions)和集合推导(Set comprehensi ...
- Python 小程序,对文件操作及其它
以下是自己写的几个对文件操作的小程序,里面涉及到文件操作,列表(集合,字典)的运用等.比方说,从文件里读取一行数据.分别存放于列表中,再对列表进行操作.如去掉里面的反复项.排序等操作. 常见对文件里行 ...
- 小学生都能学会的python(小数据池)
小学生都能学会的python(小数据池) 1. 小数据池. 目的:缓存我们字符串,整数,布尔值.在使用的时候不需要创建过多的对象 缓存:int, str, bool. int: 缓存范围 -5~256 ...
- Python 小案例实战 —— 简易银行存取款查询系统
Python 小案例实战 -- 简易银行存取款查询系统 涉及知识点 包的调用 字典.列表的混合运用 列表元素索引.追加 基本的循环与分支结构 源码 import sys import time ban ...
- 这42个Python小例子,太走心
告别枯燥,60秒学会一个Python小例子.奔着此出发点,我在过去1个月,将平时经常使用的代码段换为小例子,分享出来后受到大家的喜欢. 一.基本操作 1 链式比较 i = 3print(1 < ...
- Python学习day18-常用模块之NumPy
figure:last-child { margin-bottom: 0.5rem; } #write ol, #write ul { position: relative; } img { max- ...
随机推荐
- Zookeeper及基于Zookeeper的分布式锁总结
1. Zookeeper ZooKeeper 内部存储的数据结构 / +-- node1 +-- node2 | +-- sub_node21 -> "I am sub_node21& ...
- 并发原理 — CPU原子性指令(一)
本篇文章将以Intel CPU作为讨论基础 一.并发的由来 一台计算机有2个cpu,其中CPU1执行程序A,CPU2执行程序B,由于程序A和程序B是两个不同的应用程序,所以它们两个之间并不存在并发问题 ...
- linux系统排查数据包常用命令
1.查看当前系统中生效的所有参数 sysctl -a 2.统计处于TIME_WAIT状态的TCP连接数 netstat -ant|grep TIME_WAIT|wc -l 3.统计TCP连接数 net ...
- C#/VB.NET 读取条码类型及条码在图片中的坐标位置
我们在创建条形码时,如果以图片的方式将创建好的条码保存到指定文件夹路径,可以在程序中直接加载图片使用:已生成的条码图片,需要通过读取图片中的条码信息,如条码类型.条码绘制区域在图片中的四个顶点坐标位置 ...
- JavaWeb505错误,IDEA版问题解决
问题描述: 在学习JavaWeb的过程中,使用JSP文件转至servlet文件的过程中,发现无论如何都无法打开文件 JSP文件代码 <%@page contentType="text/ ...
- .NET MAUI 社区工具包 1.3版本发布
2022 年 10 月 4 日,微软发布了 .NET MAUI 社区工具包的 1.3 版,具体参见微软官方博客:https://devblogs.microsoft.com/dotnet/announ ...
- surging 将推出社区版微服务平台
前言 对于.NET大家并不陌生,有大批的企业选择.NET作为公司构建多种应用的开发平台,但是近几年随着微服务,大数据,移动端,物联网兴起,而后.NET社区生态没有跟上时代的步伐,已开始趋于没落,而其中 ...
- Vue学习之--------深入理解Vuex之getters、mapState、mapGetters(2022/9/3)
这一篇博客的内容是在上一篇博客的基础上进行:深入理解Vuex.原理详解.实战应用 @ 目录 1.getters的使用 1.1 概念 1.2 用法 1.3 如何读取数据 2.getters在项目中的实际 ...
- 刷完一千道java笔试题的常见题目分析
java基础刷题遇到的最常见问题 可以先看一下这位博主整理的java面试题(很详细,我看了好几遍了):https://blog.csdn.net/ThinkWon/article/details/10 ...
- 2021年9月28日,老是遇到一些非常奇葩的问题。就离谱、好好的一个web项目就莫名奇妙坏了。
起因是这样的:我前几天用idea2020编辑器,用ssm框架搭建了一个图书管理系统.只是将图书信息的增删改查实现,还有用户的注册和登录功能实现.本来想着今天将用户信息的删除和修改完善以下,本来是很简单 ...