相机有WIFI和无WIFI的c1和c2考试区别和利弊利弊是什么

Python中的Numpy入门教程
字体:[ ] 类型:转载 时间:
这篇文章主要介绍了Python中的Numpy入门教程,着重讲解了矩阵中的数组操作,需要的朋友可以参考下
1、Numpy是什么
很简单,Numpy是Python的一个科学计算的库,提供了矩阵运算的功能,其一般与Scipy、matplotlib一起使用。其实,list已经提供了类似于矩阵的表示形式,不过numpy为我们提供了更多的函数。如果接触过matlab、scilab,那么numpy很好入手。 在以下的代码示例中,总是先导入了numpy: 代码如下:&&& import numpy as np&&& print np.version.version1.6.2
2、多维数组
多维数组的类型是:numpy.ndarray。
使用numpy.array方法
以list或tuple变量为参数产生一维数组: 代码如下:&&& print np.array([1,2,3,4])[1 2 3 4]&&& print np.array((1.2,2,3,4))[ 1.2& 2.&& 3.&& 4. ]&&& print type(np.array((1.2,2,3,4)))&type 'numpy.ndarray'&以list或tuple变量为元素产生二维数组: 代码如下:&&& print np.array([[1,2],[3,4]])[[1 2]&[3 4]]生成数组的时候,可以指定数据类型,例如numpy.int32, numpy.int16, and numpy.float64等: 代码如下:&&& print np.array((1.2,2,3,4), dtype=np.int32)[1 2 3 4]使用numpy.arange方法 代码如下:&&& print np.arange(15)[ 0& 1& 2& 3& 4& 5& 6& 7& 8& 9 10 11 12 13 14]&&& print type(np.arange(15))&type 'numpy.ndarray'&&&& print np.arange(15).reshape(3,5)[[ 0& 1& 2& 3& 4]&[ 5& 6& 7& 8& 9]&[10 11 12 13 14]]&&& print type(np.arange(15).reshape(3,5))&type 'numpy.ndarray'&使用numpy.linspace方法
例如,在从1到3中产生9个数: 代码如下:&&& print np.linspace(1,3,9)[ 1.&&& 1.25& 1.5&& 1.75& 2.&&& 2.25& 2.5&& 2.75& 3.& ]使用numpy.zeros,numpy.ones,numpy.eye等方法可以构造特定的矩阵
例如: 代码如下:&&& print np.zeros((3,4))[[ 0.& 0.& 0.& 0.]&[ 0.& 0.& 0.& 0.]&[ 0.& 0.& 0.& 0.]]&&& print np.ones((3,4))[[ 1.& 1.& 1.& 1.]&[ 1.& 1.& 1.& 1.]&[ 1.& 1.& 1.& 1.]]&&& print np.eye(3)[[ 1.& 0.& 0.]&[ 0.& 1.& 0.]&[ 0.& 0.& 1.]]创建一个三维数组: 代码如下:&&& print np.zeros((2,2,2))[[[ 0.& 0.]& [ 0.& 0.]]
&[[ 0.& 0.]& [ 0.& 0.]]]获取数组的属性: 代码如下:&&& a = np.zeros((2,2,2))&&& print a.ndim&& #数组的维数3&&& print a.shape& #数组每一维的大小(2, 2, 2)&&& print a.size&& #数组的元素数8&&& print a.dtype& #元素类型float64&&& print a.itemsize& #每个元素所占的字节数8
数组索引,切片,赋值
示例: 代码如下:&&& a = np.array( [[2,3,4],[5,6,7]] )&&& print a[[2 3 4]&[5 6 7]]&&& print a[1,2]7&&& print a[1,:][5 6 7]&&& print a[1,1:2][6]&&& a[1,:] = [8,9,10]&&& print a[[ 2& 3& 4]&[ 8& 9 10]]使用for操作元素 代码如下:&&& for x in np.linspace(1,3,3):...&&&& print x...1.02.03.0
基本的数组运算
先构造数组a、b: 代码如下:&&& a = np.ones((2,2))&&& b = np.eye(2)&&& print a[[ 1.& 1.]&[ 1.& 1.]]&&& print b[[ 1.& 0.]&[ 0.& 1.]]数组的加减乘除: 代码如下:&&& print a & 2[[False False]&[False False]]&&& print a+b[[ 2.& 1.]&[ 1.& 2.]]&&& print a-b[[ 0.& 1.]&[ 1.& 0.]]&&& print b*2[[ 2.& 0.]&[ 0.& 2.]]&&& print (a*2)*(b*2)[[ 4.& 0.]&[ 0.& 4.]]&&& print b/(a*2)[[ 0.5& 0. ]&[ 0.&& 0.5]]&&& print (a*2)**4[[ 16.& 16.]&[ 16.& 16.]]
&使用数组对象自带的方法: 代码如下:&&& a.sum()4.0&&& a.sum(axis=0)&& #计算每一列(二维数组中类似于矩阵的列)的和array([ 2.,& 2.])&&& a.min()1.0&&& a.max()1.0
使用numpy下的方法: 代码如下:&&& np.sin(a)array([[ 0.,& 0.],&&&&&& [ 0.,& 0.]])&&& np.max(a)1.0&&& np.floor(a)array([[ 1.,& 1.],&&&&&& [ 1.,& 1.]])&&& np.exp(a)array([[ 2.,& 2.],&&&&&& [ 2.,& 2.]])&&& np.dot(a,a)&& ##矩阵乘法array([[ 2.,& 2.],&&&&&& [ 2.,& 2.]])
使用numpy下的vstack和hstack函数: 代码如下:&&& a = np.ones((2,2))&&& b = np.eye(2)&&& print np.vstack((a,b))[[ 1.& 1.]&[ 1.& 1.]&[ 1.& 0.]&[ 0.& 1.]]&&& print np.hstack((a,b))[[ 1.& 1.& 1.& 0.]&[ 1.& 1.& 0.& 1.]]
看一下这两个函数有没有涉及到浅拷贝这种问题: 代码如下:&&& c = np.hstack((a,b))&&& print c[[ 1.& 1.& 1.& 0.]&[ 1.& 1.& 0.& 1.]]&&& a[1,1] = 5&&& b[1,1] = 5&&& print c[[ 1.& 1.& 1.& 0.]&[ 1.& 1.& 0.& 1.]]可以看到,a、b中元素的改变并未影响c。
深拷贝数组
数组对象自带了浅拷贝和深拷贝的方法,但是一般用深拷贝多一些: 代码如下:&&& a = np.ones((2,2))&&& b = a&&& b is aTrue&&& c = a.copy()& #深拷贝&&& c is aFalse
基本的矩阵运算
转置: 代码如下:&&& a = np.array([[1,0],[2,3]])&&& print a[[1 0]&[2 3]]&&& print a.transpose()[[1 2]&[0 3]]迹: 代码如下:&&& print np.trace(a)4numpy.linalg模块中有很多关于矩阵运算的方法: 代码如下:&&& import numpy.linalg as nplg
特征值、特征向量: 代码如下:&&& print nplg.eig(a)(array([ 3.,& 1.]), array([[ 0.&&&&&&& ,& 0.],&&&&&& [ 1.&&&&&&& , -0.]]))
numpy也可以构造矩阵对象,这里不做讨论。
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具16458人阅读
编程语言(45)
Python(19)
1&语法错误
语法错误可能是你还在学习python时最为常见的错误,例如
&&& while True print &hi~&
File &&stdin&&, line 1
while True print &hi~&
SyntaxError: invalid syntax
有一个箭头指向最早发现错误的地方,这里指向了print,因为Ture后面少了冒号
2&异常(Exceptions)
即使语句和表达式语法正确,在执行时也可能出现错误,这种错误称为异常(Exceptions)。 异常并不都是致命的,你马上会学到如何处理他们。 许多异常程序都不处理,而是返回一个错误消息,例如:
&&& 10 * (1/0)
Traceback (most recent call last):
File &&stdin&&, line 1, in &module&
ZeroDivisionError: integer division or modulo by zero
&&& 4 + git*3
Traceback (most recent call last):
File &&stdin&&, line 1, in &module&
NameError: name 'git' is not defined
&&& '2' + 1
Traceback (most recent call last):
File &&stdin&&, line 1, in &module&
TypeError: cannot concatenate 'str' and 'int' objects
错误消息的最后一行就是异常消息,冒号前是异常的类型。上面的 ZeroDivisionError, NameError, TypeError, 都是系统内置的异常。
3&处理异常
可以自己编写程序来处理异常,比如下面这个例子,它会返回异常,直到用户输入有效数据为止。
&&& while True:
x = int(raw_input(&Please enter a number: &))
except ValueError:
print &Oops! That was no valid number. Try again...&
Please enter a number: x
Oops! That was no valid number. Try again...
Please enter a number: 32x
Oops! That was no valid number. Try again...
Please enter a number: 038
使用 try 和 except ExceptionName 来处理异常如果没有异常产生,except 段会被跳过如果某处有异常产生,后面的语句会被跳过,如果产生的异常类型和except后的类型一致,except后的语句会被执行如果发生异常,但和except后的类型不一致,异常会传递到try语句外面,如果没有相应处理,那么就会打印出像上 一个例子那样的信息。
一个try语句可能有多个except与之对应,分别处理不同类型的异常,最多只有一种处理会被执行。一个except可以包含多 个类型名,比如:
... except (RuntimeError, TypeError, NameError):
注意上面的三种异常类型,必须用括号把它们括起来,因为在现代python中, except ValueError, e 的意思是 except ValueError as e:(后面会讲这是什么意思)
最后一个except一般不指定名字,用于处理其余情况
import sys
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except IOError as e:
print &I/O error({0}): {1}&.format(e.errno, e.strerror)
except ValueError:
print &Could not convert data to an integer.&
print &Unexpected error:&, sys.exc_info()[0]
try..except 语句还可以选择使用else,例如
for arg in sys.argv[1:]:
f = open(arg, 'r')
except IOError:
print 'cannot open', arg
print arg, 'has', len(f.readlines()), 'lines'
需要注意,一旦使用else,每个except后都要有else,这种方式用于需要指定某一异常不出现时执行什么操作。
except子句可以在异常名后指定参数,这些参数被存储在异常实例产生时的 instance.arg
raise Exception('spam', 'eggs')
... except Exception as inst:
print type(inst)
print inst.args
print inst
x, y = inst.args
print 'x =', x
print 'y =', y
&type 'exceptions.Exception'&
('spam', 'eggs')
('spam', 'eggs')
异常处理不仅仅处理直接在try中出现的异常,还可以处理在try中调用函数的异常
&&& def mdiv():
... except ZeroDivisionError as detail:
print 'Handling run-time error:', detail
Handling run-time error: integer division or modulo by zero
4&raise 异常
raise 语句允许强制一个异常发生
&&& raise NameError('hi,there')
Traceback (most recent call last):
File &&stdin&&, line 1, in &module&
NameError: hi,there
raise 的参数必须是一个异常实例或者一个异常类
5&用户自定义异常
程序可以通过创建一个异常类来命令一个新的异常,这个异常类需要通过直接或者间接的方式由 Exception 类派生。
&&& class MyError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
raise MyError(1+5)
... except MyError as e:
print 'My exception occurred, value:', e.value
My exception occurred, value: 6
&&& raise MyError('oops!')
Traceback (most recent call last):
File &&stdin&&, line 1, in &module&
__main__.MyError: 'oops!'
在上面的例子中,__ init __ (), 覆盖了默认的 init 函数,新的行为创建了 value 属性, 替换了原有的 创建args属性的行为。
其它类可以做的事情,通过定义Exception类都可以完成。但是Exception类总是被设计地非常简单, 它们提供一些属性,这样错误处理时就可能方便地提取出这些属性。 当设计一个模块处理多种异常时,常常先定义一个基本的类,其它类在此基础上处理一些特殊情况。
class Error(Exception):
&&&Base class for exceptions in this module.&&&
class InputError(Error):
&&&Exception raised for errors in the input.
Attributes:
expr -- input expression in which the error occurred
-- explanation of the error
def __init__(self, expr, msg):
self.expr = expr
self.msg = msg
class TransitionError(Error):
&&&Raised when an operation attempts a state transition that's not
Attributes:
prev -- state at beginning of transition
next -- attempted new state
-- explanation of why the specific transition is not allowed
def __init__(self, prev, next, msg):
self.prev = prev
self.next = next
self.msg = msg
6&定义清除(clean-up)操作
try语句还可以定义清除操作,用于无论任何时候都需要被执行的语句。
raise KeyboardInterrupt
... finally:
print 'Goodbye, world!'
Goodbye, world!
Traceback (most recent call last):
File &&stdin&&, line 2, in &module&
KeyboardInterrupt
无论是否发生异常,finally后的语句在离开try之前都会被执行。
下面看一个复杂点的例子,
&&& def divide(x, y):
result = x / y
except ZeroDivisionError:
print &division by zero!&
print &result is&, result
print &excecuting finally clause&
&&& divide (3,2)
result is 1
excecuting finally clause
&&& divide (3,0)
division by zero!
excecuting finally clause
&&& divide (&3&,&1&)
excecuting finally clause
Traceback (most recent call last):
File &&stdin&&, line 1, in &module&
File &&stdin&&, line 3, in divide
TypeError: unsupported operand type(s) for /: 'str' and 'str'
在实例应用中,finally
7&预定义的 清除(Clean-up) 操作
一些对象预先定义了清除操作,当不再需要对象时这些清除操作会被执行,无论使用此对象的操作是否成功。
例如下面的例子:
for line in open(&myfile.txt&):
print line,
上述例子的问题在于,程序执行完后,文件对象仍然没有关闭。
with语句可以使得file这样的对象被及时正确合理地清除
with open(&myfile.txt&) as f:
for line in f:
print line,
原文链接:
&&相关文章推荐
参考知识库
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:455335次
积分:5050
积分:5050
排名:第4908名
原创:93篇
译文:11篇
评论:122条
/minixalpha
文章:13篇
阅读:27389
(1)(2)(1)(1)(1)(3)(1)(2)(6)(5)(5)(6)(2)(2)(2)(3)(1)(2)(2)(1)(11)(29)(1)(2)(2)(1)(2)(3)(4)}

我要回帖

更多关于 手机和相机拍照区别 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信