Python pickle模块:实现Python对象的持久化存储

【Python】pickle2 在前一章中,我们深入剖析了 协议的演进及其底层的操作码机制,初步揭示了 如何将 Python 对象转化为字节流,以及反之如何从字节流重建对象。现在,我们将把理论转化为实践,聚焦于 模块提供给开发者直接使用的核心 API。这些 API 是进行对象序列化和反序列化的门面,掌握它们的使用细节、参数含义以及潜在的行为模式,是精通 的第一步,也是至关重要的一步。本章将详细讲解 模块中最常用的四个函数:、、 和 。我们将不仅仅停留在其基本用法上,更会深入探讨其可选参数,例如 、、 和 ,并通过大量原创、详尽的 阅读详情

Python 中有个序列化过程叫作 pickle,它能够实现任意对象与文本之间的相互转化,也可以实现任意对象与二进制之间的相互转化。也就是说,pickle 可以实现 Python 对象的存储及恢复。

值得一提的是,pickle 是 python 语言的一个标准模块,安装 python 的同时就已经安装了 pickle 库,因此它不需要再单独安装,使用 import 将其导入到程序中,就可以直接使用。

pickle 模块提供了以下 4 个函数供我们使用:

  1.   dumps():将 Python 中的对象序列化成二进制对象,并返回;
  2.   loads():读取给定的二进制对象数据,并将其转换为 Python 对象;
  3.   dump():将 Python 中的对象序列化成二进制对象,并写入文件;
  4.   load():读取指定的序列化数据文件,并返回对象。

以上这 4 个函数可以分成两类,其中 dumps 和 loads 实现基于内存的 Python 对象与二进制互转;dump 和 load 实现基于文件的 Python 对象与二进制互转。

pickle.dumps()函数

此函数用于将 Python 对象转为二进制对象,其语法格式如下:

dumps(obj, protocol=None, *, fix_imports=True) 

此格式中各个参数的含义为:

  •  obj:要转换的 Python 对象;
  •  protocol:pickle 的转码协议,取值为 0、1、2、3、4,其中 0、1、2 对应 Python 早期的版本,3 和 4 则对应 Pyt
读取cifar10数据集的代码 读取数据集的代码 from six.moves import cPickle as pickle import os import platform import numpy as np import pickle filename =r'D:\PythonProjects\cifar-10-batches-py\data_batch_1' # cifar10二进制文件路径 classes = ('plane', 'car', 'bird', 'cat', 'deer', ' 阅读详情

相关推荐

实现Python中的对象持久化

根据应用的需求和场景选择适合的持久化方式,并根据具体需求实现相应的代码逻辑,以实现对象的持久化功能。在Python中,对象持久化是将对象的状态保存到存储介质中,以便在以后的时间点恢复该对象的过程。如果对象的结构比较简单,并且不需要保留对象的方法,可以使用JSON序列化来实现对象持久化。最后,我们创建一个Person对象,将其保存到数据库中,并从数据库中加载对象并打印。函数从文件中加载对象,并打印加载的对象的属性。在上面的代码中,我们定义了一个Person类,创建了一个Person对象,并使用。

DevScript的博客 280

从零到一:Firefly-RK3399上的Ubuntu镜像构建与GPU加速实战

本文详细介绍了在Firefly-RK3399开发板上从零构建深度优化的Ubuntu系统镜像的全过程,包括交叉编译环境配置、内核定制、GPU加速环境部署(Mesa Panfrost驱动、OpenCL/Vulkan支持)以及深度学习推理优化(TFLite + LinuxNN)。通过实战案例展示了如何充分发挥Mali-T860 GPU的硬件潜力,提升边缘AI应用的性能和能效。

pz8901234的博客 1029

某手 v8.x 签名计算方法(二) sig和__NS_sig3

