为啥别人运行程序那么快,而你的却是龟速?

【数学1】快速幂、龟速乘、快速乘 快速幂和(龟速乘??) 阅读详情

Python程序运行太慢的一个可能的原因是没有尽可能的调用内置方法,下面通过5个例子来演示如何用内置方法提升PythGon程序的性能。

1. 数组求平方和

输入一个列表,要求计算出该列表中数字的的平方和。最终性能提升了1.4倍。

首先创建一个长度为10000的列表。

arr = list(range(10000))

1.1 最常规的写法

while循环遍历列表求平方和。平均运行时间2.97毫秒。

def sum_sqr_0(arr):
    res = 0
    n = len(arr)
    i = 0
    while i < n:
        res += arr[i] ** 2
        i += 1
    return res
%timeit sum_sqr_0(arr)
2.97 ms ± 36.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

很多人学习python,不知道从何学起。
很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手。
很多已经做案例的人,却不知道如何去学习更加高深的知识。
那么针对这三类人,我给大家提供一个好的学习平台,免费领取视频教程,电子书籍,以及课程的源代码!
QQ群:609616831


1.2 for range代替while循环

避免i += 1的变量类型检查带来的额外开销。平均运行时间2.9毫秒。

def sum_sqr_1(arr):
    res = 0
    for i in range(len(arr)):
        res += arr[i] ** 2
    return res
%timeit sum_sqr_1(arr)
2.9 ms ± 137 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

1.3 for x in arr代替for range

避免arr[i]的变量类型检查带来的额外开销。平均运行时间2.59毫秒。

def sum_sqr_2(arr):
    res = 0
    for x in arr:
        res += x ** 2
    return res
%timeit sum_sqr_2(arr)
2.59 ms ± 89 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

1.4 sum函数套用map函数

平均运行时间2.36毫秒

def sum_sqr_3(arr):
    return sum(map(lambda x: x**2, arr))
%timeit sum_sqr_3(arr)
2.36 ms ± 15.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

1.5 sum函数套用生成器表达式

生成器表达式如果作为某个函数的参数,则可以省略掉()。平均运行时间2.35毫秒。

def sum_sqr_4(arr):
    return sum(x ** 2 for x in arr)
%timeit sum_sqr_4(arr)
2.35 ms ± 107 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

1. 6 sum函数套用列表推导式

平均运行时间2.06毫秒。

def sum_sqr_5(arr):
    return sum([x ** 2 for x in arr])
%timeit sum_sqr_5(arr)
2.06 ms ± 27.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

2. 字符串拼接

输入一个列表,要求将列表中的字符串的前3个字符都拼接为一个字符串。最终性能提升了2.1倍。

首先创建一个列表,生成10000个随机长度和内容的字符串。

from random import randint

def random_letter():
    return chr(ord('a') + randint(0, 25))

def random_letters(n):
    return "".join([random_letter() for _ in range(n)])

strings = [random_letters(randint(1, 10)) for _ in range(10000)]

2.1 最常规的写法

while循环遍历列表,对字符串进行拼接。平均运行时间1.86毫秒。

def concat_strings_0(strings):
    res = ""
    n = len(strings)
    i = 0
    while i < n:
        res += strings[i][:3]
        i += 1
    return res
%timeit concat_strings_0(strings)
1.86 ms ± 74.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

2.2 for range代替while循环

避免i += 1的变量类型检查带来的额外开销。平均运行时间1.55毫秒。

def concat_strings_1(strings):
    res = ""
    for i in range(len(strings)):
        res += strings[i][:3]
    return res
%timeit concat_strings_1(strings)
1.55 ms ± 32.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

2.3 for x in strings代替for range

避免strings[i]的变量类型检查带来的额外开销。平均运行时间1.32毫秒。

def concat_strings_2(strings):
    res = ""
    for x in strings:
        res += x[:3]
    return res
%timeit concat_strings_2(strings)
1.32 ms ± 19.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

