Sei sulla pagina 1di 19

9/25/2019 Numpy

NumPy:
NumPy stands for ‘Numerical Python’ or ‘Numeric Python’. It is an open source module of Python
which provides fast mathematical computation on arrays and matrices. Since, arrays and matrices
are an essential part of the Machine Learning ecosystem, NumPy along with Machine Learning
modules like Scikit-learn, Pandas, Matplotlib, TensorFlow, etc. complete the Python Machine
Learning Ecosystem.

NumPy is extremely important for Data Science because:

Linear algebra library


Powerful and incredibly fast
Integrate C/C++ and Fortran code

Almost all of the PyData (https://pydata.org) Eco-System libraries rely on NumPy


(http://www.numpy.org). This is one of their most important and main building block. In this
section, we will cover the key concepts of this wonderful Python library.

To use numpy, you need to import the module:

In [1]: import numpy as np

Creating Numpy arrays

There are a number of ways to initialize new Numpy arrays, for example from

From Python data type (e.g. List, Tuple)


using functions that are dedicated to generating numpy arrays, such as arange , linspace ,
etc.
reading data from files

From lists

For example, to create new vector and matrix arrays from Python lists we can use the
numpy.array function

In [2]: # a vector: the argument to the array function is a Python list


v = np.array([1,2,3,4])
v

Out[2]: array([1, 2, 3, 4])

In [3]: # a matrix: the argument to the array function is a nested Python list
M = np.array([[1, 2], [3, 4]])
M

Out[3]: array([[1, 2],


[3, 4]])

localhost:8888/notebooks/Numpy.ipynb 1/19
9/25/2019 Numpy

So far the numpy.ndarray looks a lot like a Python list (or nested list). Why not simply use
Python lists for computations instead of creating a new array type?

There are several reasons:

Python lists are very general. They can contain any kind of object. They are dynamically
typed. They do not support mathematical functions such as matrix and dot multiplications, etc.
Implementating such functions for Python lists would not be very efficient because of the
dynamic typing.
Numpy arrays are statically typed and homogeneous. The type of the elements is
determined when array is created.
Numpy arrays are memory efficient.
Because of the static typing, fast implementation of mathematical functions such as
multiplication and addition of numpy arrays can be implemented in a compiled language (C
and Fortran is used).

Speedtest: ndarrays vs lists


In [5]:
from timeit import Timer

size = 1000000
timeits = 1000

In [6]: # create the ndarray with values 0,1,2...,size-1


nd_array = np.arange(size)
print( type(nd_array) )

<class 'numpy.ndarray'>

In [7]: # timer expects the operation as a parameter,


# here we pass nd_array.sum()
timer_numpy = Timer("nd_array.sum()", "from __main__ import nd_array")

print("Time taken by numpy ndarray: %f seconds" %


(timer_numpy.timeit(timeits)/timeits))

Time taken by numpy ndarray: 0.000465 seconds

In [8]: # create the list with values 0,1,2...,size-1


a_list = list(range(size))
print (type(a_list) )

<class 'list'>

localhost:8888/notebooks/Numpy.ipynb 2/19
9/25/2019 Numpy

In [9]: # timer expects the operation as a parameter, here we pass sum(a_list)


timer_list = Timer("sum(a_list)", "from __main__ import a_list")

print("Time taken by list: %f seconds" %


(timer_list.timeit(timeits)/timeits))

Time taken by list: 0.026378 seconds

Using array-generating functions

For larger arrays it is inpractical to initialize the data manually, using explicit pythons lists. Instead
we can use one of the many functions in numpy that generates arrays of different forms.

Most of the times, we use NumPy built-in methods to create arrays. These are much simpler and
faster.

Some of the more common are:

arange()
linspace()
zeros()
ones()
eye()
diag()
Random
rand()
random()
randn()
randint()
reshape()

a. arange()
arange() is very much similar to Python function range()
Syntax: arange([start,] stop[, step,], dtype=None)
Return evenly spaced values within a given interval.

In [10]: # create a range (the end value is not included)


x = np.arange(-1, 1, 0.1) # arguments: start, stop, step
x

Out[10]: array([-1.00000000e+00, -9.00000000e-01, -8.00000000e-01, -7.00000000e-01,


-6.00000000e-01, -5.00000000e-01, -4.00000000e-01, -3.00000000e-01,
-2.00000000e-01, -1.00000000e-01, -2.22044605e-16, 1.00000000e-01,
2.00000000e-01, 3.00000000e-01, 4.00000000e-01, 5.00000000e-01,
6.00000000e-01, 7.00000000e-01, 8.00000000e-01, 9.00000000e-01])

localhost:8888/notebooks/Numpy.ipynb 3/19
9/25/2019 Numpy

In [11]: # range of integers


y = np.arange(0, 10, 1) # arguments: start, stop, step
y

Out[11]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

In [12]: # specifying dtype as float


z = np.arange(0, 10, 1, dtype=float) # arguments: start, stop, step
z

Out[12]: array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])

