Python网络请求、JSON转换、多线程、异步IO

Python发送Post请求及解析响应结果 阅读详情

在 Python 众多的 HTTP 客户端中,最有名的莫过于 requests 、 aiohttp 和 httpx 。

在不借助其他第三方库的情况下, requests 只能发送同步请求; aiohttp 只能发送异步请求; httpx 既能发送同步请求,又能发送异步请求。

那么怎么选择呢

  • 只发同步请求用 requests ,但可配合多线程变异步。
  • 只发异步请求用 aiohttp ,但可以配合await变同步。
  • httpx 可以发同步请求也可以异步,但是请求速度同步略差于 requests ,异步略差于 aiohttp

Asyncio 的强大。但是,任何一种方案都不是完美的,都存在一定的局限性,Asyncio 同样如此。

实际使用中,想用好 Asyncio,特别是发挥其强大的功能,很多情况下必须得有相应的 Python 库支持。

比如

requests 库并不兼容 Asyncio,而 aiohttp 库兼容。

requests

这里先说 requests

安装依赖

pip install requests

响应

响应的类型

#获取接口返回的字符串数据
r.text

#获取接口返回的json数据,即直接将json格式的数据转换为json对象
r.json()

#获取接口返回的二进制数据,假设二进制数据如果为图片可以继续转换成图片
r.content

#获取原始套接字,使用r.raw请在 requests 请求中加上参数 stream=True
r.raw

获取请求响应的其他信息

#获取状态码
r.status_code

#获取请求的url
r.url

#获取指定cookies信息
r.cookies['token']

#获取访问服务器返回给我们的响应头部信息
r.headers

#获取指定访问服务器返回给我们的响应头部信息
r.headers['Content-Type']

#获取发送到服务器的请求的头部的信息
r.request.headers

请求

GET请求

get请求:

res = requests.get(url,data=data,cookies=cookie,headers=header,verify=False,files=file)

data可传可不传,data是字典格式。

如果url是https的话,加上verify=False。如果url是http的话,可不加。

示例1

import requests

if __name__ == '__main__':
    r = requests.get("https://www.psvmc.cn")
    print(r.text)

示例2

import requests

if __name__ == '__main__':
    data = {'username': 'admin', 'passwd': '123456'}
    r = requests.get("https://www.psvmc.cn/login.json", params=data)
    print(r.status_code)
    print(r.json()["obj"])

POST请求

url_post = "https://www.psvmc.cn/login.json"

#不包含任何参数的请求
r = requests.post(url_post)

#不包含任何参数的请求,设置超时10s,timeout不设置则默认60s
r = requests.post(url_post,timeout=10)

#携带参数的请求,dict_param为参数字典,默认data=dict_param,使用data=则表示post的是form请求
#即 application/x-www-form-urlencoded 。
r = requests.post(url_post, data=dict_param)

#携带参数的请求,dict_param为参数字典,使用json=则表示post的是json请求
r = requests.post(url_post, json=dict_param)

#携带参数的请求,body传字符串,这里是JSON字符串。
r = requests.post(url_post, data=json.dumps(dict_param))

#携带参数的请求,dict_param为参数字典,设置超时10s,并携带headers属性
r = requests.post(
    url_post,
    data=dict_param,
    timeout=10,
    headers={
        'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X)'
    })

#post请求上传文件
url = 'http://apihost/upload/post'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)

其他类型请求

r = requests.put(url, data =dict_param)
r = requests.delete(url)
r = requests.head(url)
r = requests.options(url)

代理

跨域的时候可以考虑代理访问,不管是post请求还是get请求,只需要添加proxies即可。

客户端开发时不用考虑跨域问题,没有必要设置代理访问。

proxies = {
  "http": "http://10.10.1.10:3128",
  "https": "http://10.10.1.10:1080",
}
requests.get(url_get, proxies=proxies)

查看代理是否有效

和telnet作用一样

import telnetlib

if __name__ == '__main__':
    try:
        telnetlib.Telnet('110.242.68.4', port='80', timeout=3)
    except:
        print('ip无效!')
    else:
        print('ip有效!')

异步请求

aiohttp 的代码与 httpx 异步模式的代码重合度90%,只不过把 AsyncClient 换成了 ClientSession ,