2.4 .join方法套用生成器表达式

平均运行时间1.06毫秒。

def concat_strings_3(strings):
    return "".join(x[:3] for x in strings)
%timeit concat_strings_3(strings)
1.06 ms ± 15.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

2.5 .join方法套用列表解析式

平均运行时间0.85毫秒。

def concat_strings_4(strings):
    return "".join([x[:3] for x in strings])
%timeit concat_strings_4(strings)
858 µs ± 14.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

3. 筛选奇数

输入一个列表,要求筛选出该列表中的所有奇数。最终性能提升了3.6倍。

首先创建一个长度为10000的列表。

arr = list(range(10000))

3.1 最常规的写法

创建一个空列表res,while循环遍历列表,将奇数append到res中。平均运行时间1.03毫秒。

def filter_odd_0(arr):
    res = []
    i = 0
    n = len(arr)
    while i < n:
        if arr[i] % 2:
            res.append(arr[i])
        i += 1
    return res
%timeit filter_odd_0(arr)
1.03 ms ± 34.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

3.2 for range代替while循环

避免i += 1的变量类型检查带来的额外开销。平均运行时间0.965毫秒。

def filter_odd_1(arr):
    res = []
    for i in range(len(arr)):
        if arr[i] % 2:
            res.append(arr[i])
        i += 1
    return res
%timeit filter_odd_1(arr)
965 µs ± 4.02 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

3.3 for x in arr代替for range

避免arr[i]的变量类型检查带来的额外开销。平均运行时间0.430毫秒。

def filter_odd_2(arr):
    res = []
    for x in arr:
        if x % 2:
            res.append(x)
    return res
%timeit filter_odd_2(arr)
430 µs ± 9.25 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

3.4 list套用filter函数

平均运行时间0.763毫秒。注意filter函数很慢,在Python 3.6里非常鸡肋。

def filter_odd_3(arr):
    return list(filter(lambda x: x % 2, arr))
%timeit filter_odd_3(arr)
763 µs ± 15.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

3.5 list套用生成器表达式

平均运行时间0.398毫秒。

def filter_odd_4(arr):
    return list((x for x in arr if x % 2))
%timeit filter_odd_4(arr)
398 µs ± 16.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

3.6 带条件的列表推导式

平均运行时间0.290毫秒。

def filter_odd_5(arr):
    return [x for x in arr if x % 2]
%timeit filter_odd_5(arr)
290 µs ± 5.54 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

4. 两个数组相加

输入两个长度相同的列表,要求计算出两个列表对应位置的数字之和,返回一个与输入长度相同的列表。最终性能提升了2.7倍。

首先生成两个长度为10000的列表。

arr1 = list(range(10000))
arr2 = list(range(10000))

4.1 最常规的写法

创建一个空列表res,while循环遍历列表,将两个列表对应的元素之和append到res中。平均运行时间1.23毫秒。

def arr_sum_0(arr1, arr2):
    i = 0
    n = len(arr1)
    res = []
    while i < n:
        res.append(arr1[i] + arr2[i])
        i += 1
    return res
%timeit arr_sum_0(arr1, arr2)
1.23 ms ± 3.77 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

4.2 for range代替while循环

避免i += 1的变量类型检查带来的额外开销。平均运行时间0.997毫秒。

def arr_sum_1(arr1, arr2):
    res = []
    for i in range(len(arr1)):
        res.append(arr1[i] + arr2[i])
    return res
%timeit arr_sum_1(arr1, arr2)
997 µs ± 7.42 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

4.3 for i, x in enumerate代替for range

部分避免arr[i]的变量类型检查带来的额外开销。平均运行时间0.799毫秒。

def arr_sum_2(arr1, arr2):
    res = arr1.copy()
    for i, x in enumerate(arr2):
        res[i] += x
    return res
%timeit arr_sum_2(arr1, arr2)
799 µs ± 16.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