一、目标 今天的目标是 sig和__NS_sig3,咱们抓个包先 二、步骤 sig目测像是MD5 先jadx搜索 sig= ,没有找到结果。 再试试 sig ,晕倒 6k多个结果,突然灵光一闪,这些参数,必然是要加入到 Map中,那么我们搜索 "sig" 应该就是这个 CPU.getClock,Hook之 var signCls = Java.use('com.yxcorp.xxx.util.CPU'); signCls.getClock.implementation = function(a,b,c

fenfei331的博客 2435

TP4056锂电池充电电路设计原理与工程实践

锂离子电池充电管理是嵌入式电源系统的核心基础技术,其本质是通过恒流恒压(CC/CV)控制策略,匹配电池电化学特性以实现安全、高效、长寿命充放电。TP4056作为典型线性充电IC,以精简外围实现预充、恒流、恒压及自动截止全周期管理,但受限于线性拓扑的热耗散特性,必须协同散热设计、电阻精度选型与PCB布局进行系统级优化。该方案广泛应用于STM32智能小车、便携传感器节点等3.7V单节锂电供电场景,兼顾成本、可靠性与工程可实施性,是入门嵌入式硬件电源设计的关键实践范例。

weixin_36064575的博客 232

Android SSL证书固定实战:原理、方案与避坑指南

SSL/TLS协议是保障网络通信安全的基石,其核心原理是通过非对称加密和数字证书实现身份认证与数据加密。在移动应用开发中,为了防止中间人攻击,证书固定技术应运而生,它通过将服务器证书或公钥的哈希值预置在应用内,强制校验服务器身份,从而大幅提升通信链路的安全性。这一技术对于金融、电商等高安全要求场景尤为重要。本文聚焦Android平台,深入解析SPKI固定、Network Security Configuration与OkHttp CertificatePinner等主流方案,并针对证书更新、调试兼容等常见痛

weixin_33935636的博客 414

POWER SI仿真流程

一、打开软件Power SI二、加载PCB,可以直接使用brd文件,不用再进行格式转换三、check Stackup,与原来的PCB叠层对照一遍,检查数据加载后有没有出错。四、select Nets,加载brd文件后,可能所有的网络都处于使用状态,先在右侧net manager下面右键disable all nets,再使能需要仿真的电源网络(如果要仿真的网络没有归属到电源网络,在其上右键,选classfy as power \ground nets)

lx5213的博客 1336

python读取并可视化npy格式的深度图文件以及将其保存为jpg图片的方法

  npy文件是无法直接打开的,它里面包含的是一个矩阵格式的数据,可以用于存储图像。为了对其进行可视化,需要将其转换为图像。这里需要用到numpy包以及matplotlib包,没有的话就pip install一下吧。现进入包含有npy文件的目录(我的该目录下有一个名为0000.npy的文件),然后打开一个终端,执行python进入pythn命令行模式,依次输入如下代码即可: import numpy as np import matplotlib.pyplot as plt depthmap = np.lo

zeeq的博客 5万+

2022年12月机器人技术等级考试试卷(三级实操) 试题解析

2022年12月机器人技术等级考试试卷(三级实操) 试题解析

http://www.cierobot.com 1527

【云原生系列】第一讲:什么是云计算

云计算(cloud computing):分布式:分布式计算的一种,指的是通过网络“云”将巨大的数据计算处理程序分解成无数个小程序,合并&反馈:通过多部服务器组成的系统进行处理和分析这些小程序得到结果并返回给用户。云计算早期:分布式计算:简单的分布式计算,解决任务分发,并进行计算结果的合并。因而,云计算又称为网格计算。通过分布式计算,可以在很短的时间内(几秒钟)完成对数以万计的数据的处理,从而达到强大的网络服务。现阶段:计算:分布式计算、效用计算、负载均衡、并行计算、存储。

颜淡慕潇 1万+

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

上一篇: 一篇文章梳理清楚 Python 多线程与多进程
下一篇: #私藏项目实操分享#Python爬虫实战,requests+xpath模块,Python实现爬取豆瓣影评
Python_xiaowu
博客等级 码龄5年 3096粉丝 178原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址