15
Programming 1 - Python 1 Python이용한 기초 통계분석 1. 통계학을 위한 Python 모듈 1.1 numpy 패키지 - 고급 데이터분석과 수리 계산을 위한 라이브러리를 제공 - 아나콘다에 기본적으로 설치되어 있음 (1) numpy제공하는 통계분석 함수 import numpy as np print(dir(np)) …, 'max', …, 'mean', 'median', …, 'min', …, 'percentile', …, 'std', …, 'var', … (2) numpy이용한 외부 데이터 불러오기 - 예제 데이터: cars – Speed and Stopping Distances of Cars (M. Ezekiel), 변수 – speed, dist cars 데이터 speed dist 4 4 7 24 24 25 2 10 4 93 120 85 # 외부 데이터 불러오기 파일 import numpy as np data_file_name='e:/data/python/cars.txt' dat=np.genfromtxt(data_file_name,dtype='float32',skip_header=True) # skip_header=True 또는 skip_header=1 데이터의 첫번째 행이 변수명일 경우 지정 print(np.shape(dat)) # np.shape(dat) 데이터 객체의 행과 열을 나타냄 speed=dat[:,1]

Programming 1 - Pythondelab.cju.ac.kr/python_s1.pdf · Programming 1 - Python . 1 Python. 을 이용한 기초 통계분석 1. 통계학을. 위한. Python . 모듈. 1.1 numpy . 패키지

  • Upload
    others

  • View
    7

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Programming 1 - Pythondelab.cju.ac.kr/python_s1.pdf · Programming 1 - Python . 1 Python. 을 이용한 기초 통계분석 1. 통계학을. 위한. Python . 모듈. 1.1 numpy . 패키지

Programming 1 - Python

1

Python을 이용한 기초 통계분석

1. 통계학을 위한 Python 모듈

1.1 numpy 패키지

- 고급 데이터분석과 수리 계산을 위한 라이브러리를 제공

- 아나콘다에 기본적으로 설치되어 있음

(1) numpy가 제공하는 통계분석 함수

import numpy as np

print(dir(np))

…, 'max', …, 'mean', 'median', …, 'min', …, 'percentile', …, 'std', …, 'var', …

(2) numpy를 이용한 외부 데이터 불러오기

- 예제 데이터: cars – Speed and Stopping Distances of Cars (M. Ezekiel), 변수 – speed, dist

cars 데이터

speed dist 4 4 7 ⋮

24 24 25

2 10 4 ⋮

93 120 85

# 외부 데이터 불러오기 – 파일

import numpy as np

data_file_name='e:/data/python/cars.txt'

dat=np.genfromtxt(data_file_name,dtype='float32',skip_header=True)

# skip_header=True 또는 skip_header=1 → 데이터의 첫번째 행이 변수명일 경우 지정

print(np.shape(dat))

# np.shape(dat) → 데이터 객체의 행과 열을 나타냄

speed=dat[:,1]

Page 2: Programming 1 - Pythondelab.cju.ac.kr/python_s1.pdf · Programming 1 - Python . 1 Python. 을 이용한 기초 통계분석 1. 통계학을. 위한. Python . 모듈. 1.1 numpy . 패키지

Programming 1 - Python

2

dist=dat[:,2]

# 기초 통계량 구하기

len(speed) # 데이터의 개수

np.mean(speed) # 평균

np.var(speed) # 분산

np.std(speed) # 표준 편차

np.max(speed) # 최대값

np.min(speed) # 최소값

np.median(speed) # 중앙값

np.percentile(speed, 25) # 1사분위 수

np.percentile(speed, 50) # 2사분위 수 = 중앙값

np.percentile(speed, 75) # 3사분위 수

np.percentile(speed, 42) # 42백분위수 (42%)

(3) 난수 생성 – 정규분포

import numpy as np

r_norm_data=[]

r_norm_data =np.random.normal(2,3,4)

# np.random.normal(loc=0.0, scale=1.0, size=None)

# loc: 평균, scale: 표준편차, size: 개수

print(r_norm_data)

(4) 실습 예제

X~B(10,0.7)인 이항 분포(binomial distribution)를 따르는 난수 10개를 생성 하는 Python 프로그램

을 작성하시오.

Page 3: Programming 1 - Pythondelab.cju.ac.kr/python_s1.pdf · Programming 1 - Python . 1 Python. 을 이용한 기초 통계분석 1. 통계학을. 위한. Python . 모듈. 1.1 numpy . 패키지

Programming 1 - Python

3

1.2 matplotlib 패키지

- Python의 시각화 패키지

- line plot, scatter plot, contour plot, surface plot, bar chart, histogram, box plot, …

- matplotlib.pyplot 모듈: matplotlib를 사용할 수 있는 함수들의 모음

(1) 히스토그램과 산점도

import numpy as np

import matplotlib.pyplot as plt

data_file_name='e:/data/python/cars.txt'

dat=np.genfromtxt(data_file_name,dtype='float32',skip_header=True)

speed=dat[:,1]

dist=dat[:,2]

plt.hist(speed)

plt.show()

plt.plot(speed,dist)

plt.show()

Page 4: Programming 1 - Pythondelab.cju.ac.kr/python_s1.pdf · Programming 1 - Python . 1 Python. 을 이용한 기초 통계분석 1. 통계학을. 위한. Python . 모듈. 1.1 numpy . 패키지

Programming 1 - Python

4

plt.plot(speed, dist, c="r", lw=3, ls="-", marker="d", ms=10, mec="b", mew=3, mfc="w")

plt.show()

- plot arguments

c: 선 색깔 (blue b, green g, red r, cyan c, magenta m, yellow y, black k, white w, …)

ls: 선 형태 (- solid line style, -- dashed line style, -. dash-dot line style, …_

marker: 데이터의 위치를 나타내는 점(마커)의 형태 (. point marker / , pixel marker / o circle marker / v triangle_down marker / ^ triangle_up marker / < triangle_left marker / > triangle_right marker / 1 tri_down marker / 2 tri_up marker / 3 tri_left marker / 4 tri_right marker / s square marker / p pentagon marker / * star marker / h hexagon1 marker / H hexagon2 marker / + plus marker / x x marker / D diamond marker / d thin_diamond marker, …

lw: 선 굵기

ms: markersize, 마커 크기

mec: markeredgecolor, 마커 선 색깔

mew: markeredgewidth, 마커 선 굵기

mfc: markerfacecolor, 마커 내부 색깔

(2) 표준정규분포를 따르는 난수 생성 후 히스토그램 그리기

import numpy as np

import matplotlib.pyplot as plt

mu=0

sigma = 1

# mean=0, standard deviation=1 , 표준정규분포

s = np.random.normal(mu, sigma, 1000)

plt.hist(s)

Page 5: Programming 1 - Pythondelab.cju.ac.kr/python_s1.pdf · Programming 1 - Python . 1 Python. 을 이용한 기초 통계분석 1. 통계학을. 위한. Python . 모듈. 1.1 numpy . 패키지

Programming 1 - Python

5

plt.show()

plt.hist(s, 30)

plt.show()

plt.hist(s, 30, normed=True)

plt.show()

- 데이터 정규화 (Normalization)

[0,1]

𝑥𝑥 − min (𝑥𝑥)max(𝑥𝑥) − min (𝑥𝑥)

(3) 실습 예제 – Iris 데이터

- Sepal.Length에 대한 히스토그램을 출력하는 프로그램을 작성하시오. (계급의 크기는 5개, 막대의

색깔은 검은색으로 하시오.)

Page 6: Programming 1 - Pythondelab.cju.ac.kr/python_s1.pdf · Programming 1 - Python . 1 Python. 을 이용한 기초 통계분석 1. 통계학을. 위한. Python . 모듈. 1.1 numpy . 패키지

Programming 1 - Python

6

- Sepal.Length와 Patal.Length 간의 산점도를 출력하는 프로그램을 작성하시오. (각 점은 연결되지

않게 하고 X축과 Y축의 제목을 각각 변수 명으로 출력되게 하시오.)

1.3 pandas 패키지

- 데이터분석을 제공하는 라이브러리

- csv 파일 등을 데이터로 읽고 원하는 데이터 형식으로 변환

(1) 웹 상의 데이터 불러오기

import pandas as pd

target_url = ("http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data")

# iris data를 pandas data frame 형식으로 불러옴

iris_data = pd.read_csv(target_url,header=None, prefix="X")

print(iris_data)

print(iris_data.X4)

summary = iris_data.describe()

print(summary)

Sepal_Length = list(iris_data.X0)

print(Sepal_Length)

(2) 데이터프레임

- 데이터프레임(DataFrame): pandas 에서 사용되는 기본 데이터

- 데이터프레임을 정의할 때는 2 차원 리스트를 매개변수로 전달

import pandas as pd

a = pd.DataFrame([

[10,20,30],

[40,50,60],

[70,80,90]

])

print(a)

Page 7: Programming 1 - Pythondelab.cju.ac.kr/python_s1.pdf · Programming 1 - Python . 1 Python. 을 이용한 기초 통계분석 1. 통계학을. 위한. Python . 모듈. 1.1 numpy . 패키지

Programming 1 - Python

7

# 1 차원 데이터는 Series 를 사용

import pandas as pd

import numpy as np

s = pd.Series([1.0, 3.0, 5.0, 7.0, 9.0])

print(s) # 자료형도 함께 출력됨

m = np.mean(s)

print(m)

(3) 원하는 데이터 추출

# 1 차원 리스트의 딕셔너리 자료형으로부터 키를 이용하여 원하는 열의 데이터 출력

import pandas as pd

# 키, 몸무게, 유형 데이터프레임 생성하기

tbl = pd.DataFrame({

"weight": [80.0, 70.4, 65.5, 45.9, 51.2],

"height": [170, 180, 155, 143, 154],

"type": [ "f", "n", "n", "t", "t"]

})

# 몸무게 목록 추출하기

print("몸무게 목록")

print(tbl["weight"])

# 몸무게와 키 목록 추출하기

Page 8: Programming 1 - Pythondelab.cju.ac.kr/python_s1.pdf · Programming 1 - Python . 1 Python. 을 이용한 기초 통계분석 1. 통계학을. 위한. Python . 모듈. 1.1 numpy . 패키지

Programming 1 - Python

8

print("몸무게와 키 목록")

print(tbl[["weight","height"]])

# 원하는 위치의 값을 추출할 때는 파이썬 리스트처럼 슬라이스를 사용

import pandas as pd

tbl = pd.DataFrame({

"weight": [80.0, 70.4, 65.5, 45.9, 51.2],

"height": [170, 180, 155, 143, 154],

"type": [ "f", "n", "n", "t", "t"]

})

print("tbl[2:4]\n", tbl[2:4])

print("tbl[3:]\n", tbl[3:])

# 원하는 조건 추출

import pandas as pd

tbl = pd.DataFrame({

"weight": [80.0, 70.4, 65.5, 45.9, 51.2, 72.5],

"height": [170, 180, 155, 143, 154, 160],

Page 9: Programming 1 - Pythondelab.cju.ac.kr/python_s1.pdf · Programming 1 - Python . 1 Python. 을 이용한 기초 통계분석 1. 통계학을. 위한. Python . 모듈. 1.1 numpy . 패키지

Programming 1 - Python

9

"gender": [ "f", "m", "m", "f", "f","m"]

})

print("몸무게와 키 목록")

print(tbl[["weight","height"]])

print("--- height 가 160 이상인 것")

print(tbl[tbl.height >= 160])

print("--- gender 가 m 인 것")

print(tbl[tbl.gender == "m"])

# 정렬

import pandas as pd

tbl = pd.DataFrame({

"weight": [80.0, 70.4, 65.5, 45.9, 51.2, 72.5],

"height": [170, 180, 155, 143, 154, 160],

"gender": ["f", "m", "m", "f", "f", "m"]

})

print("--- 키로 정렬")

print(tbl.sort_values(by="height"))

print("--- 몸무게로 정렬")

print(tbl.sort_values(by="weight", ascending=False))

Page 10: Programming 1 - Pythondelab.cju.ac.kr/python_s1.pdf · Programming 1 - Python . 1 Python. 을 이용한 기초 통계분석 1. 통계학을. 위한. Python . 모듈. 1.1 numpy . 패키지

Programming 1 - Python

10

# 전치

import pandas as pd

tbl = pd.DataFrame([

["A", "B", "C"],

["D", "E", "F"],

["G", "H", "I"]

])

print(tbl)

print("------")

print(tbl.T)

(4) 데이터 조작

import numpy as np

Page 11: Programming 1 - Pythondelab.cju.ac.kr/python_s1.pdf · Programming 1 - Python . 1 Python. 을 이용한 기초 통계분석 1. 통계학을. 위한. Python . 모듈. 1.1 numpy . 패키지

Programming 1 - Python

11

# 10 개의 float32 자료형 데이터 생성

v = np.zeros(10, dtype=np.float32)

print(v)

# 연속된 10 개의 uint64 자료형 데이터 생성

v = np.arange(10, dtype=np.uint64)

print(v)

# v 값을 3 배하기

v *= 3

print(v)

# v 의 평균 구하기

print(v.mean())

# 데이터 정규화

import pandas as pd

# 키, 체중, 유형 데이터프레임 생성하기

tbl = pd.DataFrame({

"weight": [80.0, 70.4, 65.5, 45.9, 51.2, 72.5],

"height": [170, 180, 155, 143, 154, 160],

"gender": ["f", "m", "m", "f", "f", "m"]

})

# 키와 몸무게 정규화하기

# 최댓값과 최솟값 구하기

def norm(tbl, key):

c = tbl[key]

v_max = c.max()

v_min = c.min()

print(key, "=", v_min, "-", v_max)

Page 12: Programming 1 - Pythondelab.cju.ac.kr/python_s1.pdf · Programming 1 - Python . 1 Python. 을 이용한 기초 통계분석 1. 통계학을. 위한. Python . 모듈. 1.1 numpy . 패키지

Programming 1 - Python

12

tbl[key] = (c - v_min) / (v_max - v_min)

norm(tbl, "weight")

norm(tbl, "height")

print(tbl)

(5) numpy 로 변환

머신러닝 라이브러리 중에서 pandas 의 데이터프레임을 지원하지 않는 경우 numpy 형식으로

변환하여 사용하면 됨

(6) 실습 예제

- Japan credit 데이터를 pandas 데이터 프레임으로 불러와서 각 열(변수)에 대한 평균과

표준편차를 구하시오.

Page 13: Programming 1 - Pythondelab.cju.ac.kr/python_s1.pdf · Programming 1 - Python . 1 Python. 을 이용한 기초 통계분석 1. 통계학을. 위한. Python . 모듈. 1.1 numpy . 패키지

Programming 1 - Python

13

- Japan credit 데이터를 pandas 데이터 프레임으로 불러와서 각 열(변수)에 대한 정규화 및

표준화를 수행 하시오. (마지막 열은 제외)

1.4 추가적인 패키지들

(1) sklearn

- scikit-learn

- 다양한 데이터 셋 포함

- 데이터 전처리, 지도/자율 학습 알고리즘 및 평가 기법 포함

(2) scipy

//사이파이//

- 과학기술계산 지원

- 학습알고리즘 및 최적화 기법 제공

(3) statsmodels

- 추정, 검정을 포함한 통계분석 (regression, time-series analysis, …) 제공

Page 14: Programming 1 - Pythondelab.cju.ac.kr/python_s1.pdf · Programming 1 - Python . 1 Python. 을 이용한 기초 통계분석 1. 통계학을. 위한. Python . 모듈. 1.1 numpy . 패키지

Programming 1 - Python

14

2. Python 회귀 분석

2.1 Pandas 모듈 이용

(1) 변수 명이 있는 데이터

import pandas as pd

# csv 파일을 가져옴

df = pd.read_csv("f:/data/python/csv_exam.csv")

# 데이터의 칼럼명을 변경

# df.columns = ["num", "ban", "score1", "score2", "score3"]

# 앞부분 일부 데이터 보여 줌

print(df.head())

# 회귀분석 수행 및 결과

result = sm.ols(formula = 'science ~ math + english', data = df).fit()

# 분석결과 출력

print(result.summary())

(2) 변수명이 없는 데이터

import pandas as pd

# csv 파일을 가져옴

df = pd.read_csv("f:/data/python/csv_exam2.csv",names=["id", "class", "math", "english", "science"])

# 앞부분 일부 데이터 보여 줌

print(df.head())

# 회귀분석 수행 및 결과

result = sm.ols(formula = 'science ~ math + english', data = df).fit()

# 분석결과 출력

print(result.summary())

(3) 실습 예제

Page 15: Programming 1 - Pythondelab.cju.ac.kr/python_s1.pdf · Programming 1 - Python . 1 Python. 을 이용한 기초 통계분석 1. 통계학을. 위한. Python . 모듈. 1.1 numpy . 패키지

Programming 1 - Python

15

- cars.txt 데이터를 이용하여 다음의 회귀식을 구하시오.

dist = 𝑏𝑏0 + 𝑏𝑏1𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠

- speed=21 일 때 dist의 예측 값을 구하시오.

- speed (X축)와 dist (Y축)의 산점도를 그리시오.