b. linspace()
Return evenly spaced numbers over a specified interval.
Press shift+tab for the documentation.

In [13]: # start from 1 & end at 15 with 10 evenly spaced points b/w 1 to 15.
print(np.linspace(1, 15, 15))
type(np.linspace(1, 15, 15))

[ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15.]

Out[13]: numpy.ndarray

In [17]: # Lets find the step size with "retstep" which returns the array and the step siz
my_linspace = np.linspace(5, 15, 9, retstep=True)
my_linspace[1]

Out[17]: 1.25

In [15]: # my_linspace[1] to get the stepsize only


type(my_linspace)

Out[15]: tuple

In [18]: my_linspace[0]

Out[18]: array([ 5. , 6.25, 7.5 , 8.75, 10. , 11.25, 12.5 , 13.75, 15. ])

In [19]: my_linspace[1]

Out[19]: 1.25

Don't Confuse!
arange() takes 3rd argument as step size.
linspace() take 3rd argument as no of point we want.

c. zeros()
localhost:8888/notebooks/Numpy.ipynb 4/19
9/25/2019 Numpy

We want to create an array with all zeros

Press shift+tab for the documentation.

In [22]: np.zeros(3,dtype=int) # 1-D with 3 elements

Out[22]: array([0, 0, 0])

In [23]: np.zeros((4,6)) #(no_row, no_col) passing a tuple

Out[23]: array([[0., 0., 0., 0., 0., 0.],


[0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0.]])

d. ones()
We want to create an array with all ones

Press shift+tab for the documentation.

In [24]: np.ones(3)

Out[24]: array([1., 1., 1.])

In [25]: np.ones((4,6)) #(no_row, no_col) passing a tuple

Out[25]: array([[1., 1., 1., 1., 1., 1.],


[1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1., 1.]])

e. eye()
Creates an identity matrix must be a square matrix, which is useful in several linear algebra
problems.

Return a 2-D array with ones on the diagonal and zeros elsewhere.

Press shift+tab for the documentation.

In [26]: np.eye(5)

Out[26]: array([[1., 0., 0., 0., 0.],


[0., 1., 0., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 0., 0., 1., 0.],
[0., 0., 0., 0., 1.]])

localhost:8888/notebooks/Numpy.ipynb 5/19
9/25/2019 Numpy

In [27]: np.eye(5,5) #(no_row, no_col) 2-D


# not work with tuple, list

Out[27]: array([[1., 0., 0., 0., 0.],


[0., 1., 0., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 0., 0., 1., 0.],
[0., 0., 0., 0., 1.]])

f. diag()

In [29]: # diagonal matrix


np.diag([100,2,3])

Out[29]: array([[100, 0, 0],


[ 0, 2, 0],
[ 0, 0, 3]])

f1 full()

In [31]: np.full((3,3),'hello')

Out[31]: array([['hello', 'hello', 'hello'],


['hello', 'hello', 'hello'],
['hello', 'hello', 'hello']], dtype='<U5')

Random
We can also create arrays with random numbers using Numpy's built-in functions in Random
module.
np.random. and then press tab for the options with random

g. rand()
Create an array of the given shape and populate it with random samples from a uniform
distribution over [0, 1) .

In [34]: np.random.rand(3) # 1-D array with three elements

Out[34]: array([0.16437811, 0.0459702 , 0.23898306])

In [35]: np.random.rand(3,2) # row, col, note we are not passing a tuple here, each dimens

Out[35]: array([[0.78843695, 0.28151561],


[0.5046502 , 0.27020184],
[0.87359618, 0.56976549]])

h. random()
localhost:8888/notebooks/Numpy.ipynb 6/19
9/25/2019 Numpy
()
This will return random floats in the half-open interval [0, 1) following the “continuous uniform”
distribution.

