python - 计算 pickle 文件的熵

标签 python pickle entropy

我正在处理 ISCXVPN2016 dataset ,它由一些 pcap 文件组成(每个 pcap 捕获特定应用程序的流量,例如 Skype、youtube 等),我已将它们转换为 pickle 文件,然后使用以下代码将它们写入文本文件:

pkl = open("AIMchat2.pcapng.pickle", "rb")
with open('file.txt', 'w') as f:
    for Item in pkl:
        f.write('%s\n' %Item)

文件.txt:

b'\x80\x03]q\x00(cnumpy.core.multiarray\n' b'_reconstruct\n' b'q\x01cnumpy\n' b'ndarray\n' b'q\x02K\x00\x85q\x03C\x01bq\x04\x87q\x05Rq\x06(K\x01K\x9d\x85q\x07cnumpy\n' b'dtype\n' b'q\x08X\x02\x00\x00\x00u1q\tK\x00K\x01\x87q\n' b'Rq\x0b(K\x03X\x01\x00\x00\x00|q\x0cNNNJ\xff\xff\xff\xffJ\xff\xff\xff\xffK\x00tq\rb\x89C\x9dE\x00\x00\x9dU\xbc@\x00\x80\x06\xd7\xc9\x83\xca\xf0W@\x0c\x18\xa74I\x01\xbb\t].\xc8\xf3*\xc51P\x18\xfa[)j\x00\x00\x17\x03\x02\x00p\x14\x90\xccY|\xa3\x7f\xd1\x12\xe2\xb4.U9)\xf20\xf1{\xbd\x1d\xa3W\x0c\x19\xc2\xf0\x8c\x0b\x8c\x86\x16\x99\xd8:\x19\xb0G\xe7\xb2\xf4\x9d\x82\x8e&a\x04\xf2\xa2\x8e\xce\xa4b\xcc\xfb\xe4\xd0\xde\x89eUU]\x1e\xfeF\x9bv\x88\xf4\xf3\xdc\x8f\xde\xa6Kk1q`\x94]\x13\xd7|\xa3\x16\xce\xcc\x1b\xa7\x10\xc5\xbd\x00\xe8M\x8b\x05v\x95\xa3\x8c\xd0\x83\xc1\xf1\x12\xee\x9f\xefmq\x0etq\x0fbh\x01h\x02K\x00\x85q\x10h\x04\x87q\x11Rq\x12(K\x01K.\x85q\x13h\x0b\x89C.E\x00\x00

我的问题是如何计算每个 pickle 文件的熵?

(我已经更新了问题)

最佳答案

如果我没有做错任何事,这就是答案(基于 How to calculate the entropy of a file?Shannon entropy )。

#!/usr/bin/env python3

import math


filename = "random_data.bin"

with open(filename, "rb") as file:
    counters = {byte: 0 for byte in range(2 ** 8)}  # start all counters with zeros

    for byte in file.read():  # read in chunks for large files
        counters[byte] += 1  # increase counter for specified byte

    filesize = file.tell()  # we can get file size by reading current position

    probabilities = [counter / filesize for counter in counters.values()]  # calculate probabilities for each byte

    entropy = -sum(probability * math.log2(probability) for probability in probabilities if probability > 0)  # final sum

    print(entropy)

已检查ent使用 Python 3.6.9 在 Ubuntu 18.04 上运行程序:

$ dd if=/dev/urandom of=random_data.bin bs=1K count=16
16+0 records in
16+0 records out
16384 bytes (16 kB, 16 KiB) copied, 0.0012111 s, 13.5 MB/s
$ ent random_data.bin
Entropy = 7.988752 bits per byte.
...
$ ./calc_entropy.py
7.988751920202076

也使用文本文件进行了测试。

$ ent calc_entropy.py
Entropy = 4.613356 bits per byte.
...
$ ./calc_entropy.py
4.613355601248316

关于python - 计算 pickle 文件的熵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59528143/

相关文章:

python - 找不到马克

Python 3 统一码解码错误 : 'ascii' codec can't decode byte 0xe2 in position 0: ordinal not in range(128)

random - 嵌入式系统上 "uniqueness"/entropy 的来源

python - 如何绘制一条线并设置嵌套列表中每条线的颜色?

python - 如何为 gcloud ml 打包子文件夹?

python - 在基于类的表单之间传递数据

python - CPython 和 IronPython cPickle 之间的兼容性

linux - 尽早阅读/dev/urandom

python - 需要更快的 python 代码来计算样本熵

python - selenium.common.exceptions.WebDriverException : Message: no such session while executing testcases through Python unittest module