데이터 벡터화
이번 글에서는 이전 전치리 작업한 텍스트 데이터를 벡터화시키는 작업을 진행할 것이다.
전처리 과정은 아래 링크 참조
텍스트를 컴퓨터가 알아보기 쉽게 사전작업을 진행해주는 것이다.
문장의 단어를 counting해서 배열안에 count된 수를 넣어주는 작업
Bag Of Words Model 참조
데이터 전처리 작업 코드
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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | from multiprocessing import Pool import pandas as pd import re import time import nltk from nltk.corpus import stopwords def use_multiprocess(func, iter, workers): pool = Pool(processes=workers) result = pool.map(func, iter) pool.close() return result def check_basic_info(): print("-----train-----") print(train.head()) print(train.info()) print(train['tweet'][0:10]) print("\n\n-----test-----") print(test.head()) print(test.info()) def data_text_cleaning(data): # 영문자 이외 문자는 공백으로 변환 only_english = re.sub('[^a-zA-Z]', ' ', data) # 소문자 변환 no_capitals = only_english.lower().split() # 불용어 제거 stops = set(stopwords.words('english')) no_stops = [word for word in no_capitals if not word in stops] # 어간 추출 stemmer = nltk.stem.SnowballStemmer('english') stemmer_words = [stemmer.stem(word) for word in no_stops] # 공백으로 구분된 문자열로 결합하여 결과 반환 return ' '.join(stemmer_words) if __name__ == '__main__': start_time = time.time() train = pd.read_csv('/Users/Jamong/Desktop/data/twitter_sentiment/train.tsv', header=0, delimiter='\t', quoting=3) test = pd.read_csv('/Users/Jamong/Desktop/data/twitter_sentiment/test.tsv', header=0, delimiter='\t', quoting=3) check_basic_info() clean_processed_tweet = use_multiprocess(data_text_cleaning, train['tweet'], 3) print('실행 시간 :', (time.time() - start_time)) | cs |
텍스트 데이터 벡터화
위에서 전처리 작업된 tweet내용을 counting해서 벡터화
min_df : 최소 토큰 수 지정
ngram_range : (최소 ngram, 최대 ngram)
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 | def vectorization(data): vectorizer = CountVectorizer( analyzer='word', min_df=2, ngram_range=(1, 2) ) pipeline = Pipeline( [ ('vect', vectorizer), ] ) train_data_features = pipeline.fit_transform(data) print(train_data_features.shape) vocab = vectorizer.get_feature_names() print(len(vocab)) print(vocab[:10]) dist = np.sum(train_data_features, axis=0) df1 = pd.DataFrame(dist, columns=vocab) print(df1) df2 = pd.DataFrame(train_data_features[:10].toarray(), columns=vocab).head() print(df2) | cs |
결과
ngram을 1 - 2로 지정하여 반환한다.
전체 코드
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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 | from multiprocessing import Pool import pandas as pd import re import time import nltk from nltk.corpus import stopwords from sklearn.feature_extraction.text import CountVectorizer from sklearn.pipeline import Pipeline import numpy as np def use_multiprocess(func, iter, workers): pool = Pool(processes=workers) result = pool.map(func, iter) pool.close() return result def check_basic_info(): print("-----train-----") print(train.head()) print(train.info()) print(train['tweet'][0:10]) print("\n\n-----test-----") print(test.head()) print(test.info()) def data_text_cleaning(data): # 영문자 이외 문자는 공백으로 변환 only_english = re.sub('[^a-zA-Z]', ' ', data) # 소문자 변환 no_capitals = only_english.lower().split() # 불용어 제거 stops = set(stopwords.words('english')) no_stops = [word for word in no_capitals if not word in stops] # 어간 추출 stemmer = nltk.stem.SnowballStemmer('english') stemmer_words = [stemmer.stem(word) for word in no_stops] # 공백으로 구분된 문자열로 결합하여 결과 반환 return ' '.join(stemmer_words) def vectorization(data): vectorizer = CountVectorizer( analyzer='word', min_df=2, ngram_range=(1, 2) ) pipeline = Pipeline( [ ('vect', vectorizer), ] ) train_data_features = pipeline.fit_transform(data) print(train_data_features.shape) vocab = vectorizer.get_feature_names() print(len(vocab)) print(vocab[:10]) dist = np.sum(train_data_features, axis=0) df1 = pd.DataFrame(dist, columns=vocab) print(df1) df2 = pd.DataFrame(train_data_features[:10].toarray(), columns=vocab).head() print(df2) if __name__ == '__main__': start_time = time.time() train = pd.read_csv('/Users/Jamong/Desktop/data/twitter_sentiment/train.tsv', header=0, delimiter='\t', quoting=3) test = pd.read_csv('/Users/Jamong/Desktop/data/twitter_sentiment/test.tsv', header=0, delimiter='\t', quoting=3) check_basic_info() clean_processed_tweet = use_multiprocess(data_text_cleaning, train['tweet'], 3) vectorization(clean_processed_tweet) print('실행 시간 :', (time.time() - start_time)) | cs |
댓글0