1장 머신러닝의 준비

In [1]:
1/3
Out[1]:
0.3333333333333333
In [2]:
1+2+3
Out[2]:
6
In [3]:
a=1
b=7
a/b

# [shift + enter]:셀 실행 후 다음셀로
# [ctrl + enter]:셀 실행 후 현재 셀로

# 셀 바깥 쪽 클릭 시 파란박스 -> 명령모드
# 셀 안 쪽 클릿 시 초록박스 -> 편집모드

# 명령모드로 바꾼 뒤 [H]키를 누르면 각 모드에 대한 소개와 단축키 목록 표시
# 명령모드에서 [L]키를 누르면 셀에 행 번호 추가
# 명령모드에서 [A]나 [B]키를 누르면 선택 셀의 위 아래에 새로운 셀 추가
# 명령모드에서 [D, D]키를 누르면 선택 셀 삭제
Out[3]:
0.14285714285714285
In [4]:
a=1
b=2
a/b
a/0

# 행 번호 추가 시 디버깅 편리
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-4-872eb73cbe8c> in <module>
      2 b=2
      3 a/b
----> 4 a/0

ZeroDivisionError: division by zero

머신러닝을 시작합시다

우측 상단의 드롭다운 메뉴에서 Code -> Markdown 선택 시 메모작성모드로 변경

입력 후 [ctrl + enter]시 테두리가 사라지고 일반적인 문장으로 표시됨

In [7]:
import keras
keras.__version__
Out[7]:
'2.4.3'

2장 파이썬 기본

In [1]:
1+2
Out[1]:
3
In [2]:
(1+2*3-4)/5
Out[2]:
0.6
In [3]:
2**8
Out[3]:
256
In [4]:
x=1
y=1/3
x+y
Out[4]:
1.3333333333333333
In [5]:
Data_1=1/5
Data_2=3/5
Data_1+Data_2
Out[5]:
0.8
In [6]:
type(100)
Out[6]:
int
In [7]:
type(100.1)
Out[7]:
float
In [8]:
x=100
type(x)
Out[8]:
int
In [9]:
x=100.1
type(x)
Out[9]:
float
In [10]:
x='learning'
type(x)
Out[10]:
str
In [11]:
x=1/3
x
y=2/3
y
Out[11]:
0.6666666666666666
In [12]:
x=1/3
print(x)
y=2/3
print(y)
0.3333333333333333
0.6666666666666666
In [13]:
print('x= ' + str(x))
x= 0.3333333333333333
In [14]:
print('weight = {0} kg'.format(x))
weight = 0.3333333333333333 kg
In [16]:
x=1/3
y=1/7
z=1/4
print('weight: {0:.2f} kg, y={1:.2f} kg, z={2:.2f} kg'.format(x,y,z))
weight: 0.33 kg, y=0.14 kg, z=0.25 kg
In [18]:
x=[1,2,3,4,5]
print(x)
[1, 2, 3, 4, 5]
In [19]:
x[0]
Out[19]:
1
In [20]:
x[2]
Out[20]:
3
In [21]:
print(type(x))
print(type(x[0]))
<class 'list'>
<class 'int'>
In [22]:
s=['SUN',1,'MON',2]
print(type(s[0]))
print(type(s[1]))
<class 'str'>
<class 'int'>
In [25]:
a=[[1,2,3],[4,5,6]]
print(a[0][1])
2
In [26]:
x=[1,1,2,3,5]
x[3]=100
print(x)
[1, 1, 2, 100, 5]
In [27]:
x=[1,1,2,3,5]
len(x)
Out[27]:
5
In [28]:
y=range(5,10)
# 연속된 정수 데이터 (5, 6, 7, 8, 9)
# 요소 수정 불가

print(y[0],y[1],y[2],y[3],y[4])
5 6 7 8 9
In [29]:
print(y)
range(5, 10)
In [31]:
z=list(range(5,10))
# 수열

print(z)
[5, 6, 7, 8, 9]
In [32]:
list(range(10))
Out[32]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [33]:
a=(1,2,3)
# 튜플
# 요소 수정 불가

