티스토리 뷰
연습문제¶
체스판 형태로 배열을 만들려고 한다. a= np.arange(81).reshape(9,9) chess = a%2 위의 결과를 출력하여 확인하시오.
위의 결과를 plt.imshow() 함수를 써서 표시하시오.
100x100 형태의 표준정규분포로 랜덤 배열을 생성하여, plt.imshow() 함수로 표시하시오.
In [2]:
import numpy as np
a = np.arange(81).reshape(9,9)
chess = a%2
In [3]:
chess
Out[3]:
In [6]:
import matplotlib.pyplot as plt
plt.imshow(chess)
plt.colorbar()
Out[6]:
In [11]:
an = np.random.randn(100,100)
np.shape(an)
Out[11]:
In [12]:
plt.imshow(an)
plt.colorbar()
Out[12]:
Numpy 랜덤생성 함수 2¶
normal()¶
- 평균과 표준편차를 지정하여 랜덤 숫자 선택
In [14]:
a = np.random.normal(10,5,size=10000) # 0.00235 = 2.35e-3, 235 = 2.35e+2
a[:100]
Out[14]:
In [17]:
plt.hist(a, bins=100)
plt.title('Histogram')
Out[17]:
In [18]:
a.mean()
Out[18]:
In [19]:
a.std()
Out[19]:
In [20]:
(a<-5).sum()
Out[20]:
uniform()¶
정해진 범위 내에서 실수 선택
In [21]:
a = np.random.normal([100,200],20,size=10000)
a[:100]
permutation()¶
permutation은 섞어 결과를 내어주는데, shuple은 자기 자신을 섞음.
In [23]:
a = np.arange(100)
a
Out[23]:
In [24]:
a2 = np.random.permutation(a) # 기존의 값들을 마음대로 섞어버리기
a2
Out[24]:
In [30]:
plt.plot(a, label='a')
plt.plot(a2, 'ro--', label='a2') # r: red, o : 동그라미, --: 점선, g: green, ^: 세모, ':' : 세밀한 점선
plt.legend() # 범례를 쓰겠다.
Out[30]:
연습문제¶
Iris 데이터를 줄 단위로(샘플 단위로) 섞으시오.
In [61]:
f = open('iris.csv')
line = f.readline()
features = line.strip().split(',')[:4]
labels = ['Iris-setosa', 'Iris-versicolor', 'Iris-virginica']
data=[]
for line in f:
I = line.strip().split(',')
I[:4] = [float(i) for i in I[:4]]
I[4] = labels.index(I[4])
data.append(I)
f.close()
iris = np.array(data)
In [63]:
idx = np.arange(150)
idx
Out[63]:
In [64]:
idx2 = np.random.permutation(idx)
idx2
Out[64]:
In [65]:
iris[idx2] # 샘플을 분리해 낼 때 사용
Out[65]:
In [69]:
iris2 = iris[idx2]
iris_train = iris2[:100]
iris_test = iris2[100:]
iris_train.shape, iris_test.shape
Out[69]:
choice¶
- 주어진 데이터에서 임의로 뽑느다.
- (주의) 반복 선택이 가능하다.
In [70]:
a = np.arange(10)
a
Out[70]:
In [72]:
np.random.choice(a,100) #뽑을때마다 독립적
Out[72]:
In [73]:
np.random.choice([0,1],10)
Out[73]:
In [74]:
np.random.randint(2, size=10)
Out[74]:
seed()¶
- 동일한 실험 결과를 위해 랜덤 발생을 고정시킨다.
In [76]:
np.random.seed(2013)
a = np.random.randint(2,size=10)
b = np.random.randint(2,size=10)
display(a,b)
In [78]:
np.random.seed(2013) # 랜덤인데 위에 값 그대로 나옴
a = np.random.randint(2,size=10)
b = np.random.randint(2,size=10)
display(a,b)
'beginner > 파이썬 기초' 카테고리의 다른 글
NumPy_함수 (0) | 2019.02.13 |
---|---|
NumPy_사칙연산 (0) | 2019.02.13 |
NumPy_랜덤-1 (0) | 2019.02.12 |
NumPy_생성하기 (0) | 2019.02.12 |
함수와 모듈 (0) | 2019.02.11 |