2021/12/25/SAT
import numpy as np
a=np.array([100.,101.,102.,103.])
a.shape # 1차원 4개 요소
a.ndim
a[0]
a[1]
a[-1]
a
a[[1,3]]
a[-3:-1]
a[1:4:1]
a[1:4]
a[1:4:2]
a[:]
a[::2]
a[::-2]
a2=np.array([[11,12],[23 ,34]])
a2
a2.shape
a2.ndim
a2[0][1] # 겉차원 -> 속차원
a2[0,1]
a
a[[0,1]]
# 인덱스 0번쨰와 1번째 거 추출
# 따라서 a2의 첫 번째 원소와 두 번째 원소만 추출됨
a2[[0,1]]
a2[:]
a2[:,:]
행렬처럼 생각하자
a2
a2[0,:]
a2[1,:]
b=a2[:,0]
b
b.shape
b.ndim
b_=b[:,np.newaxis]
b_
b_.shape
b_.ndim
또는
b.shape=(1,2)
b
a3=np.array([[[ 1,2],[3,4 ],[5,6 ],[7,8 ],[9,10]]])
a3
a3[0,0,1]
a3.shape
# 큰 덩어리 1개, 작은 덩어리 5개, 그 안에 요소 2개씩
a3.ndim #3차원
a3[0,1,1]
# 당연히 없을 것
# 큰 덩어리는 하나임
x=np.array([12,34,14,0,34])
idx=np.where(x==34)
idx
x[idx]
idx=(x==14)
idx
x[idx]
x[np.where(x==12)]
x
np.nonzero(x)
x[np.nonzero(x)]
x==0
np.nonzero(x==14)
np.nonzero(x==0)
x[np.nonzero(x==0)]
x[np.nonzero(x==34)]
image processing시, 논리연산을 통한 idexing 중요
image=np.array([[255,0,255],
[255,0,255],
[255,0,255]])
image.shape
# 2차원, 큰덩어리 세개, 그 안에 요소 3개
idx=np.where(image==255)
idx
(0,0)(0,2)(1,0)(1,2)(2,2) 자리에 255가 있다
image[idx]=0
image
이런식으로 논리연산을 통한 indexing으로 다 검정색을 만들어버림
a=np.array([[10,20],[30,40]])
b=np.array([[1,2],[3,4]])
a
b
a * b
a @ b
a.dot(b)
#행렬 연산
a=np.zeros((3,3))
a
b=np.ones((3,3))
b
c=np.trace(b)
c
$x@a=y$ 에서 a행렬 구해보기
x=np.array([[1,-3],[2,4]])
y=np.array([[1],[3]])
print(x)
print(y)
x_inverse=np.linalg.inv(x)
a=x_inverse@y
a
혹은
a=np.linalg.solve(x,y)
a
그 외에도 고유벡터, 고유값, 특이값 분해도 np에서 함수사용할 수 있다
a=np.zeros((5,5))
np.fill_diagonal(a,12)
a
#대각원소만 12로 변경
a=np.array([[1,2,3],[3,4,4],[5,43,6]])
b=np.array([[1],[2],[3]])
b
b=b.repeat(3,axis=1)
b
- 이제 원소대 원소 곱해주면 된다
c=a*b
c
- broadcasting : size알아서 처리해주는 기능
a
b=np.array([[1],[2],[3]])
b
a*b
def f(x,y):
return 100*x+y
np.fromfunction(f,(4,4),dtype=int)
- 행이 x축 역할하고 열이 y축 역할을 함으로써, 격자로 더해준다고 생각하면 됨
a=np.array([10,20,30,40,50])
b=np.array([30,50])
np.setdiff1d(a,b)
np.random.randint(54)
import matplotlib.pyplot as plt
y=np.array([10,20,30])
plt.plot(y)
x=np.array([123,413,555])
plt.plot(x,y,'r--.')
#data가 들어간 곳에 dot으로 표시
plt.plot(x,y,'b-o',label='fuck')
plt.ylabel('sd')
plt.xlabel('SD')
plt.legend()
plt.title('What\'s this?')
hf=plt.figure() # 도화지
ha1 = hf.add_axes([0,0,1,1]) # 0,0자리에 1,1크기만큼
ha2 = hf.add_axes([1,1,1,1]) # 0,0자리에 1,1크기만큼
ha1.plot(x,y,'o-r')
ha2.plot(x,y,'x:b')
aa,bb=plt.subplots()
hong,=bb.plot(x,y)
# 이렇게 aa,bb는 임의로 지명 가능
- 위 그래프 update
a_new=np.array([200,331,335])
b_new=np.array([10,50,10])
hong.set_data(a_new,b_new)
aa
주의:애초에 aa라는 도화지에 정해진 축이 있기 때문에 그 축에서 너무 멀어지는 값들을 넣어주면 aa라는 도화지에 보이지 않을 수 있음
PLUS=1.5
a_new=np.array([200,331,335])
b_new=np.array([10,50,10])
hong.set_data(a_new,PLUS*b_new)
aa
그래프가 올라간 것을 확인할 수 있음
a=np.linspace(0,2,100)
y1=0.5*a
y2=0.5*a**2
y3=0.5*a**3
plt.plot(a,y1,label='1D')
plt.plot(a,y2,label='2D')
plt.plot(a,y3,label='3D')
plt.legend()
plt.xlabel('X')
plt.ylabel('Y')
plt.title('GRAPH')
fig,ax=plt.subplots()
ax1,=ax.plot(a,y1) # comma 입력해주면 나중에 update 가능
ax2,=ax.plot(a,y2)
ax3,=ax.plot(a,y3)
ax.set_xlabel('X') # plt가 아닐 땐 set을 입력해줘야 함
ax.set_ylabel('Y')
ax1.set_label('1')
ax2.set_label('2')
ax3.set_label('3')
ax.legend()
ax1.set_color('k')
ax2.set_color('b')
ax3.set_color('r')
ax.grid()
ax.legend()
fig
decay sin
t=np.linspace(0,100,1000)
tau= 60
y=np.sin(t)*np.exp(-t/tau)
plt.plot(t,y,label='Decay Oscillating Response')
plt.ylabel('y[m]')
plt.xlabel('t[s]')
plt.legend()
Euler eq
t=np.linspace(0,1,100)
f= 1 # 주파수
y_euler=np.exp(1j*2*np.pi**f*t)
y_cos = np.real(y_euler)
y_sin=np.imag(y_euler)
fig,ax=plt.subplots()
ax.plot(t,y_cos,'-r',label='cos')
ax.plot(t,y_sin,'--b',label='sin')
ax.grid()
ax.legend()
fig,ax=plt.subplots(2,)
ax[0].plot(t,y_cos,'-r',label='cos')
ax[1].plot(t,y_sin,'--b',label='sin')
ax[0].grid()
ax[0].legend()
ax[1].grid()
ax[1].legend()
Histogram
data=np.random.randn(500000)
plt.hist(data,100,density=True) # 100개의 막대로 나누겠다, 확률밀도함수로 그리겠다
x=np.linspace(-4,4,100)
sigma=1
mean=0
nd=(1/(sigma*np.sqrt(2*np.pi)))*np.exp(-0.5*((x-mean)/sigma)**2)
plt.plot(x,nd,'r',label='Std Normal Dist')
plt.ylabel('PSD')
plt.xlabel('X')
plt.legend()
3D plot
x=np.linspace(0,2*np.pi,10)
y=np.linspace(0,2*np.pi,10)
grid_x,grid_y=np.meshgrid(x,y) # 1차원 array를 통해 2차원 grid를 만들어줌
z=np.sin(grid_x)*np.sin(grid_y)
fig=plt.figure()
ax=fig.gca(projection='3d') # Get Current Axis=gca
ax.plot_surface(grid_x,grid_y,z,cmap='jet')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
Animation
# x=np.array([1,2,3,4,5])
# y=np.array([1,1,1,1,1])
# ax1, = ax.plot(x,y)
# ax.set_ybound([0,11])
# for i in range(0,11,1):
# ax1.set_ydata(i*y)
# plt.pause(0.3)
# 원래는 animation기능으로 움직여야 함