np.random.random((4,3))

In [ ]: np.random.random((4,3))

In [ ]:

i. randn()
Return a sample (or samples) from the "standard normal" or a "Gaussian" distribution. Unlike rand
which is uniform.
Press shift+tab for the documentation.

In [36]: np.random.randn(2)

Out[36]: array([ 0.06791608, -1.52310494])

In [39]: np.random.randn(7,7) # no tuple, each dimension as a separate argument

Out[39]: array([[-0.41734204, 2.86720697, 1.88612325, 1.97058795, 0.99696436,


-1.55748597, -0.40747535],
[-0.98546067, -1.31589368, -0.19315516, 0.8294966 , 0.82819375,
1.65204704, -0.46925555],
[-0.02835556, -0.36650945, 0.78357102, -1.98852176, -1.49929055,
1.10327421, 0.06701351],
[-0.8200136 , 2.3969934 , -2.12278874, 0.96642478, 0.9946496 ,
1.02961247, -1.80665935],
[-0.66831113, 0.292122 , -0.0759696 , -0.30946069, -1.48121461,
-0.3123383 , -0.3483075 ],
[ 0.15005687, -0.46378227, 1.83530345, -0.31688979, 0.93685312,
-1.02001673, -0.08549004],
[-1.44899437, -0.88547623, 0.30327419, 1.46845778, -1.46012396,
-1.21464852, 2.15254574]])

Difference between rand() and randn()

localhost:8888/notebooks/Numpy.ipynb 7/19
9/25/2019 Numpy

In [1]: import numpy as np


import matplotlib.pyplot as plt

sample_size = 100000
uniform = np.random.rand(sample_size)
normal = np.random.randn(sample_size)

pdf, bins, patches = plt.hist(uniform, bins=20, range=(0, 1), density=True)


plt.title('rand: uniform')
plt.show()

pdf, bins, patches = plt.hist(normal, bins=20, range=(-4, 4), density=True)


plt.title('randn: normal')
plt.show()

<Figure size 640x480 with 1 Axes>

<Figure size 640x480 with 1 Axes>

i. reshape()
shapes an array without changing data of array.

Syntax : reshape(array, shape, order = ‘C’)

localhost:8888/notebooks/Numpy.ipynb 8/19
9/25/2019 Numpy

In [25]: # Python Program illustrating


# numpy.reshape() method

array = np.arange(8)
print("Original array : \n", array)

# shape array with 2 rows and 4 columns


array = np.arange(8).reshape(2, 4)
print("\narray reshaped with 2 rows and 4 columns : \n", array)

# shape array with 2 rows and 4 columns


array = np.arange(8).reshape(4 ,2)
print("\narray reshaped with 2 rows and 4 columns : \n", array)

# Constructs 3D array
array = np.arange(8).reshape(2, 2, 2)
print("\nOriginal array reshaped to 3D : \n", array)

Original array :
[0 1 2 3 4 5 6 7]

array reshaped with 2 rows and 4 columns :


[[0 1 2 3]
[4 5 6 7]]

array reshaped with 2 rows and 4 columns :


[[0 1]
[2 3]
[4 5]
[6 7]]

Original array reshaped to 3D :


[[[0 1]
[2 3]]

[[4 5]
[6 7]]]

In [40]: np.random.randint(1,100) #returns one random int, 1 inclusive, 100 exclusive

Out[40]: 30

In [41]: np.random.randint(1,100,10) #returns ten random int,

Out[41]: array([11, 86, 59, 68, 60, 77, 69, 14, 16, 29])

Attributes of a NumPy :
Ndim: displays the dimension of the array
Shape: returns a tuple of integers indicating the size of the array
Size: returns the total number of elements in the NumPy array
Dtype: returns the type of elements in the array, i.e., int64, character
Itemsize: returns the size in bytes of each item
localhost:8888/notebooks/Numpy.ipynb 9/19
9/25/2019 Numpy

nbytes: which lists the total size (in bytes) of the array
Reshape: Reshapes the NumPy array

In general, we expect that nbytes is equal to itemsize times size.

In [42]: np.random.seed(0) # seed for reproducibility

x1 = np.random.randint(10, size=6) # One-dimensional array


x2 = np.random.randint(10, size=(3, 4)) # Two-dimensional array
x3 = np.random.randint(10, size=(3, 4, 5)) # Three-dimensional array