另外,在使用 httpx 时,当你 await client.post 时就已经发送了请求。但是当使用 aiohttp 时,只有在 awiat resp.json() 时才会真正发送请求。

aiohttp

import aiohttp
import asyncio


async def main():
    async with aiohttp.ClientSession() as client:
        resp = await client.post('https://www.psvmc.cn/login.json',
                                 json={'ts': '2020-01-20 13:14:15'})
        result = await resp.json()
        print(result)


asyncio.run(main())

httpx

import httpx
import asyncio


async def main():
    async with httpx.AsyncClient() as client:
        resp = await client.post('https://www.psvmc.cn/login.json',
                                 json={'ts': '2020-01-20 13:14:15'})
        result = resp.json()
        print(result)


asyncio.run(main())

JSON

字符串转对象

import json

# 一些 JSON:
x =  '{ "name":"Bill", "age":63, "city":"Seatle"}'

# 解析 x:
y = json.loads(x)

# 结果是 Python 字典:
print(y["age"])

对象转字符串

import json

# Python 对象(字典):
x = {
  "name": "Bill",
  "age": 63,
  "city": "Seatle"
}

# 转换为 JSON:
y = json.dumps(x)

# 结果是 JSON 字符串:
print(y)

当 Python 转换为 JSON 时,Python 对象会被转换为 JSON(JavaScript)等效项:

PythonJSON
dictObject
listArray
tupleArray
strString
intNumber
floatNumber
Truetrue
Falsefalse
Nonenull

异步IO(协程)和请求

pip install aiohttp

简单示例

import asyncio


async def test():
    await asyncio.sleep(3)
    return "123"


async def main():
    result = await test()
    print(result)


if __name__ == '__main__':
    asyncio.run(main())

异步请求

import asyncio
import aiohttp
import time