4.4 for x, y in zip代替for range

避免arr[i]的变量类型检查带来的额外开销。平均运行时间0.769毫秒。

def arr_sum_3(arr1, arr2):
    res = []
    for x, y in zip(arr1, arr2):
        res.append(x + y)
    return res
%timeit arr_sum_3(arr1, arr2)
769 µs ± 12.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

4.5 列表推导式套用zip

平均运行时间0.462毫秒。

def arr_sum_4(arr1, arr2):
    return [x + y for x, y in zip(arr1, arr2)]
%timeit arr_sum_4(arr1, arr2)
462 µs ± 3.43 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

5. 两个列表相同元素的数量

输入两个列表,要求统计两个列表相同元素的数量。其中每个列表内的元素都是不重复的。最终性能提升了5000倍。

首先创建两个列表,并将元素的顺序打乱。

from random import shuffle
arr1 = list(range(2000))
shuffle(arr1)
arr2 = list(range(1000, 3000))
shuffle(arr2)

5.1 最常规的写法

while循环嵌套,判断元素arr1[i]是否等于arr2[j],平均运行时间338毫秒。

def n_common_0(arr1, arr2):
    res = 0
    i = 0
    m = len(arr1)
    n = len(arr2)
    while i < m:
        j = 0
        while j < n:
            if arr1[i] == arr2[j]:
                res += 1
            j += 1
        i += 1
    return res
%timeit n_common_0(arr1, arr2)
338 ms ± 7.81 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

5.2 for range代替while循环

避免i += 1的变量类型检查带来的额外开销。平均运行时间233毫秒。

def n_common_1(arr1, arr2):
    res = 0
    for i in range(len(arr1)):
        for j in range(len(arr2)):
            if arr1[i] == arr2[j]:
                res += 1
    return res
%timeit n_common_1(arr1, arr2)
233 ms ± 10.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

5.3 for x in arr代替for range

避免arr[i]的变量类型检查带来的额外开销。平均运行时间84.8毫秒。

def n_common_2(arr1, arr2):
    res = 0
    for x in arr1:
        for y in arr2:
            if x == y:
                res += 1
    return res
%timeit n_common_2(arr1, arr2)
84.8 ms ± 1.38 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

5.4 使用if x in arr2代替内层循环

平均运行时间24.9毫秒。

def n_common_3(arr1, arr2):
    res = 0
    for x in arr1:
        if x in arr2:
            res += 1
    return res
%timeit n_common_3(arr1, arr2)
24.9 ms ± 1.39 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

5.4 使用更快的算法

将数组用.sort方法排序,再进行单层循环遍历。把时间复杂度从O(n2)降低到O(nlogn),平均运行时间0.239毫秒。

def n_common_4(arr1, arr2):
    arr1.sort()
    arr2.sort()
    res = i = j = 0
    m, n = len(arr1), len(arr2)
    while i < m and j < n:
        if arr1[i] == arr2[j]:
            res += 1
            i += 1
            j += 1
        elif arr1[i] > arr2[j]:
            j += 1
        else:
            i += 1
    return res
%timeit n_common_4(arr1, arr2)
329 µs ± 12.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

5.5 使用更好的数据结构

将数组转为集合,求交集的长度。平均运行时间0.067毫秒。

def n_common_5(arr1, arr2):
    return len(set(arr1) & set(arr2))
%timeit n_common_5(arr1, arr2)
67.2 µs ± 755 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

在这里还是要推荐下我自己建的Python学习群:609616831,群里都是学Python的,如果你想学或者正在学习Python ,欢迎你加入,大家都是软件开发党,不定期分享干货(只有Python软件开发相关的),包括我自己整理的一份2020最新的Python进阶资料和零基础教学,欢迎进阶中和对Python感兴趣的小伙伴加入!

