250x250
Notice
Recent Posts
Recent Comments
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- db
- 네이버뉴스
- pytorch
- Topics
- 파이썬
- Websocket
- 이력서
- 크롤링
- 게시판 만들기
- 자바
- RESFUL
- java
- 방식으로 텍스트
- 지마켓
- Python
- jsp 파일 설정
- mysql
- tomoto
- spring MVC(모델2)방식
- 코사인 유사도
- lda
- word2vec
- test
- 과학백과사전
- 幼稚园杀手(유치원킬러)
- r
- oracle
- 토픽추출
- (깃)git bash
- Gmarket
Archives
- Today
- Total
무회blog
python: 200529-python-test001 ldaModel-토픽추출 본문
import numpy as np
import pandas as pd
import matplotlib.font_manager as fm
import matplotlib.pyplot as plt
from future.utils import iteritems
from sklearn.manifold import TSNE
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import CountVectorizer
from string import punctuation
from collections import Counter
from gensim import corpora
from gensim import models
# 불용어 사전 읽기
# Txt 파일의 형태는 ANSI, EUC-KR로 인코딩 되어 한다.
with open("C:\\Users\\C20A-018\\Downloads\\python\\03-daiMa\\04-srcTest\\testting\\Dic\\StopWordKorean.txt", 'r') as r_file:
#파일을 연다. 문장 단위로 끊어 읽는다.
kr_stop = r_file.read().splitlines()
# kr_stop[710]
# punctuation는 [, ], ? 등 기호 리스트 이다.
stop_words = [set(kr_stop + list(punctuation))]
stop_words = list(punctuation)
# 분석 대상 텍스트 로딩. Txt 파일의 형태는 ANSI, EUC-KR로 인코딩 되어 한다.
with open('C:\\Users\\C20A-018\\Downloads\\python\\03-daiMa\\04-srcTest\\testting\\Dic\\문재인대통령취임연설문.txt', 'r') as read_file:
read_doc = read_file.read()
# #전처리
read_doc= read_doc.replace('.','')
documents = ' '.join(read_doc.split(' ')[1:])
documents = [' '.join(documents.split('\n')[1:])]
print(type(documents))
print(len(documents))
#################################################################
print('-'*60)
as_one = ''
for document in documents:
as_one = as_one + ' ' + document
words = as_one.split()
# as_one
# words
# print(type(words))
# print(type(words[0]))
# print(len(words))
words[0:10]
counts = Counter(words)
# print(words)
# print(len(words))
# print(type(words))
# print(len(counts))
# print(type(counts))
# print(counts)
# order by desc
vocab = sorted(counts,key=counts.get, reverse=True)
vocab
#단어들에 번호를 매겨 그 번호와 그 단어를 dictionary로 저장 e.g. {단어 : index}
word2idx = {word.encode("utf8").decode("utf8"): ii for ii, word in enumerate(vocab,1)}
word2idx
# index가 key가 되도록 순서를 바꿈
idx2word = {ii: word for ii, word in enumerate(vocab)}
idx2word
#################################################################
print('-'*60)
# Term Frequency
# 띄어쓰기로 구분되어 있는 단어의들의 집합 documents를 입력으로 하여
# CountVectorizer()를 사용하면 쉽게 document-term matrix를 쉽게 구할 수 있다.
V = len(word2idx)
N = len(documents)
# word2idx
# documents
tf = CountVectorizer() # sklearn.feature_extraction CountVectorizer()를 사용하면 쉽게 document-term matrix를 쉽게 구할 수 있다.
tf = tf.fit_transform(documents)
tf = tf.toarray()
# print(documents) #
# print(tf)
#################################################################
print('-'*60)
# TF-IDF
# TF-IDF 또한 패키지가 존재하며, 같은 방식으로 documnets를 입력으로 하는 TfidfVectorizer를 사용하면 된다
tfidf = TfidfVectorizer(max_features = 100) #tfidf = TfidfVectorizer(max_features = 100, max_df=0.95, min_df=0)
tfidf.fit_transform(documents)
#tf-idf dictionary
tfidf_dict = tfidf.get_feature_names()
type(tfidf_dict)
# print(tfidf_dict)
#################################################################
print('-'*60)
#generate tf-idf term-document matrix
A_tfidf_sp = tfidf.fit_transform(documents) #size D x V
data_array = A_tfidf_sp.toarray()
data = pd.DataFrame(data_array,columns=tfidf_dict)
data.shape
print(type(A_tfidf_sp))
print(A_tfidf_sp)
print('-'*60 + 'A_tfidf_sp')
print(type(data_array))
print('-'*60 + 'data_array')
print(type(data))
print(data)
print('-'*60 + 'data')
print(data.shape)
print('-'*60 + 'data.shape')
#################################################################
print('-'*60)
#TF-IDF score Top 100 단어 시각화
# TF-IDF를 사용하여 단어의 중요도를 산출하였고, 선택된 100개의 단어를 t-SNE로 시각화 하였다.
#t-SNE는 고차원(본 예제에서는 100차원)상에 존재하는 데이터의 유사성들을 KL-divergence가 최소화되도록 저차원(2차원)으로 임베딩시키는 방법이다.
tsne = TSNE(n_components=2, n_iter=10000, verbose=1)
data_array.shape
data_array.T.shape
print(tsne)
print('-'*60+'tsne')
print(data_array.shape)
print('-'*60+'data_array.shape')
print(data_array.T.shape)
print('-'*60+'data_array.T.shape')
#################################################################
print('-'*60)
#100차원에 존재하는 965개의 기사들을 2차원에 965개의 기사로 표현하려고 함 (2x965)
Z = tsne.fit_transform(data_array.T)
print(type(Z))
print(Z)
print('-'*60)
print(type(tfidf_dict))
# for i in enumerate(tfidf_dict):
# print(i[1], " ",Z[i[0],0])
print(tfidf_dict)
#################################################################
print('-'*60)
path= 'C:/Users/C20A-018/Pictures/malgun.ttf'
fontprop = fm.FontProperties(fname=path, size=18)
plt.scatter(Z[:,0], Z[:,1])
for i in range(len(tfidf_dict)):
# print(i)
plt.annotate(s=tfidf_dict[i].encode("utf8").decode("utf8"), xy=(Z[i,0], Z[i,1]),fontProperties =fontprop)
plt.draw()
'Python' 카테고리의 다른 글
python: 200529-python_문서내 단어 빈도 분석 (0) | 2020.05.29 |
---|---|
python: 200529-python-test002ldaModel-토픽추출 (0) | 2020.05.29 |
python:200526-pyDB_ver001.02, - insert 다건 , executemany() (0) | 2020.05.26 |
python:200526-pyDB-001.003, insert, 단건(oracle) (0) | 2020.05.25 |
python:200524-pyDB_입력 모듈 exec_oracle_sql.py test (0) | 2020.05.25 |
Comments