donut

'행렬'에 해당되는 글 2건

  1. Python Numpy3
  2. Python Numpy2

Python Numpy3

Module/Numpy

 

 

 

 

Numpy3

지난 넘피1,2에 이어 3번째 포스팅입니다.
2편에서 마무리 짓지 못하고 3번째 까지 왔네요
너무 방대한 양이다보니... 그래도 인공지능으로 넘어가기전 알고가야할 부분이니까 열심히 해야겠죠?

2편에서 마무리 짓지 못했던 numpy 특수계산, 크기비교를 알아보도록 하겠습니다.

In [86]:
import numpy as np
 

numpy all&any

any = 배열 원소값중 어떤 값들 중 하나라도 조건에 만족하면 True를 반환

all = 모든 원소값이 조건을 만족하면 True를 반환

In [87]:
test = np.arange(10)
test
Out[87]:
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [88]:
np.any(test>4) #원소값중 4보다 큰 값이 존재 함으로 True
Out[88]:
True
In [107]:
np.all(test>4) #모든 원소값이 4보단 크지 않기때문에 False
Out[107]:
False
In [108]:
np.all(test>=0)#모든 원소값은 0보다 크거나 같기 때문에 True
Out[108]:
True
 

Numpy 크기 비교

In [91]:
test1 = np.array([1,20,33])
test2 = np.array([10,10,10])
print(test1>test2)#배열의 각 인덱스별 크기 비교
print(test1==test2)
print((test1>test2).any())#배열의 각인덱스별 크기 비교중 하나라도 만족한다면 True
print((test1>test2).all())#배열의 각인덱스별 크기 비교중 모두 만족한다면 True
 
[False  True  True]
[False False False]
True
False
In [113]:
#앞서 크기비교 한것을 2차원배열로 확장
test1 = np.array([[10,20,33],[11,22,33]])
test2 = np.array([[10,10,10],[100,1,0]])
print(test1>test2)
print(test1>20)
print(test1==test2)
print((test1>test2).any())
print((test1>test2).all())
 
[[False  True  True]
 [False  True  True]]
[[False False  True]
 [False  True  True]]
[[ True False False]
 [False False False]]
True
False
 

Numpy 크기 비교2

np.logical_and

np.logical_not

Np.logical_or

In [110]:
test1 = np.array([1,20,33])
np.logical_and(test1>0,test1<10)#두 조건을 만족한다면 True
Out[110]:
array([ True, False, False])
In [111]:
test2 = np.array([False,True,True])
np.logical_not(test2)#반대값 출력 
Out[111]:
array([ True, False, False])
In [112]:
test3 = np.array([False,False,True])
np.logical_or(test2,test3)#하나라도 True라면 True 반환
Out[112]:
array([False,  True,  True])
 

Numpy where

np.where(조건, 참일때 반환할 값, 거짓일때 반환할 값)

In [122]:
test1 = np.array([1,20,33])
np.where(test1>5,100,2)
Out[122]:
array([  2, 100, 100])
In [123]:
test2 = np.arange(10)
np.where(test2>4) #배열 원소값이 4보다 큰 값들의 인덱스를 반환
Out[123]:
(array([5, 6, 7, 8, 9]),)
In [129]:
test3 = np.array([1,10,4,5,6,50,1,100])
np.where(test3>4)#배열 원소값이 4보다 큰 값들의 인덱스를 반환
Out[129]:
(array([1, 3, 4, 5, 7]),)
In [125]:
test4 = np.array(["1", 2,"2" ,np.NaN, np.Inf], float)
np.isnan(test4)#Not a Number숫자가 아닌, / Infinity 무한대 
Out[125]:
array([False, False, False,  True, False])
 

Numpy argmax & argmin

In [126]:
test1 = np.array([1,10,4,5,6,50,1,100])
np.argmax(test1), np.argmin(test1)# 배열값중 최대값 , 최소값의 인덱스 추출
Out[126]:
(7, 0)
In [131]:
test2 = np.array([[111,222,333],[555,666,777],[123,633,768]])
test2,np.argmax(test2), np.argmin(test2)#다차원 배열에서도 적용가능, 인덱스를 새는 방법에 주목
Out[131]:
(array([[111, 222, 333],
        [555, 666, 777],
        [123, 633, 768]]),
 5,
 0)
In [132]:
np.argmax(test2, axis=1) , np.argmin(test2,axis=0)#axis를 활용하여 접근 / 1은 가로로, 0은 세로로
Out[132]:
(array([2, 2, 2]), array([0, 0, 0]))
 

Numpy boolean index