print(a)
(1, 2, 3)
In [34]:
a[1]
Out[34]:
2
In [35]:
type(a)
Out[35]:
tuple
In [36]:
a=(1)
# 튜플 x

type(a)
Out[36]:
int
In [37]:
a=(1,)
# 길이가 1인 튜플

type(a)
Out[37]:
tuple
In [40]:
x=11
if x>10:
    print('x is ')
    print('    larger than 10.')
else:
    print('x is smaller than 11')
x is 
    larger than 10.
In [42]:
x>10
Out[42]:
True
In [43]:
type(x>10)
Out[43]:
bool
In [44]:
x=15
if 10<=x and x<=20:
    print('x is between 10 and 20.')
x is between 10 and 20.
In [45]:
for i in [1,2,3]:
    print(i)
1
2
3
In [46]:
num=[2,4,6,8,10]
for i in range(len(num)):
    num[i]=num[i]*2
print(num)
[4, 8, 12, 16, 20]
In [47]:
num=[2,4,6,8,10]
for i,n in enumerate(num):
    num[i]=n*2
# enumerate : i(배열의 인덱스), n(배열[i]의 값)    

print(num)
[4, 8, 12, 16, 20]
In [48]:
[1,2]+[3,4]
Out[48]:
[1, 2, 3, 4]
In [49]:
import numpy as np
In [51]:
x=np.array([1,2,3])
# 벡터(1차원 배열) 정의

x
Out[51]:
array([1, 2, 3])
In [52]:
print(x)
[1 2 3]
In [53]:
y=np.array([4,5,6])
print(x+y)
#벡터 연산
[5 7 9]
In [54]:
type(x)
Out[54]:
numpy.ndarray
In [55]:
x[0]
Out[55]:
1
In [56]:
x[0]=100
print(x)
[100   2   3]
In [57]:
print(np.arange(10))
# list(range(10))를 벡터로
[0 1 2 3 4 5 6 7 8 9]
In [58]:
print(np.arange(5,10))
[5 6 7 8 9]
In [59]:
a=np.array([1,1])
b=a
# b에 a가 저장된 곳의 참조 주소가 전달

print('a=' + str(a))
print('b=' + str(b))
b[0]=100
# 변경사항 a에도 반영

print('b=' + str(b))
print('a=' + str(a))
a=[1 1]
b=[1 1]
b=[100   1]
a=[100   1]
In [60]:
a=np.array([1,1])
b=a.copy()
# b는 a와 관계 없이 독립된 변수로 취급

print('a=' + str(a))
print('b=' + str(b))
b[0]=100
# 변경사항 a에 반영x

print('b=' + str(b))
print('a=' + str(a))
a=[1 1]
b=[1 1]
b=[100   1]
a=[1 1]
In [61]:
x=np.array([[1,2,3],[4,5,6]])
# 2차원 배열로 행렬 정의

print(x)
[[1 2 3]
 [4 5 6]]
In [62]:
x=np.array([[1,2,3],[4,5,6]])
x.shape
# 행렬 크기
Out[62]:
(2, 3)
In [64]:
w,h=x.shape
print(w)
print(h)
2
3
In [65]:
x=np.array([[1,2,3],[4,5,6]])
x[1,2]
Out[65]:
6
In [66]:
x=np.array([[1,2,3],[4,5,6]])
x[1,2]=100
print(x)
[[  1   2   3]
 [  4   5 100]]
In [67]:
print(np.zeros(10))
# 모든 요소가 0인 길이가 10인 벡터
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
In [70]:
print(np.zeros((2,10)))
# 모든 요소가 0인 2x10인 행렬
[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]
In [71]:
print(np.ones((2,10)))
# 모든 요소가 1인 2x10인 행렬
[[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]
 [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]]
In [72]:
np.random.rand(2,3)
# 2x3의 난수 행렬
Out[72]:
array([[0.79571268, 0.24842823, 0.63773972],
       [0.19132665, 0.06214691, 0.81972296]])