Python处理数据常见问题解决方案(2)Dataframe使用 append()添加大量数据时效率变低,处理时间过长,无法接受。 问题描述: 在用python给dataframe添加数据的过程中,我们经常使用append()方法往dataframe中一行一行的添加数据。但是当数据过多时,append()方法效率变得地下。近期笔者需要处理350,000行的数据,需要对其中的每一行做处理,组装成新的一行,再使用append()把新组装的一行添加至新的dataframe。 在MacBook上用Pycharm运行了8个小时,只append()了约110,000行,这个速度是无法接受的。所以需要找到一种更快的组装dataframe的方法。 解决 阅读详情

相关推荐

大数据下python的效率提升

1.不要用Append append 操作动态添加元素,很慢。可以先用 array 初始化一块内存,再赋值。 2.少用pandas 利用pandas转化为numpy array 进行操作,提高速度。

rosefun96的博客 1748

程序运行慢?你怕是写的假 Python

Python程序运行太慢的一个可能的原因是没有尽可能的调用内置方法,下面通过5个例子来演示如何用内置方法提升Python程序的性能。1. 数组求平方和输入一个列表,要求计算出该列表中数字...

Python中文社区 565

python性能提升之列表的拷贝效率(append,extend,copy,insert)

python性能提升之列表的拷贝效率 append、extend、copy、insert四种方式进行比较

LDC,公众号【轻松学编程】 1053

Python列表元素的5种添加方式以及效率问题

当列表增加和删除元素时,列表会自动进行内存管理,大大减少了程序员的负担。但这 个特点涉及列表元素的大量移动,效率较低。除非必要,我们一般只在列表的尾部添加元素 或删除元素,这会大大提高列表的操作效率。 一、append()方法 原地修改列表对象{不会创建新的对象},在列表尾部追加新的元素,速度最快,推荐使用 a = [10,20] a.append(30) print(a) #结果:[10,...

围城客的专栏 3789

UDS服务应该支持哪些否定响应码

UDS服务应该支持哪些否定响应码所有服务都需支持的否定响应码具体的服务需要支持的否定响应码否定响应码定义及其取值 USD诊断服务的否定响应中包含有导致否定响应原因的编码,称为否定响应码(NRC, Negative Response Code)。否定响应码的取值范围为0x00 - 0xFF,被分为三组: 0x00:服务器内部实现否定响应码判断逻辑时使用,表示要给出肯定响应。 0x01 – 0x7F:诊断通信相关的否定响应码。 0x80 – 0xFF:服务器收到诊断服务请求时,由于某些条件不满足要求而给出的否定

闲聊汽车软件开发 4万+

Canoe Panel基础功能介绍

CANoe Panel 是 Vector CANoe 软件中用于设计图形化操作界面的功能模块。用户可以在面板上添加合适的控件,实时的改变信号或者变量的值

m0_56208280的博客 1951

龟速乘

转https://blog.csdn.net/Cyan_rose/article/details/83065026 long long quick_mul(long long x,long long y,long long mod) { long long ans=0; while(y!=0){ if(y&1)ans+=x,ans%=mod; ...

weixin_30487317的博客 187

Titans:谷歌新型神经记忆架构,突破 Transformer 长序列处理的瓶颈

Titans 是谷歌推出的新型神经网络架构,通过神经长期记忆模块突破 Transformer 在处理长序列数据时的瓶颈,支持并行计算,显著提升训练效率。

士多啤梨先生の博客 994

【谈谈知识点】快速幂&龟速乘&快速乘

