일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- Spring
- Spring JPA
- modern c++
- Baekjoon
- 파이썬
- SECS/GEM
- programmers
- spotify
- Computer Science
- 프로그래머스
- SECS
- 스포티파이
- java
- Spotify Api
- SWEA
- MYSQL
- SECS-II
- 백준
- 자바
- 비트겟
- 회귀
- spring boot
- SW Expert Academy
- regression
- c
- Gem
- CS
- 회원가입
- C++
- python
Archives
- Today
- Total
비버놀로지
[회귀분석] 영어 단어 코퍼스 분석하기 본문
728x90
영어 단어 코퍼스 분석하기
두 번째 프로젝트에서는 약 1억 개의 영어 단어로 구성된 British National Corpus (BNC) 텍스트 코퍼스(단어모음)를 다루어봅니다.
words.txt 파일에 저장된 단어 10,000개의 빈도수를 그래프로 시각화한 후 선형회귀법을 적용해보겠습니다. 주석을 읽고 실행 결과가 출력되도록 do_linear_regression() 함수를 완성하세요.
실습
- 주석과 함께 코드를 이해하고 각 함수의 리턴값을 확인하세요.
- do_linear_regression() 함수를 작성하세요 (44번째 줄).
- 실행 버튼을 누르고 출력되는 차트를 확인하세요.
- main() 함수에서 22번째 줄의 주석을 해제하세요. 실행 버튼을 누르고 새롭게 출력되는 차트를 확인하세요.
- 출력된 그래프와 아래 [실행 결과] 를 비교해본 후 제출 버튼을 눌러보세요.
[실행 결과]
Tips!
지프의 법칙에 따르면 자연어 코퍼스의 단어들을 순서대로 나열할 때 사용 빈도가 가장 높은 단어는 두 번째 단어 보다 빈도가 약 두 배 높으며, 세 번째 단어보다는 빈도가 세 배 높습니다.
즉, 거듭제곱 분포를 보이기 때문에 주석을 해제한 후 log(X), log(Y)를 적용하면 더욱 정확하게 선형 회귀 분석을 할 수 있습니다.
import operator
from sklearn.linear_model import LinearRegression
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import elice_utils
def main():
words = read_data()
words = sorted(words, key = lambda x : x[1] , reverse = True) # words.txt 단어를 빈도수 순으로 정렬합니다.
# 정수로 표현된 단어를 X축 리스트에, 각 단어의 빈도수를 Y축 리스트에 저장합니다.
X = list(range(1, len(words)+1))
Y = [x[1] for x in words]
# X, Y 리스트를 array로 변환합니다.
X, Y = np.array(X).reshape(-1,1), np.array(Y)
X, Y = np.log(X), np.log(Y)
# X, Y의 각 원소 값에 log()를 적용합니다.
# X, Y = np.log(X), np.log(Y)
# 기울기와 절편을 구한 후 그래프와 차트를 출력합니다.
slope, intercept = do_linear_regression(X, Y)
draw_chart(X, Y, slope, intercept)
return slope, intercept
# read_data() - words.txt에 저장된 단어와 해당 단어의 빈도수를 리스트형으로 변환합니다.
def read_data():
# words.txt 에서 단어들를 읽어,
# [[단어1, 빈도수], [단어2, 빈도수] ... ]형으로 변환해 리턴합니다.
words = []
filename = 'words.txt'
x = []
y = []
with open(filename) as data:
lines = data.readlines()
for line in lines:
word = line.replace('\n','').split(',')
word[1] = int(word[1])
words.append(word)
return words
# do_linear_regression() - 임포트한 sklearn 패키지의 함수를 이용해 그래프의 기울기와 절편을 구합니다.
def do_linear_regression(X, Y):
# do_linear_regression() 함수를 작성하세요.
X = X.reshape(-1,1)
li = LinearRegression()
li.fit(X,Y)
slope = li.coef_[0] # 2번째 변수에 대한 계수 (신문)
intercept = li.intercept_ #
return (slope, intercept)
# draw_chart() - matplotlib을 이용해 차트를 설정합니다.
def draw_chart(X, Y, slope, intercept):
fig = plt.figure()
ax = fig.add_subplot(111)
plt.scatter(X, Y)
# 차트의 X, Y축 범위와 그래프를 설정합니다.
min_X = min(X)
max_X = max(X)
min_Y = min_X * slope + intercept
max_Y = max_X * slope + intercept
plt.plot([min_X, max_X], [min_Y, max_Y],
color='red',
linestyle='--',
linewidth=3.0)
# 기울과와 절편을 이용해 그래프를 차트에 입력합니다.
ax.text(min_X, min_Y + 0.1, r'$y = %.2lfx + %.2lf$' % (slope, intercept), fontsize=15)
plt.savefig('chart.png')
elice_utils.send_image('chart.png')
if __name__ == "__main__":
main()
728x90
'인공지능 머신러닝' 카테고리의 다른 글
[나이브 베이즈 분류] 유방암 검사 키트 (0) | 2022.11.03 |
---|---|
[나이브 베이즈 분류] 확률로 pi 계산하기 (0) | 2022.11.03 |
[회귀분석] 다항식 회귀 분석 (0) | 2022.11.03 |
[회귀분석] 다중 회귀 분석 (0) | 2022.11.03 |
[회귀분석] Scikit-learn을 이용한 회귀분석 (0) | 2022.11.03 |
Comments