[Python] Numpy memo

A Numpy memo that is just getting started with machine learning

Reference material

-Numpy and Scipy

Import and usage of numpy

The following are recommended because there are few types and there is little risk of confusion

numpy.py


import numpy as np
np.array([2, 0, 2, 0])

The basics of numpy is ʻarray`, you can also write multidimensional arrays

numpy.py


import numpy as np
x = np.array([[2, 0, 2, 0],[2, 0, 2, 1]])

array arithmetic

numpy.dot function = find vector inner product and matrix product

ʻArray is general-purpose data that represents a collection of data of any dimension, not just for matrix`.

numpy_array.py


import numpy as np
x = np.array([2, 0, 2, 0])
y = np.array([2, 0, 2, 1])
print(x + y)
print(x * y)
print(x.dot(y))

=> [4, 0, 4, 1] #Element by element
=> [4, 0, 4, 0] #Element by element (Caution)
=> 8            #inner product

#Matrix x vector
import numpy as np
A = np.array([[1, 2, 3],[4, 5, 6]])
x = np.array([7, 8, 9])
print(A.dot(x))
=> [ 50, 122]

#Matrix x Matrix
import numpy as np
A = np.array([[1, 2, 3],[4, 5, 6]])
B = np.array([[1, 2], [3, 4], [5, 6]])
print(A.dot(B))

=>[[22 28]
  [49 64]]

matrix arithmetic