In [73]:
a=np.arange(10)
print(a)
[0 1 2 3 4 5 6 7 8 9]
In [74]:
a.reshape(2,5)
# 행렬 사이즈 변경
Out[74]:
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])
In [75]:
x=np.array([[4,4,4],[8,8,8]])
y=np.array([[1,1,1],[2,2,2]])
print(x+y)
[[ 5  5  5]
 [10 10 10]]
In [76]:
x=np.array([[4,4,4],[8,8,8]])
print(10*x)
# 행렬의 스칼라 곱
[[40 40 40]
 [80 80 80]]
In [77]:
x=np.array([[4,4,4],[8,8,8]])
print(np.exp(x))
# exp(x) : 지수함수
[[  54.59815003   54.59815003   54.59815003]
 [2980.95798704 2980.95798704 2980.95798704]]
In [78]:
v=np.array([[1,2,3],[4,5,6]])
w=np.array([[1,1],[2,2],[3,3]])
print(v.dot(w))
# 행렬 곱의 계산(내적)
[[14 14]
 [32 32]]
In [79]:
x=np.arange(10)
print(x)
print(x[:5])
[0 1 2 3 4 5 6 7 8 9]
[0 1 2 3 4]
In [81]:
print(x[5:])
[5 6 7 8 9]
In [82]:
print(x[3:8])
# 3, 4, 5, 6, 7
[3 4 5 6 7]
In [83]:
print(x[3:8:2])
[3 5 7]
In [84]:
print(x[::-1])
# 배열 순서 거꾸로
[9 8 7 6 5 4 3 2 1 0]
In [86]:
y=np.array([[1,2,3],[4,5,6],[7,8,9]])
print(y)
print(y[:2,1:2])
# [행 슬라이싱, 열 슬라이싱]
[[1 2 3]
 [4 5 6]
 [7 8 9]]
[[2]
 [5]]
In [87]:
x=np.array([1,1,2,3,5,8,13])
x>3
Out[87]:
array([False, False, False, False,  True,  True,  True])
In [88]:
x[x>3]
Out[88]:
array([ 5,  8, 13])
In [89]:
x[x>3]=999
print(x)
[  1   1   2   3 999 999 999]
In [90]:
help(np.random.randint)

# help(함수명) : 함수의 설명 확인
Help on built-in function randint:

randint(...) method of numpy.random.mtrand.RandomState instance
    randint(low, high=None, size=None, dtype='l')
    
    Return random integers from `low` (inclusive) to `high` (exclusive).
    
    Return random integers from the "discrete uniform" distribution of
    the specified dtype in the "half-open" interval [`low`, `high`). If
    `high` is None (the default), then results are from [0, `low`).
    
    Parameters
    ----------
    low : int or array-like of ints
        Lowest (signed) integers to be drawn from the distribution (unless
        ``high=None``, in which case this parameter is one above the
        *highest* such integer).
    high : int or array-like of ints, optional
        If provided, one above the largest (signed) integer to be drawn
        from the distribution (see above for behavior if ``high=None``).
        If array-like, must contain integer values
    size : int or tuple of ints, optional
        Output shape.  If the given shape is, e.g., ``(m, n, k)``, then
        ``m * n * k`` samples are drawn.  Default is None, in which case a
        single value is returned.
    dtype : dtype, optional
        Desired dtype of the result. All dtypes are determined by their
        name, i.e., 'int64', 'int', etc, so byteorder is not available
        and a specific precision may have different C types depending
        on the platform. The default value is 'np.int'.
    
        .. versionadded:: 1.11.0
    
    Returns
    -------
    out : int or ndarray of ints
        `size`-shaped array of random integers from the appropriate
        distribution, or a single such random int if `size` not provided.
    
    See Also
    --------
    random.random_integers : similar to `randint`, only for the closed
        interval [`low`, `high`], and 1 is the lowest value if `high` is
        omitted.
    
    Examples
    --------
    >>> np.random.randint(2, size=10)
    array([1, 0, 0, 0, 1, 1, 0, 0, 1, 0]) # random
    >>> np.random.randint(1, size=10)
    array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
    
    Generate a 2 x 4 array of ints between 0 and 4, inclusive:
    
    >>> np.random.randint(5, size=(2, 4))
    array([[4, 0, 2, 1], # random
           [3, 2, 2, 0]])
    
    Generate a 1 x 3 array with 3 different upper bounds
    
    >>> np.random.randint(1, [3, 5, 10])
    array([2, 2, 9]) # random
    
    Generate a 1 by 3 array with 3 different lower bounds
    
    >>> np.random.randint([1, 5, 7], 10)
    array([9, 8, 7]) # random
    
    Generate a 2 by 4 array using broadcasting with dtype of uint8
    
    >>> np.random.randint([1, 3, 5, 7], [[10], [20]], dtype=np.uint8)
    array([[ 8,  6,  9,  7], # random
           [ 1, 16,  9, 12]], dtype=uint8)