In [43]: print("x3 ndim: ", x3.ndim)


print("x3 shape:", x3.shape)
print("x3 size: ", x3.size)

x3 ndim: 3
x3 shape: (3, 4, 5)
x3 size: 60

Each array has attributes ndim (the number of dimensions), shape (the size of each dimension),
and size (the total size of the array):

In [44]: print("the type of elements in the array-dtype:", x3.dtype)

the type of elements in the array-dtype: int32

In [45]: print("itemsize of each item:", x3.itemsize, "bytes")


print("nbytes:total size (in bytes) of the array", x3.nbytes, "bytes")

itemsize of each item: 4 bytes


nbytes:total size (in bytes) of the array 240 bytes

Indexing & slicing of 1-D arrays (vectors)


Similar to the use of slice indexing with lists and strings, we can use slice indexing to pull out sub-
regions of ndarrays.

In [46]: # Lets create a simple 1-D NumPy array.


# (we can use arange() as well.)
array_1d = np.array([-10, -2, 0, 2, 17, 106,200])

In [47]: array_1d

Out[47]: array([-10, -2, 0, 2, 17, 106, 200])

In [48]: # In the simplest case, selecting one or more elements of NumPy array looks very
# Getting value at certain index
array_1d[0]

Out[48]: -10

localhost:8888/notebooks/Numpy.ipynb 10/19
9/25/2019 Numpy

In [49]: # Getting a range value


array_1d[0:3], array_1d
# array_1d is included in the out to compare and understand

Out[49]: (array([-10, -2, 0]), array([-10, -2, 0, 2, 17, 106, 200]))

In [50]: # Using -ve index


array_1d[-2], array_1d
# array_1d is included in the out to compare and understand

Out[50]: (106, array([-10, -2, 0, 2, 17, 106, 200]))

In [52]: # Using -ve index for a range


array_1d[1:-2], array_1d # 1 inclusive and -2 exclusive in this case

Out[52]: (array([], dtype=int32), array([-10, -2, 0, 2, 17, 106, 200]))

In [53]: # Getting up-to and from certain index -- remember index starts from '0'
# (no need to give start and stop indexes)
array_1d[:2], array_1d[2:]

Out[53]: (array([-10, -2]), array([ 0, 2, 17, 106, 200]))

In [54]: # Assigning a new value to a certain index in the array


array_1d[0] = -102

In [55]: array_1d
# The first element is changed to -102

Out[55]: array([-102, -2, 0, 2, 17, 106, 200])

To access any element from 2D-Numpy, the general format is:

array_2d[row][col]
or
array_2d[row,col] .

We will use [row,col] , easier to use comma ',' for clarity.

In [56]: # Rank 2 array of shape (3, 4)


an_array = np.array([[11,12,13,14], [21,22,23,24], [31,32,33,34]])
print(an_array)

[[11 12 13 14]
[21 22 23 24]
[31 32 33 34]]

Use array slicing to get a subarray consisting of the first 2 rows x 2 columns.

localhost:8888/notebooks/Numpy.ipynb 11/19
9/25/2019 Numpy

In [57]: a_slice = an_array[:2, 1:3]


print(a_slice)

[[12 13]
[22 23]]

When you modify a slice, you actually modify the underlying array.

In [58]: print("Before:", an_array[0, 1]) #inspect the element at 0, 1


a_slice[0, 0] = 1000 # a_slice[0, 0] is the same piece of data as an_array[0,
print("After:", an_array[0, 1])

Before: 12
After: 1000

Use both integer indexing & slice indexing


We can use combinations of integer indexing and slice indexing to create different shaped
matrices.

In [2]: import numpy as np


# Create a Rank 2 array of shape (3, 4)
an_array = np.array([[11,12,13,14], [21,22,23,24], [31,32,33,34]])
print(an_array)

[[11 12 13 14]
[21 22 23 24]
[31 32 33 34]]

In [3]: # Using both integer indexing & slicing generates an array of lower rank
row_rank1 = an_array[1, :] # Rank 1 view

print(row_rank1, row_rank1.shape) # notice only a single []

[21 22 23 24] (4,)

In [4]: # Slicing alone: generates an array of the same rank as the an_array
row_rank2 = an_array[1:2, :] # Rank 2 view

