본문 바로가기

반응형

분류 전체보기

(291)
차원축소 (3) 6.4 tSNE를 이용한 시각화와 차원축소의 효과 tSNE: 시각화를 위해 사용되는 비지도학습 알고리즘, 다차원 데이터 사이의 거리를 가장 잘 보존하는 2차원 좌표를 찾기 위해 사용 %matplotlib inline import matplotlib.pyplot as plt import matplotlib as mpl # 그래프에서 마이너스 폰트 깨지는 문제에 대한 대처 mpl.rcParams['axes.unicode_minus'] = False from sklearn.manifold import TSNE tfidf = TfidfVectorizer(tokenizer=tokenizer) X_train_tfidf = tfidf.fit_transform(X_train) # train set을 변환 X_test_..
차원축소 (2) 6.3 LSA를 이용한 차원 축소와 의미 파악 LSA(Latent Semantic Analysis): 잠재 의미 분석 LSA에서 차원 축소는 SVD의 변형인 절단된 SVD(Truncated SVD)를 통해 이루어짐 6.3.1 LSA를 이용한 차원 축소와 성능 from sklearn.decomposition import TruncatedSVD svd = TruncatedSVD(n_components=2000, random_state=7) #압축할 component의 수 지정 X_train_lsa = svd.fit_transform(X_train_tfidf) X_test_lsa = svd.transform(X_test_tfidf) print('LSA Converted X shape:', X_train_lsa..
차원축소 (1) 6.1 차원의 저주와 차원 축소의 이유 차원의 저주: 낮은 차원에서는 발생하지 않던 문제가 차원이 커지면서 발생하는 것 해결방법 데이터를 충분히 늘리는 것 BOW로 표현한 문서의 특성 수를 줄임 6.2 PCA를 이용한 차원 축소 PCA(Principal Component Analysis): 주성분 분석, 데이터의 분산을 최대한 보존하는 새로운 축을 찾아 변환함으로써 차원을 축소하고자 하는 방법 from sklearn.datasets import fetch_20newsgroups #20개의 토픽 중 선택하고자 하는 토픽을 리스트로 생성 categories = ['alt.atheism', 'talk.religion.misc', 'comp.graphics', 'sci.space'] #학습 데이터셋을 가져옴 n..
BOW 기반의 문서 분류 (8) 5.8 한국어 문서의 분류 5.8.2 성능을 개선하기 위한 노력 tfidf = TfidfVectorizer(tokenizer=okt.morphs, max_features=2000, min_df=5, max_df=0.5) # 명사 대신 모든 형태소를 사용 X_train_tfidf = tfidf.fit_transform(X_train) X_test_tfidf = tfidf.transform(X_test) clf = LogisticRegression(max_iter=1000) # 충분한 학습을 위해 max_iter를 1,000으로 설정, 기본은 100 clf.fit(X_train_tfidf, y_train) print('#Train set score: {:.3f}'.format(clf.score(X_train..
BOW 기반의 문서 분류 (7) 5.8 한국어 문서의 분류 5.8.1 다음 영화 리뷰에 대한 영화 제목 예 import pandas as pd df = pd.read_csv('/content/daum_movie_review.csv') df.head(5) df.title.value_counts() """ 신과함께 4947 택시운전사 2322 인피니티 워 2042 범죄도시 1939 곤지암 1547 라라랜드 1150 코코 778 Name: title, dtype: int64 """ from sklearn.model_selection import train_test_split # split data and labels into a training and a test set X_train, X_test, y_train, y_test = trai..
BOW 기반의 문서 분류 (6) 5.7 카운트 기반의 문제점과 N-gram을 이용한 보완 5.7.1 통계로는 알 수 없는 문맥 정보 BOW는 단어들이 쓰여진 순서에 따른 문맥 정보를 이용할 수 없음 BOW는 단어들의 순서를 무시하고, 단어가 사용된 횟수를 기반으로 문서에 대한 벡터 만듬 5.7.2 N-gram의 이해 N-gram: n개의 연속적인 단어들의 나열 하나의 토큰이 두개 이상의 단어로 구성될 수 있음 5.7.3 N-gram을 이용한 문서 분류 from nltk.corpus import stopwords from sklearn.feature_extraction.text import TfidfVectorizer from nltk.corpus import stopwords cachedStopWords = stopwords.words..
BOW 기반의 문서 분류 (5) 5.6 성능을 높이는 방법 import nltk nltk.download('stopwords') nltk.download('stopwords', quiet=True) # Download stopwords without the graphical interface """ [nltk_data] Downloading package stopwords to /root/nltk_data... [nltk_data] Package stopwords is already up-to-date! True """ # 필요한 library들을 import from nltk.corpus import stopwords cachedStopWords = stopwords.words("english") from nltk.tokenize i..
BOW 기반의 문서 분류 (4) 5.4 로지스틱 회귀분석을 이용한 문서 분류 5.4.2 라쏘 회귀를 이용한 특성 선택 라쏘 회귀: 특성의 계수에 대해 정규화를 하지만 L1 정규화 사용 lasso_clf = LogisticRegression(penalty='l1', solver='liblinear', C=1) # Lasso는 동일한 LogisticRegression을 사용하면서 매개변수로 지정 lasso_clf.fit(X_train_tfidf, y_train) # train data로 학습 print('#Train set score: {:.3f}'.format(lasso_clf.score(X_train_tfidf, y_train))) print('#Test set score: {:.3f}'.format(lasso_clf.score(X_t..
BOW 기반의 문서 분류 (3) 5.4 로지스틱 회귀분석을 이용한 문서 분류 from sklearn.linear_model import LogisticRegression #sklearn이 제공하는 logistic regression을 사용 #count vector에 대해 regression을 해서 NB와 비교 LR_clf = LogisticRegression() #분류기 선언 LR_clf.fit(X_train_tfidf, y_train) # train data를 이용하여 분류기를 학습 print('Train set score: {:.3f}'.format(LR_clf.score(X_train_tfidf, y_train))) # train data에 대한 예측정확도 print('Test set score: {:.3f}'.format(LR_..
BOW 기반의 문서 분류 (2) 5.2 머신러닝과 문서 분류 과정에 대한 이해 머신러닝을 이용한 문서 분류의 과정 데이터 정제, 전처리 데이터 분리 머신러닝 학습 평가 최종모형 도출 예측 5.3 나이브 베이즈 분류기를 이용한 문서 분류 사전 확률: 특성에 대한 정보가 없을 때 학습 데이터셋의 분포를 통해 확인한 확률 from sklearn.naive_bayes import MultinomialNB #sklearn이 제공하는 MultinomialNB 를 사용 NB_clf = MultinomialNB() # 분류기 선언 NB_clf.fit(X_train_cv, y_train) #train set을 이용하여 분류기(classifier)를 학습 print('Train set score: {:.3f}'.format(NB_clf.score(X_t..

반응형