30个极简Python代码,拿走即用

【胡学长 带你学 Global Mapper 】如何将影像地图转换为国家2000坐标系 多部门联合开展工作坐标数据不匹配怎么办?Hi,我是胡学长!今天教大家如何利用Global Mapper将谷歌影像数据转换为国家2000坐标系影像数据 。 阅读详情

学 Python 怎样才最快,当然是实战各种小项目,只有自己去想与写,才记得住规则。本文是 30 个极简任务,初学者可以尝试着自己实现;本文同样也是 30 段代码,Python 开发者也可以看看是不是有没想到的用法。

、1

重复元素判定

以下方法可以检查给定列表是不是存在重复元素,它会使用 set() 函数来移除所有重复元素。

def all_unique(lst):
return len(lst)== len(set(lst))
x = [1,1,2,2,3,2,3,4,5,6]
y = [1,2,3,4,5]
all_unique(x) # False
all_unique(y) # True

2

字符元素组成判定

检查两个字符串的组成元素是不是一样的。

from collections import Counter
def anagram(first, second):
return Counter(first) == Counter(second)
anagram("abcd3", "3acdb") # True

3

内存占用

import sys
variable = 30
print(sys.getsizeof(variable)) # 24

4

字节占用

下面的代码块可以检查字符串占用的字节数。

def byte_size(string):
return(len(string.encode('utf-8')))
byte_size('') # 4
byte_size('Hello World') # 11

5

打印 N 次字符串

该代码块不需要循环语句就能打印 N 次字符串。

n = 2
s ="Programming"
print(s * n)
# ProgrammingProgramming

6 大写第一个字母

以下代码块会使用 title() 方法,从而大写字符串中每一个单词的首字母。

s = "programming is awesome"
print(s.title())
# Programming Is Awesome

7

分块

给定具体的大小,定义一个函数以按照这个大小切割列表。

from math import ceil
def chunk(lst, size):
return list(
map(lambda x: lst[x * size:x * size + size],
list(range(0, ceil(len(lst) / size)))))
chunk([1,2,3,4,5],2)
# [[1,2],[3,4],5]

8

压缩

这个方法可以将布尔型的值去掉,例如(False,None,0,“”),它使用 filter() 函数。

def compact(lst):
return list(filter(bool, lst))
compact([0, 1, False, 2, '', 3, 'a', 's', 34])
# [ 1, 2, 3, 'a', 's', 34 ]

9

解包

如下代码段可以将打包好的成对列表解开成两组不同的元组。

array = [['a', 'b'], ['c', 'd'], ['e', 'f']]
transposed = zip(*array)
print(transposed)
# [('a', 'c', 'e'), ('b', 'd', 'f')]

10 链式对比

我们可以在一行代码中使用不同的运算符对比多个不同的元素。

a = 3
print( 2 < a < 8) # True
print(1 == a < 2) # False

11 逗号连接

下面的代码可以将列表连接成单个字符串,且每一个元素间的分隔方式设置为了逗号。

hobbies = ["basketball", "football", "swimming"]
print("My hobbies are: " + ", ".join(hobbies))
# My hobbies are: basketball, football, swimming

12 元音统计

以下方法将统计字符串中的元音 (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) 的个数,它是通过正则表达式做的。

import re
def count_vowels(str):
return len(len(re.findall(r'[aeiou]', str, re.IGNORECASE)))
count_vowels('foobar') # 3
count_vowels('gym') # 0

13 首字母小写

如下方法将令给定字符串的第一个字符统一为小写。

def decapitalize(string):
return str[:1].lower() + str[1:]
decapitalize('FooBar') # 'fooBar'
decapitalize('FooBar') # 'fooBar'

14 展开列表

该方法将通过递归的方式将列表的嵌套展开为单个列表。

def spread(arg):
ret = []
for i in arg:
if isinstance(i, list):
ret.extend(i)
else:
ret.append(i)
return ret
def deep_flatten(lst):
result = []
result.extend(
spread(list(map(lambda x: deep_flatten(x) if type(x) == list else x, lst))))
return result
deep_flatten([1, [2], [[3], 4], 5]) # [1,2,3,4,5]