async def download_one(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:
            print('Read {} from {}'.format(resp.content_length, url))


async def download_all(sites):
    tasks = [asyncio.ensure_future(download_one(site)) for site in sites]
    await asyncio.gather(*tasks)


def main():
    sites = [
        'https://www.psvmc.cn/index.html',
        'https://www.psvmc.cn/login.json',
        'https://www.psvmc.cn/userlist.json'
    ]
    start_time = time.perf_counter()

    loop = asyncio.get_event_loop()
    try:
        loop.run_until_complete(download_all(sites))
    finally:
        if loop.is_running():
            loop.close()
    end_time = time.perf_counter()
    print('Download {} sites in {} seconds'.format(
        len(sites), end_time - start_time))


if __name__ == '__main__':
    main()

多线程

from concurrent.futures import ThreadPoolExecutor
import threading


# 定义一个准备作为线程任务的函数
def action(num):
    print(threading.current_thread().name)
    return num+100


# 创建一个包含4条线程的线程池
with ThreadPoolExecutor(max_workers=3) as pool:

    future1 = pool.submit(action, 1000)

    def get_result(future):
        print(f"单个任务返回:{future.result()}")

    # 为future1添加线程完成的回调函数
    future1.add_done_callback(get_result)

    print('------------------------------')
    # 使用线程执行map计算
    results = pool.map(action, (50, 100, 150))
    for r in results:
        print(f"多个任务返回:{r}")

异步 IO/多进程/多线程对比

异步 IO(asyncio)、多进程(multiprocessing)、多线程(multithreading)

IO 密集型应用CPU等待IO时间远大于CPU 自身运行时间,太浪费;

常见的 IO 密集型业务包括:浏览器交互、磁盘请求、网络爬虫、数据库请求等

Python 世界对于 IO 密集型场景的并发提升有 3 种方法:多进程、多线程、异步 IO(asyncio);

理论上讲asyncio是性能最高的,原因如下:

  1. 进程、线程会有CPU上下文切换
  2. 进程、线程需要内核态和用户态的交互,性能开销大;而协程对内核透明的,只在用户态运行
  3. 进程、线程并不可以无限创建,最佳实践一般是 CPU*2;而协程并发能力强,并发上限理论上取决于操作系统IO多路复用(Linux下是 epoll)可注册的文件描述符的极限

那asyncio的实际表现是否如理论上那么强,到底强多少呢?我构建了如下测试场景:

访问500台 DB,并sleep 100ms模拟业务查询

  • 方法 1;顺序串行一台台执行
  • 方法 2:多进程
  • 方法 3:多线程
  • 方法 4:asyncio
  • 方法 5:asyncio+uvloop

最后的 asyncio+uvloop 和官方asyncio 最大不同是用 Cython+libuv 重新实现了asyncio 的事件循环(event loop)部分,

官方测试性能是 node.js的 2 倍,持平 golang。

以下测试代码需要 Pyhton3.7+:

顺序串行一台台执行

import records

user = "root"
pwd = "123456"
port = 3306
hosts = []  # 500台 db列表

def query(host):
    conn = records.Database(
    f'mysql+pymysql://{user}:{pwd}@{host}:{port}/mysql?charset=utf8mb4')
    rows = conn.query('select sleep(0.1);')
    print(rows[0])

def main():
    for h in hosts:
        query(h)

# main entrance
if __name__ == '__main__':
    main()

多进程

from concurrent import futures
import records

user = "root"
pwd = "123456"
port = 3306
hosts = []  # 500台 db列表

def query(host):
    conn = records.Database(
    f'mysql+pymysql://{user}:{pwd}@{host}:{port}/mysql?charset=utf8mb4')
    rows = conn.query('select sleep(0.1);')
    print(rows[0])

def main():
    with futures.ProcessPoolExecutor() as executor:
        for future in executor.map(query,hosts):
            pass

# main entrance
if __name__ == '__main__':
    main()

多线程

from concurrent import futures
import records

user = "root"
pwd = "123456"
port = 3306
hosts = []  # 500台 db列表

def query(host):
    conn = records.Database(
    f'mysql+pymysql://{user}:{pwd}@{host}:{port}/mysql?charset=utf8mb4')
    rows = conn.query('select sleep(0.1);')
    print(rows[0])

def main():
    with  .ThreadPoolExecutor() as executor:
        for future in executor.map(query,hosts):
            pass

# main entrance
if __name__ == '__main__':
    main()

asyncio

import asyncio
from databases import Database 

user = "root"
pwd = "123456"
port = 3306
hosts = []  # 500台 db列表

async def query(host):
    DATABASE_URL = f'mysql+pymysql://{user}:{pwd}@{host}:{port}/mysql?charset=utf8mb4'
    async with Database(DATABASE_URL) as database:
        query = 'select sleep(0.1);'
        rows = await database.fetch_all(query=query)
        print(rows[0])

async def main():
    tasks = [asyncio.create_task(query(host)) for host in hosts]
    await asyncio.gather(*tasks)

# main entrance
if __name__ == '__main__':
    asyncio.run(main())

asyncio+uvloop

import asyncio
import uvloop
from databases import Database

user = "root"
pwd = "123456"
port = 3306
hosts = []  # 500台 db列表

async def query(host):
    DATABASE_URL = f'mysql+pymysql://{user}:{pwd}@{host}:{port}/mysql?charset=utf8mb4'
    async with Database(DATABASE_URL) as database:
        query = 'select sleep(0.1);'
        rows = await database.fetch_all(query=query)
        print(rows[0])


async def main():
    tasks = [asyncio.create_task(query(host)) for host in hosts]
    await asyncio.gather(*tasks)

# main entrance
if __name__ == '__main__':
    uvloop.install()
    asyncio.run(main())

运行时间对比

方式运行时间
串行1m7.745s
多进程2.932s
多线程4.813s
asyncio1.068s
asyncio+uvloop0.750s

可以看出: 无论多进程、多进程还是asyncio都能大幅提升IO 密集型场景下的并发,但asyncio+uvloop性能最高,运行时间只有原始串行运行时间的 1/90,相差快 2 个数量级了!

该部分摘自: Python 异步 IO(asyncio)、多进程(multiprocessing)、多线程(multithreading)性能对比

Python requests模块GET与POST请求实战:从基础到高级应用 HTTP协议是Web通信的基石,定义了客户端与服务器之间数据交换的格式与规则。其核心原理基于请求-响应模型,通过GET、POST等方法实现不同操作。理解HTTP协议对于网络编程至关重要,它能帮助开发者构建高效、可靠的网络应用。在Python生态中,requests库凭借其简洁的API和强大的功能,成为处理HTTP请求的首选工具,广泛应用于网络爬虫、API调用等场景。本文聚焦于requests库中GET与POST请求的深度应用,通过实战案例解析参数传递、会话管理、错误处理等关键技术细节,并探讨连接池、请求重试 阅读详情

相关推荐

构建高并发AI数据管道:从异步IO到任务调度,实现千源并行处理

在AI工程实践中,高并发数据处理是连接海量数据源与智能模型的关键桥梁。其核心原理在于通过异步编程、消息队列和生产者-消费者模式,构建解耦、可扩展的数据摄取管道。这项技术的核心价值在于能极大提升数据吞吐效率,为实时分析、模型训练提供稳定、低延迟的数据供给。典型的应用场景包括多源资讯聚合、竞品监控和大规模数据预处理。本文聚焦于实现“千源并行阅读”能力,详细探讨了如何利用异步框架和任务调度器,解决异构数据源适配、资源限制和错误处理等工程挑战,为AI应用构建坚实的数据基础设施。

weixin_33483304的博客 311

python实现多线程发送网络请求——基础模板

python实现多线程基础模板 python实现多线程的方式有很多种,其中有一种比较好用的是使用threadpool线程池,它可以使用多线程的方式自动调动线程任务,具体模板如下: import socket import time import threadpool send_host = '192.168.211.20' send_port = 514 sleep_sec = 1 packag...

JosenChina的博客 1958

京东商品API数据解析实战:Python高效处理JSON技巧

JSON作为现代API交互的主流数据格式,其嵌套结构和动态特性给数据处理带来挑战。通过Python的jsonpath-ng等工具可以实现声明式查询,配合pandas等库能构建完整的数据处理流水线。在电商数据采集场景中,这种技术组合特别适用于京东商品API这类深度嵌套的JSON数据解析,可实现价格监控、商品分析等实际应用。针对API返回的300+字段复杂结构,采用安全访问封装和流式处理技术能有效提升开发效率,同时避免内存溢出等问题。

weixin_30252709的博客 407

python使用http.client发送post请求

【代码】python使用http.client发送post请求。

全幼稚园最可爱 1549

VC++ REST API开发实战:基于cpr库实现HTTP CRUD操作与JSON处理

HTTP协议作为现代网络通信的基石,其核心的GET、POST、PUT、DELETE方法构成了RESTful API的设计原则。理解这些方法的语义与幂等性是实现可靠客户端交互的关键。在C++工程实践中,选择合适的HTTP客户端库能极大提升开发效率与代码可维护性。cpr库作为libcurl的现代化C++封装,提供了直观的API与强大的功能,尤其适合在VC++环境中处理网络请求。通过封装统一的HttpClient类,开发者可以集中管理连接超时、错误处理与资源释放,有效避免常见的网络错误。结合nlohmann/js

weixin_30588675的博客 578

无感无刷电机控制进阶:反电动势过零检测的5种实现方案对比

本文深入探讨无感无刷电机控制中反电动势过零检测的5种实现方案,包括电阻分压虚拟中性点法、专用BEMF检测IC方案、基于ADC采样的数字锁相环、无传感器观测器技术及混合方案创新实践。通过对比分析各方案的优劣及适用场景,为电机控制工程师提供实用的技术选型指南,助力提升系统性能与成本效益。

weixin_28691741的博客 867

Python使用requests、urllib2、httplib2、http.client执行Get和Post请求

Python(Python2和Python3)中后台执行Get和Post有一些方法,本文主要介绍使用requests、urllib2、httplib2、http.client执行Get和Post请求方法及示例代码。

weixin_52026996的博客 2178

MTK Linux Charger驱动分析(二) - power_supply_core.c

的核心作用可以概括为:提供统一的电源管理框架;管理电源设备注册、属性访问、事件通知;封装sysfs 接口和 uevent 通知,屏蔽硬件细节;驱动开发者只需要实现,不关心底层通知和接口细节。简单来说,它是电源子系统的“大脑和中枢”,具体的电池/充电器只是“信息源”。

iTom1900 1496

Python在服务端/客户端实现GET POST请求

Python Flask实现GET POST请求的服务端和客户端 网上关于GET POST请求的文章很多,但是感觉挺乱的。 所以这里提供用Flask实现GET POST最简单的server端和client端代码。 服务端代码: # coding:utf-8 import json from flask import Flask, request app = Flask(__name__) BASE_URL = '/shitou/' # 接收get请求 @app.route(BASE_URL +

weixin_44096485的博客 4985

Windows10 搭建 FTP 服务器

问题: 有这么一个需求,博主需要对班级同学的信息进行收集,同学的信息是一个个的文件, 正常是每个同学将自己的信息打包压缩通过 QQ 或者邮箱方式发送给博主, 博主一个个接收这些压缩包,然后进行解压,再统一放到一个文件夹下, 但是博主觉得这样子实在是太麻烦了,如果某一个同学的信息来回变动,就需要接收很多次,更改很多次, 另外如果消息过多还会产生漏掉某个同学的信息的问题。 解决方法: 如果可以使...

assiduous_me的博客 3981

手把手教你学Simulink——四开关 Buck‑Boost(FSBB)变换器的无缝模式切换仿真

本文详细介绍了四开关Buck-Boost(FSBB)变换器的Simulink仿真方法,重点解决模式切换时的直通风险和输出电压波动问题。通过统一电压PI控制、迟滞比较模式仲裁(Buck/Boost/Pass-Through)和200ns死区设计,实现了Vin从26V到22V变化时Vout稳定在12V±0.15V。关键步骤包括:搭建功率级电路、Stateflow模式判断、PI控制器输出占空比映射(Buck模式D≈Vo/Vin,Boost模式D≈1-Vo/Vin),以及带死区的PWM信号分配。仿真验证了切换过程中

MHD0815的博客 129

【Python数据处理高手进阶】:掌握JSON/XML高效解析的5大核心技术

掌握Python处理JSON/XML数据的高效方式,提升数据解析性能。涵盖流式解析、库对比、异步处理等5大核心技术,适用于爬虫、API开发等场景,显著提高运行效率与代码可维护性,值得收藏。

CodeTrick的博客 732

心理学量表汇总 50多个 附下载

目录一、心理健康与精神病态量表二、行为问题量表三、人格评估量表四、智力测验一、心理健康与精神病态量表1.一般症状自评量表(SCL-90)症状自评量表 (The self-report symptom inventory ,Symptom checklist ,90,简称 SCL90) 有 90 个评定项目 , 每个项目分五级评分 , 包含了比较广泛的精神病症状学内容, 从感觉、 情 感、思维、意识、行为直至生活习惯、人际关系、饮食等均有涉及,能准确刻划被试的自觉 症状,能较好地反映被试的问题及其严重程度和变

南七小僧的学海无涯 1918

11.python3的标准库

Python 标准库的重要性及其在开发中的应用标准库与第三方库的区别Python3 标准库的主要分类sys:访问解释器相关变量与功能os:文件系统操作、进程管理subprocess:创建和管理子进程Python 标准库的生态优势未来可能的扩展方向。

wjj131419的博客 1650

⭐️【2024年新版教程】vmware tools安装步骤(Windows、Linux、MacOS版本)

VMware Tools是VMware提供的一套实用工具,它可以增强虚拟机与宿主机之间的交互性能,如改进显示性能、优化鼠标和键盘性能、提供时间同步功能等。无论是在Windows、Linux还是MacOS虚拟机上,安装VMware Tools都可以提高虚拟机的使用体验。以上就是在不同操作系统上安装VMware Tools的步骤,希望对您有所帮助。

Python老吕的博客 6万+

STM32G0/G4电机控制中三角函数与浮点运算优化实战

三角函数(sin/cos)和浮点运算是电机矢量控制(FOC)的核心基础,直接影响Clark/Park变换、SVPWM及观测器的实时性与精度。在资源受限的MCU上,标准math.h库因无硬件FPU支持而引发严重时序抖动,导致电流环延迟、转矩脉动增大甚至系统复位。通过硬件加速(如STM32G4的CORDIC协处理器)或定制化定点算法(如STM32G0的查表+线性插值),可将sin/cos计算从数十微秒压缩至1–3 μs量级,提升30倍以上效率。该方案广泛适用于BLDC/PMSM驱动、伺服控制及高动态响应嵌入式运

weixin_35751412的博客 112

C++ Boost.Asio实现多线程端口扫描器:从异步I/O到性能优化

网络编程的核心在于高效处理并发连接,而异步I/O模型是实现这一目标的关键技术。通过操作系统提供的I/O多路复用机制,程序可以用少量线程管理大量网络套接字,在连接就绪时通过回调函数处理,从而极大提升吞吐量。这种技术在构建高性能网络工具时具有重要价值,例如端口扫描器就需要快速探测大量目标端口的状态。本文以C++ Boost.Asio库为基础,深入剖析了如何利用异步I/O和多线程技术实现一个高效的端口扫描器,重点解决了超时控制、线程同步等工程实践问题,并探讨了线程池和连接池等性能优化方案,为网络诊断和系统运维提供

weixin_30706691的博客 404

ue 打包linux程序 在windows系统 2026

ue 打包linux程序 在windows系统 2026

jacke121的专栏 377

深度解析bilili:Python实现B站视频爬取的核心技术架构

bilili作为一个专注于B站视频与弹幕下载的开源项目,通过Python实现了从API交互到视频处理的完整技术栈。该项目不仅支持普通视频和番剧的高效下载,还提供了弹幕转换、多线程并发、画质选择等高级功能,为开发者提供了一个完整的多媒体内容获取解决方案。 ## 异步请求与API交互机制的实现 ### 原理分析:智能重试与异常处理策略 bilili的API层采用装饰器模式实现智能重试机制,通过`

gitblog_01076的博客 1006

精雕软件(JDpaint) 5.5 绿色版

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

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

Python语法在实际项目中的10个经典应用

比如用fillna()处理缺失值,用apply()进行数据转换,用groupby()进行分组统计。定义路由用@app.route装饰器,处理请求用request对象,返回JSON响应用jsonify函数。它内置了Python运行环境,可以直接在线编写和运行代码,还能一键部署Web服务,省去了配置环境的麻烦。除了内置的open(),还可以用contextlib创建自定义上下文管理器,处理数据库连接等资源。从简单的脚本到复杂的系统,Python都能优雅地应对。通过继承和多态,可以设计灵活的插件架构。

ObsidianRaven13的博客 562

深度学习工具包 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")

Python标准库实战指南:pathlib、datetime、json、urllib与并发五步精要

Python标准库是每个开发者绕不开的底层基础设施,其核心价值在于开箱即用、零依赖、高稳定性。理解其设计原理——如pathlib对路径的对象化抽象、zoneinfo对时区的标准化建模、json模块对序列化边界的严格定义——是写出健壮脚本的关键。这些模块不追求语法糖,而强调语义清晰与错误早暴露,技术价值体现在减少隐性bug(如跨平台路径拼接失败、时区转换偏差、JSON编码乱码)和提升工程可维护性。典型应用场景覆盖自动化运维脚本、日志分析工具、配置驱动服务及轻量API聚合器等。本文聚焦5个高频实战模块,以真实排

weixin_30621711的博客 393

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

Python从入门到精通(三):文件IO、网络编程与并发架构的底层重构

Python从入门到精通(三):文件IO、网络编程与并发架构的底层重构

搞定过:百亿级数据、万级QPS、零宕机、AI工业化。 226

【Python 教程】如何将 JSON 数据转换为 Excel 工作表

当然这个值是可以更改的,但是线程越多,CPU切换所需的时间也就越长,用来处理真正业务的需求也就越少。虽然在服务器端,请求的处理交给了一个独立线程进行,但是操作系统通知accept()的方式还是单个的。虽然客户端A和客户端B的请求是同时进行的,但客户端B发送的请求信息只能等到服务器接受完A的请求数据后,才能被接受。很显然,这样的处理方式在高并发的情况下,是不能采用的。当服务器收到客户端X的请求后,(读取到所有请求数据后)将这个请求送入一个独立线程进行处理,然后主线程继续接受客户端Y的请求。

MoWXdpdG0的博客 361
上一篇: 晋级python高手的必备技能(之一)-内存泄露分析优化
下一篇: 涨知识了——Python除了截屏其它不为人知的图片处理神操作(灰度、滤镜、裁剪和旋转、缩放、对比度增强、GIF处理)
老贡讲Python
博客等级 码龄5年 526粉丝 129原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址