In [91]:
def my_func1():
    print('Hi!')
my_func1()
Hi!
In [92]:
def my_func2(a,b):
    c=a+b
    return c
my_func2(1,2)
Out[92]:
3
In [93]:
def my_func3(D):
    m=np.mean(D)
    # D의 평균
    
    s=np.std(D)
    #D의 표준편차
    
    return m,s

# D : 인수
# m,s : 반환값
In [96]:
data=np.random.randn(100)
data_mean,data_std=my_func3(data)
print('mean:{0:3.2f}, std:{1:3.2f}'.format(data_mean, data_std))
mean:-0.05, std:0.94
In [98]:
output=my_func3(data)
# 반환 값이 여러 개라도 하나의 변수로 받을 수 있음
# 이 경우 반환 값은 튜플형

print(output)
print(type(output))
print('mean:{0:3.2f}, std:{1:3.2f}'.format(output[0], output[1]))
(-0.04843133584984466, 0.9398183277521265)
<class 'tuple'>
mean:-0.05, std:0.94
In [99]:
data=np.random.randn(5)
print(data)
np.save('datafile.npy',data)
# ndarray형을 파일에 저장

data=[]
print(data)
data=np.load('datafile.npy')
# ndarray형을 파일에서 로드

print(data)
[-1.18372302 -0.14197173 -0.10104674 -0.10805159 -1.13138617]
[]
[-1.18372302 -0.14197173 -0.10104674 -0.10805159 -1.13138617]
In [102]:
data1=np.array([1,2,3])
data2=np.array([10,20,30])
np.savez('datafile2.npz', data1=data1, data2=data2)
# 여러 ndarray형을 파일에 저장

data1=[]
data2=[]
outfile=np.load('datafile2.npz')
# 여러 ndarray형을 파일에서 로드

print(outfile.files)
# 저장된 변수 목록 확인

data1=outfile['data1']
data2=outfile['data2']
print(data1)
print(data2)
['data1', 'data2']
[1 2 3]
[10 20 30]

3장 그래프 그리기

In [103]:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# 주피터 노트북에서 그래프 표시

np.random.seed(1)
# 난수 고정

x=np.arange(10)
y=np.random.rand(10)

# <그래프 표시>
plt.plot(x,y) # 꺾은선 그래프를 등록
plt.show() # 그래프 그리기
In [104]:
%reset
# 지금까지의 이력을 모두 메모리에서 삭제
Once deleted, variables cannot be recovered. Proceed (y/[n])? y
In [105]:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

def f(x):
    return (x-2)*x*(x+2)
In [106]:
print(f(1))
-3
In [107]:
print(f(np.array([1,2,3])))
# ndarray 배열을 함수의 인수로 받을 수 있음
[-3  0 15]
In [108]:
x=np.arange(-3,3.5,0.5)
# 그래프를 그리는 범위를 설정

print(x)
[-3.  -2.5 -2.  -1.5 -1.  -0.5  0.   0.5  1.   1.5  2.   2.5  3. ]
In [110]:
plt.plot(x, f(x))
plt.show()
In [112]:
def f2(x,w):
    return (x-w)*x*(x+2)

x=np.linspace(-3,3,100)
# x 정의(-3 ~ 3 을 100 분할)

# <차트 묘사>
plt.plot(x,f2(x,2),color='black',label='$w=2$') # 검정색
plt.plot(x,f2(x,1),color='cornflowerblue',
        label='$w=1$') # 파란색