15 列表的差

该方法将返回第一个列表的元素,其不在第二个列表内。如果同时要反馈第二个列表独有的元素,还需要加一句 set_b.difference(set_a)。

def difference(a, b):
set_a = set(a)
set_b = set(b)
comparison = set_a.difference(set_b)
return list(comparison)
difference([1,2,3], [1,2,4]) # [3]

16 通过函数取差

如下方法首先会应用一个给定的函数,然后再返回应用函数后结果有差别的列表元素。

def difference_by(a, b, fn):
b = set(map(fn, b))
return [item for item in a if fn(item) not in b]
from math import floor
difference_by([2.1, 1.2], [2.3, 3.4],floor) # [1.2]
difference_by([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], lambda v : v['x'])
# [ { x: 2 } ]

17 链式函数调用

你可以在一行代码内调用多个函数。

def add(a, b):
return a + b
def subtract(a, b):
return a - b
a, b = 4, 5
print((subtract if a > b else add)(a, b)) # 9

18 检查重复项

如下代码将检查两个列表是不是有重复项。

def has_duplicates(lst):
return len(lst) != len(set(lst))
x = [1,2,3,4,5,5]
y = [1,2,3,4,5]
has_duplicates(x) # True
has_duplicates(y) # False

19 合并两个字典

下面的方法将用于合并两个字典。

def merge_two_dicts(a, b):
c = a.copy() # make a copy of a 
c.update(b) # modify keys and values of a with the once from b
return c
a={'x':1,'y':2}
b={'y':3,'z':4}
print(merge_two_dicts(a,b))
#{'y':3,'x':1,'z':4}

在 Python 3.5 或更高版本中,我们也可以用以下方式合并字典:

def merge_dictionaries(a, b)
return {**a, **b}
a = { 'x': 1, 'y': 2}
b = { 'y': 3, 'z': 4}
print(merge_dictionaries(a, b))
# {'y': 3, 'x': 1, 'z': 4}

20 将两个列表转化为字典

如下方法将会把两个列表转化为单个字典。

def to_dictionary(keys, values):
return dict(zip(keys, values))
keys = ["a", "b", "c"]
values = [2, 3, 4]
print(to_dictionary(keys, values))
#{'a': 2, 'c': 4, 'b': 3}

21 使用枚举

我们常用 For 循环来遍历某个列表,同样我们也能枚举列表的索引与值。

list = ["a", "b", "c", "d"]
for index, element in enumerate(list): 
print("Value", element, "Index ", index, )
# ('Value', 'a', 'Index ', 0)
# ('Value', 'b', 'Index ', 1)
#('Value', 'c', 'Index ', 2)
# ('Value', 'd', 'Index ', 3)

22 执行时间

如下代码块可以用来计算执行特定代码所花费的时间。

import time
start_time = time.time()
a = 1
b = 2
c = a + b
print(c) #3
end_time = time.time()
total_time = end_time - start_time
print("Time: ", total_time)
# ('Time: ', 1.1205673217773438e-05) 

23 Try else

我们在使用 try/except 语句的时候也可以加一个 else 子句,如果没有触发错误的话,这个子句就会被运行。

try:
2*3
except TypeError:
print("An exception was raised")
else:
print("Thank God, no exceptions were raised.")
#Thank God, no exceptions were raised.

24 元素频率

下面的方法会根据元素频率取列表中最常见的元素。

def most_frequent(list):
return max(set(list), key = list.count)
list = [1,2,1,2,3,2,1,4,2]
most_frequent(list)

25 回文序列

以下方法会检查给定的字符串是不是回文序列,它首先会把所有字母转化为小写,并移除非英文字母符号。最后,它会对比字符串与反向字符串是否相等,相等则表示为回文序列。

def palindrome(string):
from re import sub
s = sub('[\W_]', '', string.lower())
return s == s[::-1]
palindrome('taco cat') # True

26 不使用 if-else 的计算子

这一段代码可以不使用条件语句就实现加减乘除、求幂操作,它通过字典这一数据结构实现:

import operator
action = {
"+": operator.add,
"-": operator.sub,
"/": operator.truediv,
"*": operator.mul,
"**": pow
}
print(action['-'](50, 25)) # 25

27 Shuffle

该算法会打乱列表元素的顺序,它主要会通过 Fisher-Yates 算法对新列表进行排序:

from copy import deepcopy
from random import randint
def shuffle(lst):
temp_lst = deepcopy(lst)
m = len(temp_lst)
while (m):
m -= 1
i = randint(0, m)
temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst[m]
return temp_lst
foo = [1,2,3]
shuffle(foo) # [2,3,1] , foo = [1,2,3]

28 展开列表

将列表内的所有元素,包括子列表,都展开成一个列表。

def spread(arg):
ret = []
for i in arg:if isinstance(i, list):
ret.extend(i)
else:
ret.append(i)
return ret
spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9]

29 交换值

不需要额外的操作就能交换两个变量的值。

def swap(a, b):
return b, a
a, b = -1, 14
swap(a, b) # (14, -1)
spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9]

30 字典默认值

通过 Key 取对应的 Value 值,可以通过以下方式设置默认值。如果 get() 方法没有设置默认值,那么如果遇到不存在的 Key,则会返回 None。

d = {'a': 1, 'b': 2}
print(d.get('c', 3)) # 3

End.

作者:Fatos Morina(机器之心编译)

参考链接:https://towardsdatascience.com/30-helpful-python-snippets-that-you-can-learn-in-30-seconds-or-less-69bb49204172

近期十大热门:
我总结的80页《菜鸟学Python精选干货.pdf》,都是干货

笑喷了,我用Python帮韦小宝选最佳老婆组合
用Python一键生成炫酷九宫格图片,火了朋友圈

菜鸟也疯狂!8分钟用Python做一个酷炫的家庭随手记

Github获8300星!用Python开发的一个命令行的网易云音乐

一道Python面试题,硬是没憋出来,最后憋出一身汗!
Python高手进阶|实战4大并发秘籍

让你纵横 GitHub 的五大神器

值得收藏!8大技巧,带你了解菜鸟和高手的区别!

卧槽!Pdf转Word用Python轻松搞定!

由菜鸟学Python原班人马打造的公众号【程序员GitHub】,专注于分享GitHub上有趣的资源包括,Python,Java,Go语言前端学习等优质的学习资源,爆料程序员圈的新鲜趣事,热门干货,职场感悟,感兴趣的小伙伴可以来捧场!

点的“在看”,否则就看不到我了555
基于Claude AI的Dex个人操作系统:从零部署到高效工作流实战 在当今信息过载的时代,个人知识管理(PKM)和任务自动化成为提升效率的关键技术。传统PKM工具如Notion、Obsidian虽然提供了强大的信息存储能力,但本质上是被动的数据库,需要用户手动维护结构和链接,容易形成信息孤岛。其核心原理在于通过预设的文件夹结构和智能路由,实现信息的自动归类与关联。这种自动化同步机制的技术价值在于彻底消除重复劳动和决策疲劳,让用户从繁琐的信息整理中解放出来,专注于高价值思考。在实际应用场景中,它尤其适合需要处理大量会议、任务和人际关系的知识工作者,如产品经理、项目经理和团队领 阅读详情

相关推荐

Virbox Protector:全方位守护 Android 应用安全

在数字化浪潮中,Android 应用面临着诸多安全挑战,如破解、篡改、盗版、数据窃取和钓鱼欺诈等。为了应对这些复杂的安全问题,Virbox Protector 应运而生,为 Android 应用提供高强度的专业化安全保护,支持对 APK 和 AAB 文件的加固保护,并兼容 Google Play,助力应用顺利出海。

VBP_2025的博客 998

30段极简Python代码:这些小技巧你都Get了么

学 Python 怎样才最快,当然是实战各种小项目,只有自己去想与写,才记得住规则。本文是 30 个极简任务,初学者可以尝试着自己实现;本文同样也是 30 段代码,Python 开发者也可以看看是不是有没想到的用法。 Python 是机器学习最广泛采用的编程语言,它最重要的优势在于编程的易用性。如果读者对基本的 Python 语法已经有一些了解,那么这篇文章可能会给你一些启发。作者简单概...