matrix is a class that represents a matrix Note that ʻarray and matrix` are different

Characteristics of np.matrix class

numpy_matrux.py


import numpy as np
A = np.matrix([[1, 2, 3],[4, 5, 6]])
B = np.matrix([[1, 2], [3, 4], [5, 6]])
print(A.dot(B)) #numpy.The result of the dot function calculates the inner product together with the array

=> [[22 28]
    [49 64]]

import numpy as np
A = np.matrix([[1, 2, 3],[4, 5, 6]])
B = np.matrix([[1, 2], [3, 4], [5, 6]])
print(A * B) #Operator in matrix"*"Calculate the inner product with

=> [[22 28]
    [49 64]]

import numpy as np
A = np.array([[1, 2, 3],[4, 5, 6]])
B = np.array([[1, 2], [3, 4], [5, 6]])
print(A * B) #An error occurs because the matrix shapes do not match when trying to calculate for each element.

=> ValueError: operands could not be broadcast together with shapes (2,3) (3,2)

Various ways to make an array

python:numpy.array.py


import numpy as np

#Arithmetic progression(Arithmetic progression)
np.arrange(2, 3, 0.2)
=> array([ 2. ,  2.2,  2.4,  2.6,  2,8])

#Arithmetic progression(Specify points)
np.linspace(2, 3, 6)
=> array([ 2. , 2.2, 2.4, 2.6, 2.8, 3. ])

#Line up zore
np.zeros((3, 2))
=> array([[0., 0.],
          [0., 0.],
          [0., 0.]])

#Line up one
np.ones((2, 3))
=> array([[1., 1.],
          [1., 1.],
          [1., 1.]])

#Method
#Make a shape with 0 and assign a value to each element
import numpy as np

def make_diag(n):
  A = np.zeros((n, n))
  for i in range(n):
    A[i, i] = i + 1
  return A

print(make_diag(4))

=> [[1. 0. 0. 0.]
    [0. 2. 0. 0.]
    [0. 0. 3. 0.]
    [0. 0. 0. 4.]]

#Reshape that changes shape while leaving the arrangement of elements as it is
import numpy as np

A = np.arange(0, 15, 1)
print("Contents of A:\n{}".format(A))
B = A.reshape(3, 5)
print("Contents of B:\n{}".format(B))
C = B.reshape(5, 3)
print("Contents of C:\n{}".format(C))

=>Contents of A:
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14]
Contents of B:
[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]]
Contents of C:
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]
 [12 13 14]]

#Use of random numbers random
import numpy as np

np.random.random((3, 3))
=>array([[0.96781535, 0.64650387, 0.05718226],
         [0.78586557, 0.4422813 , 0.92825971],
         [0.94403786, 0.90600626, 0.85543603]])

#Specify each component with a function
import numpy as np

def f(i, j):
  return i + j

A = np.fromfunction(f, (3, 3))
print(A)

=>[[0. 1. 2.]
   [1. 2. 3.]
   [2. 3. 4.]]

Extraction of elements / rows / columns

numpy.py


import numpy as np

A = np.arange(0, 15, 1)
print("A=>\n{}".format(A))
B = A.reshape(3, 5)
print("B=>\n{}".format(B))

print("B[1:2]=>\n{}".format(B[1:2]))
print("B[1:3, 2:3]=>\n{}".format(B[1:3, 2:4]))
print("B[1:3, :]=>\n{}".format(B[1:3, :]))
print("B[:, 2:4]=>\n{}".format(B[:, 2:4]))
print("B[:, 2]=>\n{}".format(B[:, 2]))
print("B[:, :]=>\n{}".format(B[:,:])

A=>
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14]
B=>
[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]]
B[1:2]=>
[[5 6 7 8 9]]
B[1:3, 2:3]=>
[[ 7  8]
 [12 13]]
B[1:3, :]=>
[[ 5  6  7  8  9]
 [10 11 12 13 14]]
B[:, 2:4]=>
[[ 2  3]
 [ 7  8]
 [12 13]]
B[:, 2]=>
[ 2  7 12]
B[:, :]=>
[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]]

Universal function

numpy provides functions with the same names as those provided by the math module, such as sin and cos. They behave as ʻapply to all elements of array for array

universal.py


import numpy as np
import math

r = np.linspace(0, 0.5 * math.pi, 6)
print(r)

sin_r = np.sin(r)
print(sin_r)

cos_r = np.cos(r)
print(cos_r)

print("TypeError when using the function provided by math for numpy")
print(math.sin(r)

[0.         0.31415927 0.62831853 0.9424778  1.25663706 1.57079633]
[0.         0.30901699 0.58778525 0.80901699 0.95105652 1.        ]
[1.00000000e+00 9.51056516e-01 8.09016994e-01 5.87785252e-01
 3.09016994e-01 6.12323400e-17]
TypeError when using the function provided by math
Traceback (most recent call last):
  File "test_conda.py", line 14, in <module>
    print(math.sin(r))
TypeError: only size-1 arrays can be converted to Python scalars

Recommended Posts

[Python] Numpy memo
Python memo
python memo
Python memo
python memo
Python memo
Python memo
Python memo
My Numpy (Python)
[Python] Memo dictionary
python beginner memo (9.2-10)
python beginner memo (9.1)
#Python basics (#Numpy 1/2)
[Python] EDA memo
#Python basics (#Numpy 2/2)
Python 3 operator memo
[My memo] python
Python3 metaclass memo
Python beginner memo (2)
Python class (Python learning memo ⑦)
My python environment memo
Python and numpy tips
python openCV installation (memo)
Python module (Python learning memo ④)
Python basics 8 numpy test
Python test package memo
[Python] Memo about functions
[Python] Search (NumPy) ABC165C
python regular expression memo
Binary search (python2.7) memo
python numpy array calculation
[My memo] python -v / python -V
Python3 List / dictionary memo
[Memo] Python3 list sort
[Python] Memo about errors
DynamoDB Script Memo (Python)
Python basic memo --Part 2
python recipe book Memo
Basic Python command memo
Python OpenCV tutorial memo
Python basic grammar memo
[Python] Sorting Numpy data
TensorFlow API memo (Python)
Python decorator operation memo
Python basic memo --Part 1
Effective Python Memo Item 3
Divisor enumeration Python memo
Python Basic --Pandas, Numpy-
Python / Numpy np.newaxis thinking tips
Python memo (for myself): Array
Python exception handling (Python learning memo ⑥)
Python execution time measurement memo
Convert numpy int64 to python int
Python
Twitter graphing memo with Python
[Line / Python] Beacon implementation memo
Implemented SMO with Python + NumPy
Python and ruby slice memo
Python Basic Grammar Memo (Part 1)
Python code memo for yourself
Matrix multiplication in python numpy