祝您观看愉快(笑

Cyan_rose 1万+

Jetson Thor平台JP7.0版本96712 GMSL相机驱动调试记录

摘要:本文档记录了在Thor Custom Board (JP7.0GA)上配置GMSL摄像头时遇到的视频流问题及调试过程。问题表现为视频设备(/dev/video11)能正常创建,但获取视频时出现"Internal data stream error",而相同配置在AGX Orin JP6.0上运行正常。通过梳理硬件拓扑、v4l2-ctl测试、提升时钟频率及分析内核日志,发现VI引擎未接收到帧数据包。调试步骤包括检查设备树冲突、调整I2C总线配置、修正通道名称,最终通过屏蔽传感器启动时

jzwjzw19900922的博客 1112

三态门Multisim电路仿真——硬件工程师笔记

三态门原理及应用摘要 三态门是具有高电平(1)、低电平(0)和高阻态(Z)三种输出的逻辑电路,通过使能端(EN)控制状态切换。高阻态时输出端等效断路,避免信号冲突。其核心应用包括: 总线系统:多设备共享总线时,仅使能选中设备的三态门,其余保持高阻态,防止干扰。 数据选择器:利用三态门切换多路输入信号,简化电路设计。 实现方式分两种: TTL三态门(三极管构成):低电平使能有效,仿真验证输出逻辑与高阻态。 MOS三态门(MOS管构成):高电平使能有效,仿真显示使能信号控制输出状态。 文中还附硬件工程师笔试面试

XU157303764的博客 2013

取模意义的快速幂黑科技:龟速乘

取模意义的快速幂黑科技:龟速乘 一般的快速幂: ll ksm(ll a,ll n,ll m){ ll ans=1; while(n){ if(n&1) ans=ans*a%m; a=a*a%m; n>>=1; } return ans; } 这样会存在一个问题,当求ab(modm),a^b\pmod{m},ab(modm),且a>109a>10^9a>109时,会存在爆long longlong\ longlong long的

Harris-H的博客 793

从 SAP ABAP 到 S/4HANA,SAML 2.0 单点登录到底是怎么跑起来的

在很多 SAP 项目里,SSO 不是一个锦上添花的功能,而是系统能不能顺利上线的基本门槛。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 1051

基本算法之龟速乘

利用二进制拆分思想, 因为直接计算乘法时间复杂度是。, 但是二进制拆分时间复杂度是。

Ayanami_Rei的博客 322

022、Conv-BN-SiLU 基础卷积块:构造函数参数计算,前向传播的 PyTorch 逐行实现

本文详细解析了Conv-BN-SiLU卷积块的实现细节与注意事项。作者从调试经历出发,指出bias参数冗余会导致数值不稳定,强调卷积层应设置bias=False。文章对比了SiLU与ReLU的特性差异,逐行分析了构造函数参数计算(包括自动填充、分组卷积等)和前向传播过程,特别讲解了BN层与SiLU激活的数值特性。最后分享了三个实践中的常见问题:BN的momentum设置、SiLU输出范围的影响,以及分组卷积的通道对齐要求,并提供了卷积与BN融合的推理优化技巧。全文聚焦实际工程实现中的关键细节,具有较强实操指

ai技术增长的博客 220

手把手教你学Simulink--基于车联网与智能交通系统的场景实例:基于车联网(V2X)的实时路况信息共享与处理

《基于Simulink的车联网(V2X)实时路况共享系统仿真》摘要:本文详细介绍使用Simulink构建V2X智能交通系统的完整方法。系统包含交通路网建模、V2X通信实现(支持DSRC/C-V2X标准)、多源路况信息融合、动态路径规划等核心模块。通过对比实验,验证V2X可使平均车速提升52%,行程时间缩短34%,显著提升交通效率。文章还探讨了AI预测调度、车辆编队等高级应用,为智慧交通系统开发提供实用参考。所需工具包括Simulink、SimEvents及无线通信工具箱等。

MHD0815的博客 739

快速幂+龟速乘

快速幂+龟速乘 今天在牛客遇到一道题华华教月月做数学 我看了一下题,发现是让求a^b%p,我一看就知道应该是快速幂,就非常高兴的开始写起来,但是写完的时候,发现连给的第二个样例都过不去,才发现,原来爆long long 了。 我看了一下题解,又搜了一下网上的资料,发现快速幂的弊端就是容易爆longlong,所以还有一种可以解决爆longlong的方法,那就是龟速乘,所以就去学了一下,然后AC了。 借鉴的大佬博客 快速幂模板 ll quick_pow(ll a,ll b, ll p) { ll res=1;

qq_45719639的博客 352

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

快速幂&龟速乘&快速乘

快速幂模板 #include<iostream> using namespace std; #define ll long long #define Mod 1e+7; ll fastPow(ll a,ll n){ ll base = a; ll sum =1; while(n){ if(n&1) sum*=base; base*=base; n>>=1;} return sum; } int main (){ int a,n; cin&g

weixin_45819197的博客 455

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

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

算法提高——基础算法(龟速乘)

文章目录一、例题二、思路分析三、算法介绍四、完整代码总结 一、例题 求 a 乘 b 对 p 取模的值。 输入格式 第一行输入整数a,第二行输入整数b,第三行输入整数p。 输出格式 输出一个整数,表示a*b mod p的值。 数据范围 1≤a,b,p≤1018 输入样例: 3 4 5 输出样例: 2 题目来源Acwing 二、思路分析 题目要让我们两个10e18的数相乘,必然会爆longlong,对于这种问题,我们的解法有两个,一个是高精度,另一个就是龟速乘。 三、算法介绍 先说一个很简单的思路,我们让结果

leoyongyuan的博客 1942

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...

快速幂,龟速乘和快速乘

目录 快速幂 引入 原理 代码 龟速乘 引入 原理 代码 快速乘 引入 原理 代码 快速幂 引入 假设a^b表示a的b次方。 那么求a^b,很容易想到这样的代码: int ans=1; for(int i=1;i<=b;i++) { ans*=a; } 然后仔细一看,这个的复杂度即为O(n)。 那么有没有一种可能,能降低复杂度呢?答案是有,即快速幂,复杂度为O(logn)。 所以快速幂的好处就是提升速度,降低时间。 原理 快速幂原理:基于二进制和位运算

qq_62102968的博客 952

快速幂&&龟速乘&&快速乘

背景   今天有一道题死活过不去,然后看大佬的博客,发现需要用到龟速乘。   然鹅我并不知道什么是龟速乘,于是就去查了QAQ   然后还被安利了快速乘。   做题的时候经常需要求解形如 ab mod c 的式子。   当b的值比较小的时候,我们可以使用循环乘【基本挂掉 或者快速幂。 快速幂   我知道大家都会,所以放个代码滚了      算法时间复杂度 O(log n)...

weixin_30549175的博客 179

快速乘法(龟速乘法)

#include<stdio.h> #include<stdlib.h> #include<algorithm> #include<string.h> #include<map> #include<string> using namespace std; #define ll long long ll a,b,c; ll q...

weixin_44554979的博客 1470

AcWing 90. 64位整数乘法 龟速乘

注意数据范围,这是longlong相乘都会爆掉的,所以要用到龟速乘。所以我们可以通过遍历b的所有二进制位寻找答案。该式意味着,b某一位二进制值为1则加。是不是很像快速幂的思想。

m0_74056929的博客 1012

【算法设计-分治】快速幂与龟速乘、矩阵乘与矩阵快速幂

【算法设计-分治思想】快速幂与龟速乘

Mount256的博客 882

一只蒟蒻的龟速乘学习笔记

一只蒟蒻的龟速乘学习笔记 背景 关于快速幂: 它死了。 咳咳。 以下是快速幂模板: inline int q_p(int a, int k, int p) { int ans = 1; while (k) { if (k & 1)ans = ans * a % p; k >>= 1; a = a * a % p; } return ans; } 可以看出,快速幂有一个缺点:当模数 p 大于 int 范围(最大值为 231-1)时,快速幂会爆 long long

Dumblog 250
上一篇: 十七种方法轻松解决PyTorch训练速度慢!
下一篇: 用Python给人物P上墨镜烟斗特效
python阿喵
博客等级 码龄6年 169粉丝 127原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值