100个python的基本语法知识【上】

Python--ndarray 常用属性详解 1. 描述维度的属性--shape 1.1 改变原始数组的维度 1.2 视图变维 1.3 复制变维 2. 数组的索引操作--index 2.1 一维数组的索引切片 2.2 多维数组的切片 2.2.1 二维数组的切片 2.2.2 三维数组的切片 3. ndarray 掩码 3.1 布尔掩码 3.2 索引掩码 4. ndarray 的属性... 阅读详情

0. 变量和赋值:

x = 5  
name = “John”

1. 数据类型:

整数(int)  
浮点数(float)  
字符串(str)  
布尔值(bool)

2. 注释:

# 这是单行注释
"""
这是多行注释
"""

3. 算术运算:

a + b  # 加法
a - b  # 减法
a * b  # 乘法
a / b  # 除法
a % b  # 取余
a ** b # 幂运算

4. 比较运算:

a == b  # 等于
a != b  # 不等于
a > b   # 大于
a < b   # 小于
a >= b  # 大于等于
a <= b  # 小于等于

5. 逻辑运算:

a and b
a or b
not a

6. 条件语句:

if condition:
# do something
elif another_condition:
# do something else
else:
# do something different

7. 循环:

for i in range(5):
print(i)
while condition:
# do something

8. 列表:

my_list = [1, 2, 3]
my_list.append(4)
my_list[0]  # 访问元素

9. 元组:

my_tuple = (1, 2, 3)

10. 字典:

my_dict = {"name": "John", "age": 30}
my_dict["name"]  # 访问键值

11. 集合:

my_set = {1, 2, 3}
my_set.add(4)

12. 字符串操作:

s = "hello"
s.upper()
s.lower()
s.split(" ")
s.replace("h", "j")

13. 字符串格式化:

name = "John"
age = 30
f"Hello, {name}. You are {age}."

14. 列表解析:

squares = [x**2 for x in range(10)]

15. 函数定义:

def my_function(param1, param2):
return param1 + param2

16. 默认参数:

def my_function(param1, param2=5):
return param1 + param2

17. 关键字参数:

def my_function(param1, param2):
return param1 + param2
my_function(param2=10, param1=5)

18. 可变参数:

def my_function(*args):
for arg in args:
print(arg)
my_function(1, 2, 3)

19. 关键字可变参数:

def my_function(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
my_function(name="John", age=30)

20. lambda表达式:

f = lambda x: x**2
f(5)

21. map函数:

list(map(lambda x: x**2, range(10)))

22. filter函数:

list(filter(lambda x: x % 2 == 0, range(10)))

23. reduce函数:

from functools import reduce
reduce(lambda x, y: x + y, range(10))

24. 异常处理:

try:
# do something
except Exception as e:
print(e)
finally:
# cleanup

25. 文件读取:

with open("file.txt", "r") as file:
content = file.read()

26. 文件写入:

with open("file.txt", "w") as file:
file.write("Hello, World!")

27. 类定义:

class MyClass:
def __init__(self, param1):
self.param1 = param1
def my_method(self):
return self.param1

28. 类继承:

class MyBaseClass:
def __init__(self, param1):
self.param1 = param1
class MyDerivedClass(MyBaseClass):
def __init__(self, param1, param2):
super().__init__(param1)
self.param2 = param2

29. 魔法方法:

class MyClass:
def __init__(self, param1):
self.param1 = param1
def __str__(self):
return f"MyClass with param1={self.param1}"

30. 属性和装饰器:

class MyClass:
def __init__(self, value):
self._value = value
@property
def value(self):
return self._value
@value.setter
def value(self, new_value):
self._value = new_value

31. 生成器:

def my_generator():
yield 1
yield 2
yield 3
for value in my_generator():
print(value)

32. 列表解析和生成器表达式:

[x**2 for x in range(10)]
(x**2 for x in range(10))

33. 集合解析:

{x**2 for x in range(10)}

34. 字典解析:

{x: x**2 for x in range(10)}

35. 上下文管理器:

with open("file.txt", "r") as file:
content = file.read()

36. 装饰器:

def my_decorator(func):
def wrapper(*args, **kwargs):
print("Before function call")
result = func(*args, **kwargs)
print("After function call")
return result
return wrapper
@my_decorator
def my_function():
print("Function call")
my_function()

37. 类型注解:

def my_function(param1: int, param2: str) -> str:
return param2 * param1

38. 枚举:

from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3

39. 迭代器:

class MyIterator:
def __init__(self, start, end):
self.current = start
self.end = end
def __iter__(self):
return self`
def __next__(self):
if self.current >= self.end:
raise StopIteration
else:
self.current += 1
return self.current - 1

40. JSON解析:

import json
json_str = '{"name": "John", "age": 30}'
data = json.loads(json_str)

41. 日期和时间:

from datetime import datetime``now = datetime.now()

42. 随机数生成:

import random
random_number = random.randint(1, 10)

43. 数学运算:

import math
math.sqrt(16)

44. 模块和包:

# my_module.py
def my_function():
return "Hello"
# main.py
import my_module
my_module.my_function()

45. 命名空间:

global_var = 5
def my_function():
local_var = 10
global global_var
global_var = 20

46. 继承和多态:

class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof"
class Cat(Animal):
def speak(self):
return "Meow"

47. 操作系统交互:

import os
os.getcwd()
os.listdir(".")

48. 命令行参数:

import sys
for arg in sys.argv:
print(arg)

49. 正则表达式:

import re
pattern = r"\d+"
re.findall(pattern, "There are 2 apples and 5 bananas.")

以上就是今天的全部内容分享,篇幅有限,下半部分关注下次的内容,觉得有用的话欢迎点赞收藏哦!

关于Python技术储备

学好 Python 不论是就业还是做副业赚钱都不错,但要学会 Python 还是要有一个学习规划。最后给大家分享一份全套的 Python 学习资料,给那些想学习 Python 的小伙伴们一点帮助!

包括:Python激活码+安装包、Python web开发,Python爬虫,Python数据分析,人工智能、自动化办公等学习教程。带你从零基础系统性的学好Python!

点击领取 100%免费!

👉Python所有方向的学习路线👈

Python所有方向路线就是把Python常用的技术点做整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。(全套教程文末领取)

在这里插入图片描述

👉Python学习视频600合集👈

观看零基础学习视频,看视频学习是最快捷也是最有效果的方式,跟着视频中老师的思路,从基础到深入,还是很容易入门的。

在这里插入图片描述

温馨提示:篇幅有限,已打包文件夹,获取方式在:文末
👉Python70个实战练手案例&源码👈

光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。

在这里插入图片描述

👉Python大厂面试资料👈

我们学习Python必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有阿里大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。

在这里插入图片描述

在这里插入图片描述

👉Python副业兼职路线&方法👈

学好 Python 不论是就业还是做副业赚钱都不错,但要学会兼职接单还是要有一个学习规划。

在这里插入图片描述

👉 这份完整版的Python全套学习资料已经上传,朋友们如果需要可以扫描下方优快云官方认证二维码或者点击链接免费领取【保证100%免费】

![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/711c5966aa7348dc9340894eea54e99f.png#pic_center在这里插入图片描述

Python数据分析系列(四 ):python数据结构 — Numpy中的ndarray(数组)的使用 本文主要介绍 Numpy中的ndarray(数组)的使用,其中包括用于数组创建,常用的数组算法(如排序集合运算),数组描述统计,数据聚合或分组运算,数据集的合并/连接运算的数据对齐和关系型数据运算等等。 阅读详情

相关推荐

Python基础知识训练题100道

看完head first python(第二版),找了天元浪子老师的一套语感训练题加强记忆,这里每道题结合自己的答案做下汇总。 原题在这里:https://xufive.blog.youkuaiyun.com/article/details/102993538 1. 将元组 (1,2,3) 和集合 {4,5,6} 合并成一个列表。 >>> list((1,2,3))+list({4,5,6}) [1, 2, 3, 4, 5, 6] 2. 在列表 [1,2,3,4,5,6] 首尾分别添加整型元

打工人 打工魂 2299

Python的numpy库ndarray简介

numpy库可以用来处理矩阵相关的数学运算,相比于Python自带的列表,其功能更强大,且运行速度更快。下面介绍一些常用的numpy库的用法。一、ndarray产生方法ndarray是numpy模块的基本数据模块,它是由一组数字组成一维或者多维的阵列。Numpy可以有多种方法产生ndarray,下面介绍其中的常用的方法。本文介绍了numpy的ndarray的属性和基本的产生方法,关于ndarray,numpy库还提供了很多其他处理方法,后续再进行介绍。

qq_21337539的博客 7960

python基础题库100题及答案,python基础题目及答案

已知 x = [[1,3,3], [2,3,1]],那么表达式 sorted(x, key=lambda item:(item[1], -item[2])) 的值为____________________________________。已知 x = [[1,3,3], [2,3,1]],那么表达式 sorted(x, key=lambda item:(item[1],item[2])) 的值为____________________________________。

Rtee1的博客 5789

Python装逼代码

鼓起白色的帆;愿你是船,剪开蓝色的波澜。生活正在你的前方微笑,勇敢的走上前去,将彩色的人生拥抱。

we123aaa4567的博客 9065

python基础题库100题及答案,python基础题库及答案

已知 x = [[1,3,3], [2,3,1]],那么表达式 sorted(x, key=lambda item:(item[1], -item[2])) 的值为____________________________________。已知 x = [[1,3,3], [2,3,1]],那么表达式 sorted(x, key=lambda item:(item[1],item[2])) 的值为____________________________________。

P5688346的博客 1975

【python】python基础测试100题

python基础面试测试100题Q1.什么是Python?Q2.Python的主要功能是什么?Q3.Python中支持的数据类型有哪些?Q4.列表和元组有什么区别?Q5.什么是Python模块?Q6.python解释器种类以及特点?Q7.什么是Python切片?Q8.Python中的%S是什么?Q9.Python编程中的函数是什么?Q10.Python中有多少基本类型的函数可用?Q11.我们如何用Python编写函数?Q12.深拷贝和浅拷贝有什么区别?Q13.Python中的函数调用或可调用对象是什么?Q1

浪里小飞侠的博客 2155

10分钟逆袭,掌握Python 100个易懂的基本语法知识 | 上篇

列表是有序的可变集合,可以存储任意类型的元素.使用切片操作可以获取字符串的子串.字典是键值对的集合,键是唯一的.函数可以获取字符串的长度.

python茶水实验室 1038

在iPad上使用Python进行编程

如果你拥有一台iPad,并且想在上面编写和运行Python代码,你会发现iPad提供了一些适用的工具和应用程序来满足你的需求。安装一个Python解释器应用程序,编写和运行Python代码,使用第三方库和模块,以及存储和共享代码,这些步骤将帮助你在iPad上进行Python编程。要在iPad上运行Python代码,首先需要安装一个Python解释器。这些应用程序提供了一个交互式的开发环境,允许你编写、编辑和运行Python代码。一旦你安装了Python解释器应用程序,你可以开始编写Python代码了。

2301_79366435的博客 4628

100个python的基本语法知识【下】

这些知识点涵盖了Python编程的基本语法和常用功能。

roc_ever的博客 7689

PCIe 6.0实战指南:从链路训练到信号完整性的避坑手册

本文是一份针对PCIe 6.0硬件工程师的实战避坑指南。文章深入解析了从NRZ到PAM4调制带来的信号完整性挑战,详细拆解了链路训练(LTSSM)的复杂过程与调试方法,并提供了从信道仿真到实验室实测(如使用Keysight示波器进行眼图与误码率分析)的完整信号完整性闭环验证策略,帮助工程师解决高速率下的链路不稳定与降速问题。

weixin_29306875的博客 343

InsightFace(RetinaFace + ArcFace)人脸识别实战:从模型部署到Web服务构建

本文详细介绍了如何利用InsightFace框架,结合其集成的RetinaFace人脸检测与ArcFace人脸识别预训练模型,从零开始构建一个高性能的Web人脸识别服务。内容涵盖环境搭建、模型部署、核心代码解析(包括五点仿射对齐关键步骤)、FAISS向量检索集成以及基于FastAPI的Web服务开发,并提供了实战优化与常见问题排查指南,帮助开发者快速实现工业级应用。

weixin_29054245的博客 228

100个Python基本语法知识(一)

使用class关键字定义类。类定义中包含属性(变量)和方法(函数)。使用类名后跟括号(可选地包含参数)来实例化对象。

Chujun123528的博客 921

从数据手册到代码:一步步解读SC7A20寄存器配置与加速度值换算原理

本文详细解析了SC7A20三轴加速度传感器的寄存器配置与加速度值换算原理。从数据手册出发,逐步拆解关键寄存器设置,并推导原始ADC值到物理加速度的完整换算过程,帮助开发者深入理解传感器底层工作原理,提升嵌入式开发效率。

weixin_29179311的博客 369

100个python的基本语法知识总结【上】

Python大礼包:《2024年最新Python全套学习资料包》免费领取x = 5 name = “John”整数(int) 浮点数(float) 字符串(str) 布尔值(bool) 3. 算术运算: 4. 比较运算: 5. 逻辑运算: 6. 条件语句: 7. 循环: 8. 列表: 9. 元组: 10. 字典: 11. 集合: 12. 字符串操作: 13. 字符串格式化: 14. 列表解析: 15. 函数定义: 16. 默认参数: 17. 关键字参数: 18. 可变参数:

m0_62283350的博客 669

揭秘CAS:深入理解与应用解析

在并发编程中,Compare-And-Swap(CAS)机制作为一种无锁算法,凭借其高效性和避免线程阻塞的优势,受到广泛关注。CAS不仅在底层实现上有着重要地位,还在实际开发中发挥着关键作用。本文将从CAS的工作原理、在Java中的实现及其增强机制来回顾和加深理解一下CAS。

曾经“等你生日那天”都遥远得像未来,如今却可欢愉的挥手说“下个十年见” 85万+

【MATLAB】STM32电机调速闭环控制工程

本文提出了一种基于MATLAB仿真与STM32实现的直流电机闭环PID调速控制方案。通过MATLAB建立电机数学模型并进行参数整定,仿真验证了增量式PID算法在启停、稳态和抗扰动方面的优越性能。基于STM32F103搭建了硬件系统,实现了编码器测速、定时中断控制、PWM输出等功能。实测表明,该系统转速超调<2%、稳态误差±2r/min,具备快速响应和强抗扰能力。相比开环控制,闭环调速显著提升了动态性能和稳态精度。方案提供了完整的仿真代码和嵌入式工程源码,可直接应用于智能小车、工业传动等场景,具有较高的

unber的博客 50

100个python的基本语法知识(二)

当然,我们可以继续深入探讨Python的一些高级特性和常见用法,这些通常是在掌握了基础语法之后进一步学习的内容。

Chujun123528的博客 1141

EMC辐射整改常用的4种整改方法

例如,产品设计研发工程师们根据需求,设计出效果良好的滤波电路,置入产品I/O(输入/输出)接口的前级,可使因传导而进入系统的干扰噪声消除在电路系统的入口处;通过选择元器件和合理安排的电路系统,使干扰的影响减少。有些频率点是通过电路板上走线分布参数所决定的,通过前述方法不大有用,此类整改通过在走线中增加小的电感、电容、磁珠来改变电路参数结构,使其移到限值要求较高的频率点上。电线电缆的分类整理在电子设备中,线间耦合是一种重要的途径,也是造成干扰的重要原因,因为频率的因素,可大体分为高频耦合与低频耦合。

学海无涯的专栏 3124

从入门到精通:python 100个关键技术关键词

Python 是一门强大而易学的编程语言,广泛应用于Web开发、数据分析、人工智能、自动化脚本等多个领域。通过掌握本指南中的100个关键技术关键词,你将逐步了解Python的核心概念、基本语法、函数与模块、面向对象编程、异常处理、文件操作、正则表达式、网络编程、数据处理、并发与多线程以及数据库操作等方面的知识。每个关键词都配有详细的注释,帮助你轻松理解和应用。让我们一起开始这段精彩的Python学习之旅吧!

老码的专栏 1486

上线之前多一道闸:业务审核系统的接入定义、双轨状态机与可靠生效闭环

运营后台“保存即生效”,让价格、库存、人群等配置每次修改都相当于一次无评审的上线。本文以至尊会员降价活动为例,系统拆解业务审核系统:用带业务语义的操作编码、规则化审核人与候选人快照、完整的生效回调契约做好接入定义;把业务改造为提交待生效,以不可变快照、字段级差异和唯一约束加幂等号防误配防重复;用审批轨与执行轨双轨状态机、链路式重新提交和以事件为准的审核链路理清状态;最后以发件箱、幂等键、超时先查后试、乐观锁与对账闭合生效环节,并结合两个可运行的Java程序,给出五种生效策略的事故率实测对比。

曾经“等你生日那天”都遥远得像未来,如今却可欢愉的挥手说“下个十年见” 6万+

threejs中使用Reflector实现出倒影效果,并实现背景透明的效果(Reflector镜面背景透明, 倒影弱化)

在项目中遇到要实现倒影效果,threejs给我们提供了Reflector,可以轻松完成镜面效果,实现倒影。但背景不透明;并且反射出的倒影太亮了;网上没搜到解决方案, 自己修改了下源码实现了想要的效果,做个记录...

weixin_40856652的博客 5723

Python 100道经典练习题

Python 100道经典练习题 去发现同类优质开源项目:https://gitcode.com/ 欢迎来到Python 100道经典练习题资源仓库!本仓库为您提供了一份包含100道Python编程练习题的集合,旨在帮助您巩固Python基础知识,提升编程技能。 以下是资源文件简介: 标题:Python 100道经典练习题 描述:Python 100道经典练习题 这些练习题覆盖了Python的...

gitblog_06764的博客 400

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

3分钟学会Python 50个易懂的基本知识!

使用def关键词定义函数name }!!自定义异常用于创建特定的错误类型class CustomError(Exception): pass try: raise CustomError("这是自定义异常") except CustomError as e: print(e)

zhang120529的博客 1027

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

深度学习工具包 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过中秋节来自程序员的浪漫《嫦娥奔月》_python画一个嫦娥!
下一篇: 100个python的基本语法知识【下】
Python_trys
博客等级 码龄2年 4379粉丝 377原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值