plt.legend(loc="upper left") # 범례 표시 (upper/lower right/left)
plt.ylim(-15,15) # y축 범위
plt.title('$f_2(x)$') # 제목
plt.xlabel('$x$') # x 라벨
plt.ylabel('$y$') # y 라벨
plt.grid(True) # 그리드
plt.show()
In [113]:
import matplotlib
matplotlib.colors.cnames

# 사용할 수 있는 색상 목록 확인
Out[113]:
{'aliceblue': '#F0F8FF',
 'antiquewhite': '#FAEBD7',
 'aqua': '#00FFFF',
 'aquamarine': '#7FFFD4',
 'azure': '#F0FFFF',
 'beige': '#F5F5DC',
 'bisque': '#FFE4C4',
 'black': '#000000',
 'blanchedalmond': '#FFEBCD',
 'blue': '#0000FF',
 'blueviolet': '#8A2BE2',
 'brown': '#A52A2A',
 'burlywood': '#DEB887',
 'cadetblue': '#5F9EA0',
 'chartreuse': '#7FFF00',
 'chocolate': '#D2691E',
 'coral': '#FF7F50',
 'cornflowerblue': '#6495ED',
 'cornsilk': '#FFF8DC',
 'crimson': '#DC143C',
 'cyan': '#00FFFF',
 'darkblue': '#00008B',
 'darkcyan': '#008B8B',
 'darkgoldenrod': '#B8860B',
 'darkgray': '#A9A9A9',
 'darkgreen': '#006400',
 'darkgrey': '#A9A9A9',
 'darkkhaki': '#BDB76B',
 'darkmagenta': '#8B008B',
 'darkolivegreen': '#556B2F',
 'darkorange': '#FF8C00',
 'darkorchid': '#9932CC',
 'darkred': '#8B0000',
 'darksalmon': '#E9967A',
 'darkseagreen': '#8FBC8F',
 'darkslateblue': '#483D8B',
 'darkslategray': '#2F4F4F',
 'darkslategrey': '#2F4F4F',
 'darkturquoise': '#00CED1',
 'darkviolet': '#9400D3',
 'deeppink': '#FF1493',
 'deepskyblue': '#00BFFF',
 'dimgray': '#696969',
 'dimgrey': '#696969',
 'dodgerblue': '#1E90FF',
 'firebrick': '#B22222',
 'floralwhite': '#FFFAF0',
 'forestgreen': '#228B22',
 'fuchsia': '#FF00FF',
 'gainsboro': '#DCDCDC',
 'ghostwhite': '#F8F8FF',
 'gold': '#FFD700',
 'goldenrod': '#DAA520',
 'gray': '#808080',
 'green': '#008000',
 'greenyellow': '#ADFF2F',
 'grey': '#808080',
 'honeydew': '#F0FFF0',
 'hotpink': '#FF69B4',
 'indianred': '#CD5C5C',
 'indigo': '#4B0082',
 'ivory': '#FFFFF0',
 'khaki': '#F0E68C',
 'lavender': '#E6E6FA',
 'lavenderblush': '#FFF0F5',
 'lawngreen': '#7CFC00',
 'lemonchiffon': '#FFFACD',
 'lightblue': '#ADD8E6',
 'lightcoral': '#F08080',
 'lightcyan': '#E0FFFF',
 'lightgoldenrodyellow': '#FAFAD2',
 'lightgray': '#D3D3D3',
 'lightgreen': '#90EE90',
 'lightgrey': '#D3D3D3',
 'lightpink': '#FFB6C1',
 'lightsalmon': '#FFA07A',
 'lightseagreen': '#20B2AA',
 'lightskyblue': '#87CEFA',
 'lightslategray': '#778899',
 'lightslategrey': '#778899',
 'lightsteelblue': '#B0C4DE',
 'lightyellow': '#FFFFE0',
 'lime': '#00FF00',
 'limegreen': '#32CD32',
 'linen': '#FAF0E6',
 'magenta': '#FF00FF',
 'maroon': '#800000',
 'mediumaquamarine': '#66CDAA',
 'mediumblue': '#0000CD',
 'mediumorchid': '#BA55D3',
 'mediumpurple': '#9370DB',
 'mediumseagreen': '#3CB371',
 'mediumslateblue': '#7B68EE',
 'mediumspringgreen': '#00FA9A',
 'mediumturquoise': '#48D1CC',
 'mediumvioletred': '#C71585',
 'midnightblue': '#191970',
 'mintcream': '#F5FFFA',
 'mistyrose': '#FFE4E1',
 'moccasin': '#FFE4B5',
 'navajowhite': '#FFDEAD',
 'navy': '#000080',
 'oldlace': '#FDF5E6',
 'olive': '#808000',
 'olivedrab': '#6B8E23',
 'orange': '#FFA500',
 'orangered': '#FF4500',
 'orchid': '#DA70D6',
 'palegoldenrod': '#EEE8AA',
 'palegreen': '#98FB98',
 'paleturquoise': '#AFEEEE',
 'palevioletred': '#DB7093',
 'papayawhip': '#FFEFD5',
 'peachpuff': '#FFDAB9',
 'peru': '#CD853F',
 'pink': '#FFC0CB',
 'plum': '#DDA0DD',
 'powderblue': '#B0E0E6',
 'purple': '#800080',
 'rebeccapurple': '#663399',
 'red': '#FF0000',
 'rosybrown': '#BC8F8F',
 'royalblue': '#4169E1',
 'saddlebrown': '#8B4513',
 'salmon': '#FA8072',
 'sandybrown': '#F4A460',
 'seagreen': '#2E8B57',
 'seashell': '#FFF5EE',
 'sienna': '#A0522D',
 'silver': '#C0C0C0',
 'skyblue': '#87CEEB',
 'slateblue': '#6A5ACD',
 'slategray': '#708090',
 'slategrey': '#708090',
 'snow': '#FFFAFA',
 'springgreen': '#00FF7F',
 'steelblue': '#4682B4',
 'tan': '#D2B48C',
 'teal': '#008080',
 'thistle': '#D8BFD8',
 'tomato': '#FF6347',
 'turquoise': '#40E0D0',
 'violet': '#EE82EE',
 'wheat': '#F5DEB3',
 'white': '#FFFFFF',
 'whitesmoke': '#F5F5F5',
 'yellow': '#FFFF00',
 'yellowgreen': '#9ACD32'}