print(row_rank2, row_rank2.shape) # Notice the [[ ]]

[[21 22 23 24]] (1, 4)

In [ ]: #We can do the same thing for columns of an array:

print()
col_rank1 = an_array[:, 1]
col_rank2 = an_array[:, 1:2]

print(col_rank1, col_rank1.shape) # Rank 1


print()
print(col_rank2, col_rank2.shape) # Rank 2

localhost:8888/notebooks/Numpy.ipynb 12/19
9/25/2019 Numpy

Array Indexing for changing elements:


Sometimes it's useful to use an array of indexes to access or change elements.

In [ ]: # Create a new array


an_array = np.array([[11,12,13], [21,22,23], [31,32,33], [41,42,43]])

print('Original Array:')
print(an_array)

In [ ]: # Create an array of indices


col_indices = np.array([0, 1, 2, 0])
print('\nCol indices picked : ', col_indices)

row_indices = np.arange(4)
print('\nRows indices picked : ', row_indices)

In [ ]: # Examine the pairings of row_indices and col_indices. These are the elements we
for row,col in zip(row_indices,col_indices):
print(row, ", ",col)

In [ ]: # Select one element from each row


print('Values in the array at those indices: ',an_array[row_indices, col_indices

In [ ]: # Change one element from each row using the indices selected
an_array[row_indices, col_indices] += 100000

print('\nChanged Array:')
print(an_array)

Boolean Indexing / Fancy Indexing / Conditional Indexing

In [2]: # create a 3x2 array


a = np.array([[1,2], [3, 4], [5, 6]])
a

Out[2]: array([[1, 2],


[3, 4],
[5, 6]])

In [3]: # create a filter which will be boolean values for whether each element meets thi
c=a > 2
print(c)

[[False False]
[ True True]
[ True True]]

Notice that the c is a same size ndarray as array a, array c is filled with True for each element
whose corresponding element in array a is greater than 2 and False for those elements whose
value is less than 2.

localhost:8888/notebooks/Numpy.ipynb 13/19
9/25/2019 Numpy

We can use , these comparison expressions directly for access. Result is only those elements for
which the expression evaluates to True.

In [4]: print(a[c])
print(a[c].shape)

[3 4 5 6]
(4,)

notice that the result is a 1D array.

Lets see if this works with writing mulitple conditions as well. In that process we'll also see that we
dont have to store results in one variable and then pass for subsetting. We can instead, write the
conditional expression directly for subsetting.

In [5]: a>2

Out[5]: array([[False, False],


[ True, True],
[ True, True]])

In [6]: a<5

Out[6]: array([[ True, True],


[ True, True],
[False, False]])

In [7]: (a>2) | (a<5)

Out[7]: array([[ True, True],


[ True, True],
[ True, True]])

In [8]: (a>2) & (a<5)

Out[8]: array([[False, False],


[ True, True],
[False, False]])

In [9]: print(a)
a[(a>2) | (a<5)] , a[(a>2) & (a<5)] ###### A, B i.e Multiple operation in one l

[[1 2]
[3 4]
[5 6]]

Out[9]: (array([1, 2, 3, 4, 5, 6]), array([3, 4]))

Arithmetic Array Operations:

localhost:8888/notebooks/Numpy.ipynb 14/19
9/25/2019 Numpy

In [11]: x = np.array([[111,112],[121,122]], dtype=np.int)


y = np.array([[211.1,212.1],[221.1,222.1]], dtype=np.float64)

print(x)
print()
print(y)

[[111 112]
[121 122]]

[[211.1 212.1]
[221.1 222.1]]

In [12]: # add
print(x + y) # The plus sign works
print()
print(np.add(x, y)) # so does the numpy function "add"

[[322.1 324.1]
[342.1 344.1]]

[[322.1 324.1]
[342.1 344.1]]

In [13]: # subtract
print(x - y)
print()
print(np.subtract(x, y))

[[-100.1 -100.1]
[-100.1 -100.1]]

[[-100.1 -100.1]
[-100.1 -100.1]]

In [14]: # multiply
print(x * y)
print()
print(np.multiply(x, y))

[[23432.1 23755.2]
[26753.1 27096.2]]

[[23432.1 23755.2]
[26753.1 27096.2]]

localhost:8888/notebooks/Numpy.ipynb 15/19
9/25/2019 Numpy

In [15]: # divide
print(x / y)
print()
print(np.divide(x, y))

[[0.52581715 0.52805281]
[0.54726368 0.54930212]]

[[0.52581715 0.52805281]
[0.54726368 0.54930212]]

In [16]: # square root


print(np.sqrt(x))

[[10.53565375 10.58300524]
[11. 11.04536102]]

In [17]: # exponent (e ** x)
print(np.exp(x))

[[1.60948707e+48 4.37503945e+48]
[3.54513118e+52 9.63666567e+52]]

In general you'll find that , mathematical functions from numpy [being referred as np here ] when
applied on array, give back result as an array where that function has been applied on individual
elements. However the functions from package math on the other hand give error when applied to
arrays. They only work for scalars.

In [19]: # square root


import math
math.sqrt(x)

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-19-f63d9241fcd6> in <module>
1 # square root
2 import math
----> 3 math.sqrt(x)

TypeError: only size-1 arrays can be converted to Python scalars

np.dot() in Numpy

To multiply two matrices, dot () method is used. Here is an introduction to numpy.dot( a, b,


out=None)

Few specifications of numpy.dot:

If both a and b are 1-D (one dimensional) arrays — Inner product of two vectors (without a
complex conjugation)
If both a and b are 2-D (two dimensional) arrays — Matrix multiplication

localhost:8888/notebooks/Numpy.ipynb 16/19
9/25/2019 Numpy

If either a or b is 0-D (also known as a scalar) — Multiply by using numpy.multiply(a, b) or a *


b.
If a is an N-D array and b is a 1-D array — Sum product over the last axis of a and b.
If a is an N-D array and b is an M-D array provided that M>=2 — Sum product over the last
axis of a and the second-to-last axis of b:

If the last dimension of a is not the same size as the second-to-last dimension of b.

In [20]: v = np.array([9,10]) #### Defining 1-D array


v

Out[20]: array([ 9, 10])

In [21]: w = np.array([11, 12]) #### Defining 1-D array


w

Out[21]: array([11, 12])

In [22]: # Matrix multiplication


v.dot(w)

Out[22]: 219

You can see that result is not what you'd expect from matrix multiplication. This happens because
a single dimensional array is not a matrix.

In [23]: print(v.shape)
print(w.shape)

(2,)
(2,)

In [26]: v=v.reshape((1,2))
w=w.reshape((1,2))
v

Out[26]: array([[ 9, 10]])

Now if you simply try to do v.dot(w) or np.dot(v,w) [both are same] , you will get and error because
you can multiple a mtrix of shape 2X1 with a matrix of 2X1 .

In [27]: np.dot(v,w)

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-27-efb51945670c> in <module>
----> 1 np.dot(v,w)

ValueError: shapes (1,2) and (1,2) not aligned: 2 (dim 1) != 1 (dim 0)

localhost:8888/notebooks/Numpy.ipynb 17/19
9/25/2019 Numpy

In [28]: print('matrix v : ',v)


print('matrix v Transpose:',v.T)
print('matrix w:',w)
print('matrix w Transpose:',w.T)
print('~~~~~~~~~ v multiply with transpose of w')
print(np.dot(v,w.T))
print('~~~~~~~~~ transpose of v is multiply by w')
print(np.dot(v.T,w))

matrix v : [[ 9 10]]
matrix v Transpose: [[ 9]
[10]]
matrix w: [[11 12]]
matrix w Transpose: [[11]
[12]]
~~~~~~~~~ v multiply with transpose of w
[[219]]
~~~~~~~~~ transpose of v is multiply by w
[[ 99 108]
[110 120]]

If you leave v to be a single dimensional array . you will simply get an element wise multiplication.
Here is an example

In [29]: print(x)
v=np.array([9,10])
print("~~~~~")
print(v)
x.dot(v)

[[111 112]
[121 122]]
~~~~~
[ 9 10]

Out[29]: array([2119, 2309])

In [30]: print(x)
print("~~~")
print(y)
x.dot(y)

[[111 112]
[121 122]]
~~~
[[211.1 212.1]
[221.1 222.1]]

Out[30]: array([[48195.3, 48418.3],


[52517.3, 52760.3]])

In [ ]:

localhost:8888/notebooks/Numpy.ipynb 18/19
9/25/2019 Numpy

localhost:8888/notebooks/Numpy.ipynb 19/19

Potrebbero piacerti anche