














Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
An overview of Numpy arrays, which are vastly different than Sage matrices. Numpy arrays have many similarities with matlab arrays and can have any number of dimensions. They can be initialized with a specified data type and can be reshaped, sliced, and have various attributes such as flags, shape, strides, ndim, data, size, itemsize, ctypes, and __array_interface__.
What you will learn
Typology: Study notes
1 / 22
This page cannot be seen from the preview
Don't miss anything!
%hide
%html
The Guide to NumPy is
Travis Oliphant's book about numpy. The description of
functions in this worksheet draws heavily on that.
Numpy arrays are vastly different than Sage matrices, to put
it mildly. Essentially
every rule, constraint, convention, etc., is different. They
server a very different purpose.
They are meant to be the ultimate Python general $n$-dimensional
dense array object. In contrast, Sage matrices are meant to be
very mathematical objects with clear mathematically meaningful
semantics and very fast algorithms mainly for algebraic
computations.
Numpy array have many similarities with matlab arrays, given that
they have very similar computational domains.
See Numpy for
Matlab Users for a table that compares
and contrasts their functions. That page also has an excellent
table showing equivalent commands in Matlab and Numpy.
The Guide to NumPy is Travis Oliphant's book about numpy. The
description of functions in this worksheet draws heavily on that.
Numpy arrays are vastly different than Sage matrices, to put it mildly.
Essentially every rule, constraint, convention, etc., is different. They
server a very different purpose. They are meant to be the ultimate
Python general -dimensional dense array object. In contrast, Sage
matrices are meant to be very mathematical objects with clear
mathematically meaningful semantics and very fast algorithms mainly
for algebraic computations.
Numpy array have many similarities with matlab arrays, given that they
have very similar computational domains. See Numpy for Matlab Users
for a table that compares and contrasts their functions. That page also
has an excellent table showing equivalent commands in Matlab and
Numpy.
import numpy
%hide
%html
Create a numpy array as follows. For numeric types, one can and
n
s += 'r'*ncols + '}\n'
for i in range(nrows):
s += ' & '.join([latex(A[i,j]) for j in range(ncols)]) +
'\\\n'
s += r'\end{array}\right)'
html('$%s$'%s)
shownp(Z)
shownp(numpy.dot(Z,Z))
A = numpy.array([1..10])
shownp(A)
%hide
%html
Numpy arrays can have any number of dimensions!
Think of these higher dimensional arrays as arrays of arrays (of
arrays...). They are useful, e.g., in image processing, where
there is one array for each color channel.
Numpy arrays can have any number of dimensions! Think of these
higher dimensional arrays as arrays of arrays (of arrays...). They are
useful, e.g., in image processing, where there is one array for each color
channel.
p
2 + 3
3
2
p
2 + 3
p
2 + 3
p
2 + 3
M = numpy.array([[[1,2], [3,4]], [[1/3,5], [10,2]], [[8,1],
[-5,2]]], dtype=int)
array([[[ 1, 2],
[ 3, 4]],
type(M[0,0,0])
<type 'numpy.int32'>
M[0,0,0].item()
shownp(M)
the array%u2019s
M.dtype
dtype('int32')
M.dtype = float
shownp(M)
4 : 24399158242 e À 314
8 : 48798316534 e À 314
1 : 06099789548 e À 313
4 : 24399158687 e À 314
shownp(M.reshape((4,3)))
M.shape
in
M.strides
M.ndim
data
d = M.data; d
<read-write buffer for 0x7cc3470, size 48, offset 0 at 0x7fda800>
d[0:10]
'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00'
type(d)
<type 'buffer'>
M.size
M.flat
<numpy.flatiter object at 0xe83e00>
len(M.flat)
list(M.flat)
M.flat[0] = 20090283
shownp(M)
M.ctypes
<numpy.core._internal._ctypes object at 0x7fda7d0>
type(M.ctypes)
<class 'numpy.core._internal._ctypes'>
M.ctypes.data
M.array_interface
{'descr': [('', '<i4')], 'strides': None, 'shape': (3, 2, 2),
'version': 3, 'typestr': '<i4', 'data': (130823360, False)}
M.array_struct
<PyCObject object at 0x7a16740>
ndarray
M.array_priority
%hide
%html
type(A[0,0])
<type 'numpy.float64'>
A[0,0] = 10; shownp(A)
A.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : True
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
A.flags['WRITEABLE'] = False
A.flags
C_CONTIGUOUS : True
F_CONTIGUOUS : False
OWNDATA : True
WRITEABLE : False
ALIGNED : True
UPDATEIFCOPY : False
Traceback (click to the left for traceback)
...
RuntimeError: array is not writeable
before = A.flags['WRITEABLE']
A.flags['WRITEABLE'] = True
A.flags['WRITEABLE'] = before
shownp(A)
B = matrix(RDF, 3, 3, [1..9])
B.set_immutable()
subtle
Traceback (click to the left for traceback)
...
ValueError: matrix is immutable; please change a copy instead (use
self.copy()).
save(M, DATA+'M.sobj')
print M.dumps()
(M == loads(M.dumps())).all()
€cnumpy.core.multiarray
_reconstruct
qcnumpy
ndarray
qK?…U‡Rq(KKKK‡cnumpy
dtype
qUi4K?K‡Rq(KU<NNNJÿÿÿÿJÿÿÿÿK?tb‰U0?ʏ\
5533;??ûÿÿÿ???tb.
True
load(DATA+'M.sobj')
array([[[ 1, 2],
[ 3, 4]],
%hide
%html
type(B)
<type 'sage.matrix.matrix_integer_dense.Matrix_integer_dense'>
M = matrix(CDF, 3, [1,2,3.4, 1.2, 2.5, -1.3, 2+I,2-I,e]); M
A = M.numpy(); A
array([[ 1.00000000+0.j, 2.00000000+0.j, 3.40000000+0.j],
[ 1.20000000+0.j, 2.50000000+0.j, -1.30000000+0.j],
[ 2.00000000+1.j, 2.00000000-1.j, 2.71828183+0.j]])
A.dtype
dtype('complex128')
%hide
%html
Functionality
A = random_matrix(RDF,3).numpy()
shownp(A)
A.max()
max(A)
Traceback (click to the left for traceback)
...
ValueError: The truth value of an array with more than one element
is ambiguous. Use a.any() or a.all()
A.min()
A.ptp()
set to min
shownp(A.clip(min=-0.5, max=0.5))
array
B = random_matrix(CDF, 3).numpy()
print "Matrix B = ",
shownp(B)
print "\nComplex conjugate = ",
shownp(B.conj())
Matrix B =
Complex conjugate =
shownp(A)
shownp(A.round())
shownp(A)
A.trace()
(0.476948747614-0.694197532337j)
(-0.106544963575-0.879795738338j)
(-0.37540094272+0.835285088525j)
(0.476948747614+0.694197532337j)
(-0.106544963575+0.879795738338j)
(-0.37540094272-0.835285088525j)
shownp(A)
A.var()
shownp(A)
A.std()
sqrt(A.var())
A.prod()
A.all()
True
B = A.copy(); B[0,0] = 0
B.all()
False
A.any()
True
%hide
%html
(a )
NÀ 1
i=
i
2
import numpy
shownp(numpy.cov(A))
shownp(numpy.corrcoef(A))
%hide
%html
Numpy (and Sage) both have sophisticated array slicing somewhat
like Matlab.
Numpy (and Sage) both have sophisticated array slicing somewhat like
Matlab.
shownp(A)
shownp(A[:2,])
shownp(A[:3,0:2])
shownp(A[1:3,0:2])
shownp(A[1:3,1:3])
B = matrix(A); show(B) # sage matrix
show(B[1:3, 1:3])
show(B[:3, 0:2])
%hide
%html
A key difference between numpy and sage slicing, is that in
Sage the slices are new copies, but in numpy they are references
into the original matrix!
A key difference between numpy and sage slicing, is that in Sage the
slices are new copies, but in numpy they are references into the original
matrix!
shownp(A)