In [115]:
plt.figure(figsize=(10,3)) # 전체 영역의 크기 지정
plt.subplots_adjust(wspace=0.5,hspace=0.5) # 그래프의 간격 지정
# 여러 그래프를 나란히 표시

for i in range(6):
    plt.subplot(2,3,i+1) #그래프 묘사 위치 지정
    plt.ylim(-20,20)
    plt.title(i+1)
    plt.plot(x,f2(x,i),'k')
    plt.grid(True)
plt.show()
In [118]:
import numpy as np
import matplotlib.pyplot as plt

def f3(x0,x1):
    r=2*x0**2+x1**2
    ans=r*np.exp(-r)
    return ans
# 이변수 함수

xn=9
x0=np.linspace(-2,2,xn)
x1=np.linspace(-2,2,xn)
y=np.zeros((len(x0),len(x1)))
for i0 in range(xn):
    for i1 in range(xn):
        y[i1,i0]=f3(x0[i0],x1[i1])
In [119]:
print(x0)
[-2.  -1.5 -1.  -0.5  0.   0.5  1.   1.5  2. ]
In [120]:
print(np.round(y,1))
# 소수점 1자리로 반올림
[[0.  0.  0.  0.  0.1 0.  0.  0.  0. ]
 [0.  0.  0.1 0.2 0.2 0.2 0.1 0.  0. ]
 [0.  0.  0.1 0.3 0.4 0.3 0.1 0.  0. ]
 [0.  0.  0.2 0.4 0.2 0.4 0.2 0.  0. ]
 [0.  0.  0.3 0.3 0.  0.3 0.3 0.  0. ]
 [0.  0.  0.2 0.4 0.2 0.4 0.2 0.  0. ]
 [0.  0.  0.1 0.3 0.4 0.3 0.1 0.  0. ]
 [0.  0.  0.1 0.2 0.2 0.2 0.1 0.  0. ]
 [0.  0.  0.  0.  0.1 0.  0.  0.  0. ]]