In [133]:
test1 =np.array([
    [1,2,3,4,5,6,7,8,9,10],
    [1,2,3,4,5,6,7,8,9,10],
    [1,2,3,4,5,6,7,8,9,10],
    [1,2,3,4,5,6,7,8,9,10],
    [1,2,3,4,5,6,7,8,9,10],
    [1,2,3,4,5,6,7,8,9,10]
])
test2 = test1 < 5#값들이 5보다 작다면 False
test2
Out[133]:
array([[ True,  True,  True,  True, False, False, False, False, False,
        False],
       [ True,  True,  True,  True, False, False, False, False, False,
        False],
       [ True,  True,  True,  True, False, False, False, False, False,
        False],
       [ True,  True,  True,  True, False, False, False, False, False,
        False],
       [ True,  True,  True,  True, False, False, False, False, False,
        False],
       [ True,  True,  True,  True, False, False, False, False, False,
        False]])
In [134]:
test2.astype(np.int)#True는 1, False는0으로 변환
Out[134]:
array([[1, 1, 1, 1, 0, 0, 0, 0, 0, 0],
       [1, 1, 1, 1, 0, 0, 0, 0, 0, 0],
       [1, 1, 1, 1, 0, 0, 0, 0, 0, 0],
       [1, 1, 1, 1, 0, 0, 0, 0, 0, 0],
       [1, 1, 1, 1, 0, 0, 0, 0, 0, 0],
       [1, 1, 1, 1, 0, 0, 0, 0, 0, 0]])
 

이상으로 numpy 포스팅을 마칩니다.
너무 방대한 양이라 빠진부분들도 있습니다.
네이버 부스트코스 파이썬을 참고하였습니다.

In [ ]:
 

'Module > Numpy' 카테고리의 다른 글

Python Numpy2  (0) 2020.07.12
Python Numpy1  (0) 2020.07.12

Python Numpy2

Module/Numpy

 

 

 

 

Numpy 2

지난 Numpy 관련 첫번째 포스팅에 이어지는 2번째 기록입니다.
지난 시간에는 넘피 선언, 배열확인, 다차원 배열, 배열 재정립등에서 포스팅 하였습니다.

이번엔 슬라이싱, 특수 처리, 계산에 대하여 포스팅 하겠습니다.

In [2]:
#시작에 앞서 np 선언
import numpy as np
 

numpy indexing

numpy 인덱스 접근

In [6]:
test = np.array([[111,222,333],[555,666,777]])
print(test,'\n')#2행 3열 메트릭스 배열 
print(test[0],'\n')# 0번째 행 
print(test[0,0],'\n')#0번째 행 0번째 인덱스 요소
print(test[0][0],'\n')#0번째 행 0번째 인덱스 요소
 
[[111 222 333]
 [555 666 777]] 

[111 222 333] 

111 

111 

 

numpy slicing

numpy 슬라이싱

In [17]:
test = np.array([[111,222,333],[555,666,777],[123,633,768]])
print(test[:],'\n')#모두 출력
print(test[1:],'\n')#인덱스1행 부터 출력
print(test[:-1],'\n')#맨뒤를 제외하고 모든 인덱스행 출력
print(test[1,1:3],'\n')#인덱스1행에서 1,2인덱스 요소 출력
print(test[1,0:3],'\n')#인덱스1행에서 0,1,2인덱스 요소 출력
print(test[1,::2],'\n')#인덱스 1행에서 한칸씩 뛰고 인덱스 출력
 
[[111 222 333]
 [555 666 777]
 [123 633 768]] 

[[555 666 777]
 [123 633 768]] 

[[111 222 333]
 [555 666 777]] 

[666 777] 

[555 666 777] 

[555 777] 

 

numpy ones, zeros

모든 요소가 1또는 0인 행렬

In [84]:
test1 = np.zeros((3,4))
test2 = np.zeros(shape=(3,4))
print(test1,'\n')
print(test2)
 
[[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]] 

[[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]
In [85]:
test1 = np.ones((3,4))
test2 = np.ones(shape=(3,4))
print(test1,'\n')
print(test2)
 
[[1. 1. 1. 1.]
 [1. 1. 1. 1.]
 [1. 1. 1. 1.]] 

[[1. 1. 1. 1.]
 [1. 1. 1. 1.]
 [1. 1. 1. 1.]]
 

numpy identity

단위행렬 (가로 세로의 길이가 같고 대각선에만 1 나머진 0)

In [30]:
np.identity(10)
Out[30]:
array([[1., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 1., 0., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 1., 0., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 1., 0., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 1., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 1., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 1., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 1., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 1., 0.],
       [0., 0., 0., 0., 0., 0., 0., 0., 0., 1.]])
In [32]:
np.identity(n=4, dtype = int)
Out[32]:
array([[1, 0, 0, 0],
       [0, 1, 0, 0],
       [0, 0, 1, 0],
       [0, 0, 0, 1]])
 

numpy eye

대각선의 값이 1인 행렬생성, 대각선시작 위치를 선언 가능

In [33]:
np.eye(N=4, M=5,dtype=int)
Out[33]:
array([[1, 0, 0, 0, 0],
       [0, 1, 0, 0, 0],
       [0, 0, 1, 0, 0],
       [0, 0, 0, 1, 0]])
In [36]:
np.eye(N=4, M=5,k=3,dtype=int)
Out[36]:
array([[0, 0, 0, 1, 0],
       [0, 0, 0, 0, 1],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]])
 

numpy diag

행렬에서 대각선에 있는 값 추출

In [47]:
test =np.arange(12).reshape(4,3)
print(test)
print(np.diag(test))
print(np.diag(test, k=1))
 
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]
[0 4 8]
[1 5]
 

Numpy random sampling

데이터 분포에따른 균등분포와, 정규분포
nuiform(m,s,n)
normal(m,s,n)
m= 평균
s= 표준편차
n= 표본 수

In [51]:
np.random.uniform(0,1,10).reshape(2,5)
Out[51]:
array([[0.07207403, 0.17562454, 0.08155453, 0.61678642, 0.44434153],
       [0.69988152, 0.89725396, 0.26241236, 0.72943985, 0.47883354]])
In [52]:
np.random.normal(0,1,20).reshape(4,5)
Out[52]:
array([[-0.8667263 ,  0.23096233,  1.09094323,  0.38321506, -0.81504225],
       [ 0.9462905 ,  0.98660504,  1.85126187,  0.70032458,  0.0239339 ],
       [ 0.9048189 , -0.11227337, -1.2831095 ,  0.60489643,  0.36733851],
       [-0.15573663, -0.11809552, -0.49308224, -0.63444637, -0.3384238 ]])
 

Numpy axis

In [60]:
test = np.array([[[0,1,2],[3,4,5],[6,7,8],[111,222,333]],
                  [[9,10,11],[12,13,14],[15,16,17],[111,222,333]]])
In [61]:
test.shape
Out[61]:
(2, 4, 3)
 

(2,4,3)
= > (axis =0 , axis =1 , axis =2)
= > (테이블 , 세로(로우),가로(컬럼))

아래 numpy계산에서 한번더 보면서 생각해야합니다.

 

Numpy 계산

In [86]:
test = np.arange(1,17).reshape(4,4)
test
Out[86]:
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12],
       [13, 14, 15, 16]])
In [88]:
print(test.mean()) #모든 요소들의 평균
print(test.mean(axis = 0))#컬럼들의 평균 -> (1 + 5 + 9 + 13) / 4 = 7
print(test.mean(axis = 1))#로우의 평균 - >(1+2+3+4)/4 = 2.5
 
8.5
[ 7.  8.  9. 10.]
[ 2.5  6.5 10.5 14.5]
In [89]:
#기본 사칙 연산 가능
# + 외에 다른 사칙연산 대입하면됩니다.
test + test
Out[89]:
array([[ 2,  4,  6,  8],
       [10, 12, 14, 16],
       [18, 20, 22, 24],
       [26, 28, 30, 32]])
In [70]:
#브로드캐스팅 1
# + 외에 다른 사칙연산 대입하면됩니다.
test + 3 
Out[70]:
array([[ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19]])
In [74]:
#브로드캐스팅 2
#위 브로드캐스팅 1에선 수 와 계산 했습니다.
#이번엔 차원 수가 다른 배열끼리의 계산입니다.
#각 행마다 1,2,3,4를 각각 요소에 맞게 더해줍니다.
test2 = np.array([1,2,3,4])
test + test2
Out[74]:
array([[ 2,  4,  6,  8],
       [ 6,  8, 10, 12],
       [10, 12, 14, 16],
       [14, 16, 18, 20]])
 

numpy transpose

행과 열의 변환

In [79]:
test = np.arange(1,13).reshape(4,3)
test
Out[79]:
array([[ 1,  2,  3],
       [ 4,  5,  6],
       [ 7,  8,  9],
       [10, 11, 12]])
In [80]:
test.transpose()
Out[80]:
array([[ 1,  4,  7, 10],
       [ 2,  5,  8, 11],
       [ 3,  6,  9, 12]])
In [82]:
test.T
Out[82]:
array([[ 1,  4,  7, 10],
       [ 2,  5,  8, 11],
       [ 3,  6,  9, 12]])
 

numpy transpose2 (Dot)

행과 열의 구조가 다를때 계산

In [83]:
test.dot(test.T)
Out[83]:
array([[ 14,  32,  50,  68],
       [ 32,  77, 122, 167],
       [ 50, 122, 194, 266],
       [ 68, 167, 266, 365]])
 

numpy3에서 이어집니다.

In [ ]:
 

'Module > Numpy' 카테고리의 다른 글

Python Numpy3  (0) 2020.07.13
Python Numpy1  (0) 2020.07.12