weixin_30824599的博客 1829

ACM论文LaTeX模板解析(三)| 文章顶部信息(Top matter))Part 1

文章顶部信息(Top matter))Part 1,文章类型、作者信息等

FreshManInC的博客 4857

10个经典的C语言面试基础算法及代码

本文是码农网原创整理,转载请看清文末的转载要求,谢谢合作! 算法是一个程序和软件的灵魂,作为一名优秀的程序员,只有对一些基础的算法有着全面的掌握,才会在设计程序和编写代码的过程中显得得心应手。本文是近百个C语言算法系列的第二篇,包括了经典的Fibonacci数列、简易计算器、回文检查、质数检查等算法。也许他们能在你的毕业设计或者面试中派上用场。 1、计算Fibonacci数列 F

一直在路上 1667

智能车竞赛循迹控制:基于状态机的直道、弯道、十字路口处理策略

在嵌入式系统与自动控制领域,PID控制算法是实现精确运动控制的基础。其原理是通过比例、积分、微分三个环节的线性组合,对系统误差进行实时校正,从而实现对目标值的快速、稳定跟踪。这项技术的核心价值在于为各类自动控制系统提供了稳定、可靠且易于实现的解决方案,广泛应用于机器人、无人机、工业自动化等场景。在智能车循迹这类特定应用中,赛道环境复杂多变,单一的PID控制器难以应对直道、弯道、十字路口等不同赛道元素的控制需求。此时,有限状态机(FSM)作为一种高效的**决策框架**,能够根据实时感知的赛道特征(如边线曲率、

weixin_34034261的博客 288

平面变压器PCB绕组设计实战:从原理到布局的工程考量

本文深入探讨了平面变压器PCB绕组设计的工程实践,从基础原理到布局优化,涵盖了电流密度、层间绝缘、绕组拓扑结构等关键参数。通过实战案例分享,解析了高频应用中的集肤效应、邻近效应等挑战,并提供了热管理和EMC优化的实用技巧,助力工程师在服务器电源、车载充电器等空间敏感场景实现高效设计。

weixin_42666036的博客 479

50个c/c++源代码网站

C/C++是最主要的编程语言。这里列出了50名优秀网站和网页清单,这些网站提供c/c++源代码。这份清单提供了源代码的链接以及它们的小说明。我已尽力包括最佳的C/C++源代码的网站。这不是一个完整的清单,您有建议可以联系我,我将欢迎您的建议,以进一步加强这方面的清单。 1、http://snippets.dzone.com/tag/c/ --数以千计的有用的C语言源代码片段 2、http://...

weixin_30276935的博客 624

光谱特征选择之模拟退火算法SA

光谱特征选择之模拟退火算法SA。

weixin_42621095的博客 903

Linux 命令集

Linux 命令集linux 命令-查看命令linux 查看-lslinux 查看-pwdcd命令集ls目录和文件目录操作Vi/vim创建/查看/编辑文件删除文件复制和移动文件浏览文件打包命令grep命令linux 安装jdk1.8JDK配置命令: vim /etc/profile 注意中间有个小空格Linux安装MariaDB数据库配置Linux数据库权限配置Linux防火墙策略导入数据库命令方式导入数据库 linux 命令-查看命令 linux 查看-ls 查看当前目录下的所有文件夹 [root@

weixin_45988184的博客 1239

Windows加域迁移避坑指南:Profwiz工具实战中的5个常见问题与解决方案

本文详细解析了使用Profwiz工具进行Windows加域迁移时的5个常见问题及解决方案,包括临时配置文件生成、密码策略冲突、SID冲突等。通过实战案例和优化技巧,帮助IT运维团队高效完成账户配置文件迁移,确保Active Directory环境下的数据完整性和权限无缝衔接。

q9r0s的博客 531

YOLO26改进策略【YOLO和Mamba】| 替换骨干 Mamba-YOLO26-L !!! 最新的发文热点

Vision Clue Merge模块在Mamba - YOLO模型中同样重要,主要负责在模型的下采样过程中处理特征图,为后续的特征融合和目标检测任务提供更有效的信息。

Limiiiing的博客 480

static静态

static 静态方法和类一起加载,可以直接调用 static的主要意义是在于创建独立于具体对象的域变量或者方法。以致于即使没有创建对象,也能使用属性和调用方法!static关键字还有一个比较关键的作用就是 用来形成静态代码块以优化程序性能。static块可以置于类中的任何地方,类中可以有多个static块。在类初次被加载的时候,会按照static块的顺序来执行每个static块,并且只会执行一次.为什么说static块可以用来优化程序性能,是因为它的特性:只会在类加载的时候执行一次。因此,很多时候会将一些

weixin_52793038的博客 812

液态神经网络(Liquid Neural Networks)从线虫大脑到下一代 AI

液态神经网络(Liquid Neural Networks,LNN)是一类具有动态内部结构的神经网络,其灵感来源于生物神经系统,尤其是大脑中神经元如何以复杂、非线性的方式响应外部刺激。与传统神经网络不同,液态神经网络的每个神经元在处理输入时,不再是静态线性或非线性变换,而是基于一个微分方程模型进行响应。这种建模方式使神经元的行为具有时间连续性和动态适应性。换句话说,它不仅“记住”过去的信息,还能根据当前环境实时调整自身的动态特性,这对于感知、决策、预测等任务都非常关键。

hello.reader 7466

30个Python常用极简代码,拿走就用

学 Python 怎样才最快,当然是实战各种小项目,只有自己去想与写,才记得住规则。本文是 30 个极简任务,初学者可以尝试着自己实现;本文同样也是 30 段代码,Python 开发者也可以看看是不是有没想到的用法。...

qq_27726087的博客 7107

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

30个极简Python代码,拿走即用!

以下方法将统计字符串中的元音 (‘a’, ‘e’, ‘i’, ‘o’, ‘u’) 的个数,它是通过正则表达式做的。这个方法可以将布尔型的值去掉,例如(False,None,0,“”),它使用 filter() 函数。该算法会打乱列表元素的顺序,它主要会通过 Fisher-Yates 算法对新列表进行排序:​​​​​​​。这一段代码可以不使用条件语句就实现加减乘除、求幂操作,它通过字典这一数据结构实现:​​​​​​​。在 Python 3.5 或更高版本中,我们也可以用以下方式合并字典:​​​​​​​。

WANGWUSAN66的博客 1938

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

30个极简Python代码,拿走就能用!

作者丨Fatos Morina来源丨Python 技术编辑丨极市平台学 Python 怎样才最快,当然是实战各种小项目,只有自己去想与写,才记得住规则。本文是 30 个 Python 小任务,初学者可以尝试着自己实现。同样也是 30 段代码,Python 开发者也可以看看是不是有没想到的用法。1 重复元素判定以下方法可以检查给定列表是不是存在重复元素,它会使用 set() 函数来移除所有重复元素。...

cainiao_python的博客 1万+

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

30 个极简 Python 代码,拿走即用

“ 阅读本文大概需要 3 分钟。 ”学 Python 怎样才最快,当然是实战各种小项目,只有自己去想与写,才记得住规则。本文是 30 个极简任务,初学者可以尝试着自己实现;本文同样也是 ...

静觅 637

30个python常用代码大全_30 个 Python 常用极简代码,拿走就用

原标题:30 个 Python 常用极简代码,拿走就用文章转自:Python程序员学 Python 怎样才最快,当然是实战各种小项目, 只有自己去想与写,才记得住规则。本文是 30 个极简任务,初学者可以尝试着自己实现;本文同样也是 30 段代码,Python 开发者也可以看看是不是有没想到的用法。 、1重复元素判定以下方法可以检查给定列表是不是存在重复元素,它会使用 set 函数来移除所有重复元...

weixin_32999557的博客 7万+
上一篇: 我给互联网大佬们换上了女装
下一篇: 嘿嘿!我用Python一键生成《乘风破浪的姐姐》们的星座运势PPT
菜鸟学Python
博客等级 码龄9年 8169粉丝 571原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址