DictVectorizer
from sklearn.feature_extraction import DictVectorizer
v = DictVectorizer(sparse=False)
D = [ {'A':1, 'B':2},{'B':3, 'C':1}]
X = v.fit_transform(D)
print(X)
print(v.feature_names_)
d_l = { 'A':5, 'B':1, 'D':100 }
print(v.transform(d_l))
CountVectorizer
from sklearn.feature_extraction.text import CountVectorizer
corpus = [
'This is the first document.',
'This is the second second document.',
'And the third one.',
'Is this the first document?',
'The last document?'
]
v1 = CountVectorizer()
v1.fit(corpus)
print(v1.vocabulary_)
print(v1.transform(['This is the second second document.']).toarray())
t_data = '나는 오늘은 습기가 높아서 슬퍼 강의는 잘 듣고 있니?'
from sklearn.feature_extraction.text import CountVectorizer
t_t = t_data.replace('?','')
bv = CountVectorizer()
bv.fit_transform([t_t]).toarray()
bv.vocabulary_
문서 = [ '나는 강의는 어려워', '나는 날씨가 덥고 습기가 많아', '나는 오늘은 그냥 있니?' , '나는 수업은 듣고 있니?' ]
bv.transform(문서).toarray()
bv2.vocabulary_
bv2 = CountVectorizer(stop_words=['나는'])
bv2.fit_transform(문서).toarray()
bv2.vocabulary_
Tokenizer를 활용한 카운트, TFIDF
data1 = '나는 오늘 정말 피곤해 그래서 힘들어'
data2 = '나는 오늘 정말 못해 그래서 힘들어'
data3 = '나는 오늘 너무 즐거와 그래서 행복해'
data = [data1,data2,data3]
from tensorflow.keras.preprocessing.text import Tokenizer
tk = Tokenizer()
tk.fit_on_texts(data)
tk.index_word
tk.texts_to_matrix(data, mode='count')
tk.texts_to_matrix(data, mode='tfidf')
TfidfVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
t_data = [
'공부 하고 싶다' ,
'공부 하고 싫다' ,
'공부 내일 할까' ,
'공부 하고 놀기' ,
'놀기 말고 놀자' ]
tfidfv = TfidfVectorizer().fit(t_data)
tfidfv.vocabulary_
a = tfidfv.transform(t_data).toarray()
pd.DataFrame(a, columns = ['공부','내일','놀기','놀자','말고','싫다','싶다','하고','할까'])
data1 = '나는 오늘 정말 피곤해 그래서 힘들어'
data2 = '나는 오늘 정말 못해 그래서 힘들어'
data3 = '나는 오늘 너무 즐거와 그래서 행복해'
t_v = TfidfVectorizer()
m_data = t_v.fit_transform( [data1,data2,data3] )
m_data.toarray()
m_data.toarray().shape
TF IDF 원시적 방법
from math import log
import pandas as pd
t_data = [
'공부 하고 싶다' ,
'공부 하고 싫다' ,
'공부 내일 할까' ,
'공부 하고 놀기' ,
'놀기 말고 놀자' ]
vos = list(set( 단어 for 문장 in t_data for 단어 in 문장.split()))
n=len(t_data)
def tf(t,d):
return d.count(t)
def idf(t):
df=0
for 문장 in t_data:
df += t in 문장
return log(n/(df+1))
def tfidf(t,d):
return tf(t,d)*idf(t)
t_l = []
for i in range(n):
t_l.append([])
d = t_data[i]
for j in range(len(vos)):
t = vos[j]
t_l[-1].append(tf(t,d))
import pandas as pd
tf_ = pd.DataFrame(t_l, columns = vos)
tf_
idf_l = []
for i in range(len(vos)):
t = vos[i]
idf_l.append(idf(t))
idf_ = pd.DataFrame(idf_l , index=vos , columns=['IDF'])
idf_
tf_idf_l = []
for i in range(n):
tf_idf_l.append([])
d = t_data[i]
for j in range(len(vos)):
t = vos[j]
tf_idf_l[-1].append(tfidf(t,d))
tf_idf_ = pd.DataFrame(tf_idf_l, columns=vos )
tf_idf_
pad_sequences
ck_t_x = pad_sequences(t_x)
ck_t_x = pad_sequences(t_x, padding = 'post')
ck_t_x = pad_sequences (t_x, padding = 'post', maxlen=4)
ck_t_x = pad_sequences (t_x, padding = 'post', maxlen=4, truncating='post', )
ck_t_x = pad_sequences (t_x, padding = 'post', maxlen=4, truncating='post', value=3 )
ck_t_x = pad_sequences (t_x, padding = 'post', maxlen=4, truncating='post', value=v )
Okt
! pip install konlpy
from konlpy.tag import Okt
from tqdm import tqdm
from nltk.util import ngrams
tk = Okt()
def tk_f(문장):
tk_d=['/'.join(i) for i in tk.pos(문장)]
return tk_d
tk_f(긍정문장_data[0])
tk.tagset 출력 : {'Adjective': '형용사', 'Adverb': '부사'} 태그정보
! pip install kss konlpy
import nltk, kss, konlpy
from konlpy.tag import Okt
t_data = '나는 오늘은 습기가 높아서 슬퍼 강의는 잘 듣고 있니?'
tk = Okt()
tk.morphs(t_data)
def 문장_처리(in_t):
입력문자 = in_t.replace('?','')
토큰_data= tk.morphs(입력문자)
단어집합 = {}
단어빈도수 = []
for 단어 in 토큰_data:
if 단어 not in 단어집합 :
단어집합[단어] = len(단어집합)
단어빈도수.insert(len(단어집합)-1 , 1)
else:
단어인덱스 = 단어집합.get(단어)
단어빈도수[단어인덱스] += 1
return 단어집합, 단어빈도수
문장_처리(t_data)
ngrams
ng= ngrams(data, 2, pad_left=True, pad_right=True, left_pad_symbol="SS", right_pad_symbol='SE')