In [121]:
plt.figure(figsize=(3.5,3))
plt.gray() # 색상 회색 음영으로 표현
plt.pcolor(y)
# 행렬을 색상으로 표현

plt.colorbar() # 행렬 옆에 컬러 바를 나타냄
plt.show()
In [122]:
from mpl_toolkits.mplot3d import Axes3D
# 3차원 표현

xx0,xx1=np.meshgrid(x0,x1)
# x0,x1 -> xx0,xx1 2차원 배열이 됨 (9x9)

plt.figure(figsize=(5,3.5))
ax=plt.subplot(1,1,1,projection='3d') # 3차원 차트
ax.plot_surface(xx0,xx1,y,rstride=1,cstride=1,alpha=0.3,
               color='blue',edgecolor='black')
# rstride, cstride : 가로세로 선 긋는 개수 지정
# alpha : 면의 투명도 지정

ax.set_zticks((0,0.2)) # z축 눈금 제한
ax.view_init(75,-95) # 3차원 그래프의 방향 조절 (상하회전각도, 좌우회전각도)
plt.show()
In [123]:
print(x0)
print(x1)
[-2.  -1.5 -1.  -0.5  0.   0.5  1.   1.5  2. ]
[-2.  -1.5 -1.  -0.5  0.   0.5  1.   1.5  2. ]
In [124]:
print(xx0)
[[-2.  -1.5 -1.  -0.5  0.   0.5  1.   1.5  2. ]
 [-2.  -1.5 -1.  -0.5  0.   0.5  1.   1.5  2. ]
 [-2.  -1.5 -1.  -0.5  0.   0.5  1.   1.5  2. ]
 [-2.  -1.5 -1.  -0.5  0.   0.5  1.   1.5  2. ]
 [-2.  -1.5 -1.  -0.5  0.   0.5  1.   1.5  2. ]
 [-2.  -1.5 -1.  -0.5  0.   0.5  1.   1.5  2. ]
 [-2.  -1.5 -1.  -0.5  0.   0.5  1.   1.5  2. ]
 [-2.  -1.5 -1.  -0.5  0.   0.5  1.   1.5  2. ]
 [-2.  -1.5 -1.  -0.5  0.   0.5  1.   1.5  2. ]]
In [125]:
print(xx1)
[[-2.  -2.  -2.  -2.  -2.  -2.  -2.  -2.  -2. ]
 [-1.5 -1.5 -1.5 -1.5 -1.5 -1.5 -1.5 -1.5 -1.5]
 [-1.  -1.  -1.  -1.  -1.  -1.  -1.  -1.  -1. ]
 [-0.5 -0.5 -0.5 -0.5 -0.5 -0.5 -0.5 -0.5 -0.5]
 [ 0.   0.   0.   0.   0.   0.   0.   0.   0. ]
 [ 0.5  0.5  0.5  0.5  0.5  0.5  0.5  0.5  0.5]
 [ 1.   1.   1.   1.   1.   1.   1.   1.   1. ]
 [ 1.5  1.5  1.5  1.5  1.5  1.5  1.5  1.5  1.5]
 [ 2.   2.   2.   2.   2.   2.   2.   2.   2. ]]
In [127]:
xn=50
x0=np.linspace(-2,2,xn)
x1=np.linspace(-2,2,xn)

y=np.zeros((len(x0),len(x1)))
for i0 in range(xn):
    for i1 in range(xn):
        y[i1,i0]=f3(x0[i0],x1[i1])
        
xx0,xx1=np.meshgrid(x0,x1) # (50x50)

plt.figure(1,figsize=(4,4))
cont=plt.contour(xx0,xx1,y,5,colors='black') # 등고선 표시 높이 5단계로 지시
# 등고선으로 표시

cont.clabel(fmt='%3.2f',fontsize=8) # 각 등고선에 숫자 삽입 (fmt : 숫자 형식)
plt.xlabel('$x_0$',fontsize=14)
plt.ylabel('$x_1$',fontsize=14)
plt.show()
In [ ]: