cs231n spring 2017 Python/Numpy基础
本文使根据CS231n的讲义整理而成(http://cs231n.github.io/python-numpy-tutorial/),以下内容基于Python3。
1. 基本数据类型:可以用 print(type(x)) 查看类型
1)整数、浮点数:
幂:x**y等价于pow(x, y);
不支持 x++、x--,支持 x+=1;
/是浮点除法,//是整除,3//2 = 1;
%取余;
2)布尔:
与(and,&)、或(or,|)、非(not),不要使用&&、||之类的。
3)字符串:
单引号 'abc' ,双引号 "abc",都可以;
字符串长度 len(a);
可以用 + 把多个字符串串联起来;
可以格式化的赋值,例如 a = '%s %s %d' % (x, y, 3);
字符串有很多内置的小函数可以调用,例如 s.capitalize(),s.upper(),s.replace('a', 'A') 等等。
2. 容器
1)列表 List:
赋值:x = [1, 2, ‘a’],跟一维数组很像,都是用方括号,但大小可以扩展,而且元素可以是任意类型。
取出元素 x[0] = 1,x[-1] = 'a',序号也是用方括号,从0开始,-1是倒数第一个。
末尾添加:x.append('b'),这时候x = [1, 2, 'a', 'b'];
取末尾值:y = x.pop(),这时候y = ‘b’, x = [1, 2, ‘a’];
可以像matlab一样取子集,y = x[1:2],这时候y = [2, 'a'];
可以用for循环遍历,enumerate可以取出元素的序列:
- animals = ['cat', 'dog', 'monkey']
- for animal in animals:
- print(animal)
- # Prints "cat", "dog", "monkey", each on its own line.
- animals = ['cat', 'dog', 'monkey']
- for idx, animal in enumerate(animals):
- print('#%d: %s' % (idx + 1, animal))
- # Prints "#1: cat", "#2: dog", "#3: monkey", each on its own line
list comprehension的用法:
- nums = [0, 1, 2, 3, 4]
- squares = [x ** 2 for x in nums]
- print(squares) # Prints [0, 1, 4, 9, 16]
- nums = [0, 1, 2, 3, 4]
- even_squares = [x ** 2 for x in nums if x % 2 == 0]
- print(even_squares) # Prints "[0, 4, 16]"
2)字典,Dictionary:
赋值用大括号,一个key冒号一个value,d = {'cat': 'cute', 'dog': 'furry'};
直接赋值就能增加元素,d['fish'] = 'wet',这时候 d = {'cat': 'cute', 'dog': 'furry', 'fish': 'wet'};
取值 a = d['fish'],这时候a = 'wet';
取值的时候可以设定默认值,d.get('monkey', 'N/A'),如果没有'moneky'词条就会输出'N/A'
可以for循环遍历, item()可以把key和value都取出来:
- d = {'person': 2, 'cat': 4, 'spider': 8}
- for animal in d:
- legs = d[animal]
- print('A %s has %d legs' % (animal, legs))
- # Prints "A person has 2 legs", "A cat has 4 legs", "A spider has 8 legs"
- d = {'person': 2, 'cat': 4, 'spider': 8}
- for animal, legs in d.items():
- print('A %s has %d legs' % (animal, legs))
- # Prints "A person has 2 legs", "A cat has 4 legs", "A spider has 8 legs"
Dictionary comprehensions的用法:
- nums = [0, 1, 2, 3, 4]
- even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}
- print(even_num_to_square) # Prints "{0: 0, 2: 4, 4: 16}"
3)集合,Set:
赋值用大括号,animals = {'cat', 'dog'},也可以不同类型的元素 x = {'a', 3, 'b', 3.52};
增加元素用add,删除元素用remove,animals.add('fish'),animals.remove('cat'),如果增加的元素已经有了就不操作,但如果想删除的元素集合里没有就会报错。
集合大小,len(animals);
查看集合内是否有某个元素 print(x in animals),有就是True,没有就是False;
也可以用for循环以及set comprehensions:
- animals = {'cat', 'dog', 'fish'}
- for idx, animal in enumerate(animals):
- print('#%d: %s' % (idx + 1, animal))
- # Prints "#1: fish", "#2: dog", "#3: cat"
- from math import sqrt
- nums = {int(sqrt(x)) for x in range(30)}
- print(nums) # Prints "{0, 1, 2, 3, 4, 5}"
4)Tuple:和list很像,差别在于,tuple可以作为字典和集合的元素,而list不行。
赋值用小括号,d = (5, 6);
取元素,d[0]。
3. 函数:注意缩进对齐,可以设置默认参数:
- def hello(name, loud=False):
- if loud:
- print('HELLO, %s!' % name.upper())
- else:
- print('Hello, %s' % name)
- hello('Bob') # Prints "Hello, Bob"
- hello('Fred', loud=True) # Prints "HELLO, FRED!"
4. 类
- class Greeter(object):
- # Constructor
- def __init__(self, name):
- self.name = name # Create an instance variable
- # Instance method
- def greet(self, loud=False):
- if loud:
- print('HELLO, %s!' % self.name.upper())
- else:
- print('Hello, %s' % self.name)
- g = Greeter('Fred') # Construct an instance of the Greeter class
- g.greet() # Call an instance method; prints "Hello, Fred"
- g.greet(loud=True) # Call an instance method; prints "HELLO, FRED!"
5. Numpy的Array:
和list一样也是用中括号:
- import numpy as np
- a = np.array([1, 2, 3]) # Create a rank 1 array
- print(type(a)) # Prints "<class 'numpy.ndarray'>"
- print(a.shape) # Prints "(3,)"
- print(a[0], a[1], a[2]) # Prints "1 2 3"
- a[0] = 5 # Change an element of the array
- print(a) # Prints "[5, 2, 3]"
- b = np.array([[1,2,3],[4,5,6]]) # Create a rank 2 array
- print(b.shape) # Prints "(2, 3)"
- print(b[0, 0], b[0, 1], b[1, 0]) # Prints "1 2 4"
- a = np.zeros((2,2)) # Create an array of all zeros
- print(a) # Prints "[[ 0. 0.]
- # [ 0. 0.]]"
- b = np.ones((1,2)) # Create an array of all ones
- print(b) # Prints "[[ 1. 1.]]"
- c = np.full((2,2), 7) # Create a constant array
- print(c) # Prints "[[ 7. 7.]
- # [ 7. 7.]]"
- d = np.eye(2) # Create a 2x2 identity matrix
- print(d) # Prints "[[ 1. 0.]
- # [ 0. 1.]]"
- e = np.random.random((2,2)) # Create an array filled with random values
- print(e) # Might print "[[ 0.91940167 0.08143941]
- # [ 0.68744134 0.87236687]]"
也可以取子集,x = y[1, :],取出第一行的全部元素;
有一个技巧是对矩阵的每一行某个元素进行操作:
- # Create a new array from which we will select elements
- a = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
- # Create an array of indices
- b = np.array([0, 2, 0, 1])
- # Select one element from each row of a using the indices in b
- print(a[np.arange(4), b]) # Prints "[ 1 6 7 11]"
可以对array的序号进行筛选:
- a = np.array([[1,2], [3, 4], [5, 6]])
- bool_idx = (a > 2) # 对每个元素判断是否大于2.
- print(bool_idx) # Prints "[[False False]
- # [ True True]
- # [ True True]]"
- # 可以序号为真的取出来
- print(a[bool_idx]) # Prints "[3 4 5 6]"
- # We can do all of the above in a single concise statement:
- print(a[a > 2]) # Prints "[3 4 5 6]"
cs231n spring 2017 Python/Numpy基础的更多相关文章
- cs231n spring 2017 Python/Numpy基础 (1)
本文使根据CS231n的讲义整理而成(http://cs231n.github.io/python-numpy-tutorial/),以下内容基于Python3. 1. 基本数据类型:可以用 prin ...
- Python Numpy基础教程
Python Numpy基础教程 本文是一个关于Python numpy的基础学习教程,其中,Python版本为Python 3.x 什么是Numpy Numpy = Numerical + Pyth ...
- python numpy基础 数组和矢量计算
在python 中有时候我们用数组操作数据可以极大的提升数据的处理效率, 类似于R的向量化操作,是的数据的操作趋于简单化,在python 中是使用numpy模块可以进行数组和矢量计算. 下面来看下简单 ...
- Python——Numpy基础知识(一)
一.Numpy的引入 1.标准的Python 中用列表(list)保存一组值,可以当作数组使用.但由于列表的元素可以是任何对象,因此列表中保存的是对象的指针.对于数值运算来说,这种结构显然比较浪费内存 ...
- cs231n spring 2017 lecture15 Efficient Methods and Hardware for Deep Learning 听课笔记
1. 深度学习面临的问题: 1)模型越来越大,很难在移动端部署,也很难网络更新. 2)训练时间越来越长,限制了研究人员的产量. 3)耗能太多,硬件成本昂贵. 解决的方法:联合设计算法和硬件. 计算硬件 ...
- cs231n spring 2017 lecture13 Generative Models 听课笔记
1. 非监督学习 监督学习有数据有标签,目的是学习数据和标签之间的映射关系.而无监督学习只有数据,没有标签,目的是学习数据额隐藏结构. 2. 生成模型(Generative Models) 已知训练数 ...
- cs231n spring 2017 lecture11 Detection and Segmentation 听课笔记
1. Semantic Segmentation 把每个像素分类到某个语义. 为了减少运算量,会先降采样再升采样.降采样一般用池化层,升采样有各种"Unpooling"." ...
- cs231n spring 2017 lecture9 CNN Architectures 听课笔记
参考<deeplearning.ai 卷积神经网络 Week 2 听课笔记>. 1. AlexNet(Krizhevsky et al. 2012),8层网络. 学会计算每一层的输出的sh ...
- cs231n spring 2017 lecture7 Training Neural Networks II 听课笔记
1. 优化: 1.1 随机梯度下降法(Stochasitc Gradient Decent, SGD)的问题: 1)对于condition number(Hessian矩阵最大和最小的奇异值的比值)很 ...
随机推荐
- HTML 回到顶部 浮动
回到顶部 <div id="FloatDIV" style="position: absolute; top: 0px; z-index: 9999; backgr ...
- TensorFlow(一)
一.Hello World 1.只安装CPU版,TensorFlow1.14.0版本代码 # import tensorflow as tf import tensorflow.compat.v1 a ...
- Spring Cloud Zuul 网关服务的fallback
当我们的zuul进行路由分发时,如果后端服务没有启动,或者调用超时,这时候我们希望Zuul提供一种降级功能,而不是将异常暴露出来. Spring cloud zuul提供这种降级功能,操作步骤如下: ...
- [腾讯 TMQ] 接口测试用例设计
接口测试 [腾讯 TMQ] 接口测试用例设计 腾讯移动品质中心 · 2018年01月17日 · 最后由 于静 回复于 20 天前 · 21794 次阅读 本帖已被设为精华帖! 目录 作者:刘燕 团队: ...
- sklearn 模型评估
原文链接 http://d0evi1.com/sklearn/model_evaluation/ 预测值:pred 真实值:y_test #### 直接用平均值 ``` mean(pred == y_ ...
- TiKV 在京东云对象存储元数据管理的实践
京东云对象存储是在 2016 年作为公有云对外公开的,主要特点是可靠.安全.海量.低成本,应用于包括一些常用的业务场景,比如京东内部的京东商城视频/图片云存储,面向京东云公有云外部的开发者的服务,和面 ...
- 实现Action
实现Action 对于开发者来说,Action才是应用的核心,开发者需要提供大量的Action类,并在Struts.xml文件中配置Action.Action类中包含了用户请求的处理逻辑,Action ...
- 吴裕雄--天生自然ShellX学习笔记:Shell简介
Shell 是一个用 C 语言编写的程序,它是用户使用 Linux 的桥梁.Shell 既是一种命令语言,又是一种程序设计语言. Shell 是指一种应用程序,这个应用程序提供了一个界面,用户通过这个 ...
- 01 语言基础+高级:1-2 面向对象和封装_day06【类与对象、封装、构造方法】
day06[类与对象.封装.构造方法] 面向对象类与对象三大特征——封装构造方法 能够理解面向对象的思想能够明确类与对象关系能够掌握类的定义格式能够掌握创建对象格式,并访问类中的成员能够完成手机类的练 ...
- cJSON api的使用教程
背景说明:由于和后台通信,为了统一数据格式,选择使用json格式,客户端开发语言使用的是c,故需要借助第三方库来实现json格式的转化,cJSON是一个很好的第三方库, 下载链接1:https://g ...