#examples taken from here: http://stackoverflow.com/a/1750187
mydoclist = ['Julie loves me more than Linda loves me',
'Jane likes me more than Julie loves me',
'He likes basketball more than baseball']
#mydoclist = ['sun sky bright', 'sun sun bright']
from collections import Counter
for doc in mydoclist:
tf = Counter()
for word in doc.split():
tf[word] +=1
print tf.items()
[('me', 2), ('Julie', 1), ('loves', 2), ('Linda', 1), ('than', 1), ('more', 1)]
[('me', 2), ('Julie', 1), ('likes', 1), ('loves', 1), ('Jane', 1), ('than', 1), ('more', 1)]
[('basketball', 1), ('baseball', 1), ('likes', 1), ('He', 1), ('than', 1), ('more', 1)]
import string #allows for format()
def build_lexicon(corpus):
lexicon = set()
for doc in corpus:
lexicon.update([word for word in doc.split()])
return lexicon
def tf(term, document):
return freq(term, document)
def freq(term, document):
return document.split().count(term)
vocabulary = build_lexicon(mydoclist)
doc_term_matrix = []
print 'Our vocabulary vector is [' + ', '.join(list(vocabulary)) + ']'
for doc in mydoclist:
print 'The doc is "' + doc + '"'
tf_vector = [tf(word, doc) for word in vocabulary]
tf_vector_string = ', '.join(format(freq, 'd') for freq in tf_vector)
print 'The tf vector for Document %d is [%s]' % ((mydoclist.index(doc)+1), tf_vector_string)
doc_term_matrix.append(tf_vector)
# here's a test: why did I wrap mydoclist.index(doc)+1 in parens? it returns an int...
# try it! type(mydoclist.index(doc) + 1)
print 'All combined, here is our master document term matrix: '
print doc_term_matrix
import math def l2_normalizer(vec): denom = np.sum([el**2 for el in vec]) return [(el / math.sqrt(denom)) for el in vec] doc_term_matrix_l2 = [] for vec in doc_term_matrix: doc_term_matrix_l2.append(l2_normalizer(vec)) print 'A regular old document term matrix: ' print np.matrix(doc_term_matrix) print '\nA document term matrix with row-wise L2 norms of 1:' print np.matrix(doc_term_matrix_l2) # if you want to check this math, perform the following: # from numpy import linalg as la # la.norm(doc_term_matrix[0]) # la.norm(doc_term_matrix_l2[0])
[[2 0 1 0 0 2 0 1 0 1 1] [2 0 1 0 1 1 1 0 0 1 1] [0 1 0 1 1 0 0 0 1 1 1]]
[[ 0.57735027 0. 0.28867513 0. 0. 0.57735027 0. 0.28867513 0. 0.28867513 0.28867513] [ 0.63245553 0. 0.31622777 0. 0.31622777 0.31622777 0.31622777 0. 0. 0.31622777 0.31622777] [ 0. 0.40824829 0. 0.40824829 0.40824829 0. 0. 0. 0.40824829 0.40824829 0.40824829]]
def numDocsContaining(word, doclist):
doccount = 0
for doc in doclist:
if freq(word, doc) > 0:
doccount +=1
return doccount
def idf(word, doclist):
n_samples = len(doclist)
df = numDocsContaining(word, doclist)
return np.log(n_samples / 1+df)
my_idf_vector = [idf(word, mydoclist) for word in vocabulary]
print 'Our vocabulary vector is [' + ', '.join(list(vocabulary)) + ']'
print 'The inverse document frequency vector is [' + ', '.join(format(freq, 'f') for freq in my_idf_vector) + ']'
import numpy as np def build_idf_matrix(idf_vector): idf_mat = np.zeros((len(idf_vector), len(idf_vector))) np.fill_diagonal(idf_mat, idf_vector) return idf_mat my_idf_matrix = build_idf_matrix(my_idf_vector) #print my_idf_matrix
doc_term_matrix_tfidf = []
#performing tf-idf matrix multiplication
for tf_vector in doc_term_matrix:
doc_term_matrix_tfidf.append(np.dot(tf_vector, my_idf_matrix))
#normalizing
doc_term_matrix_tfidf_l2 = []
for tf_vector in doc_term_matrix_tfidf:
doc_term_matrix_tfidf_l2.append(l2_normalizer(tf_vector))
print vocabulary
print np.matrix(doc_term_matrix_tfidf_l2) # np.matrix() just to make it easier to look at
set(['me', 'basketball', 'Julie', 'baseball', 'likes', 'loves', 'Jane', 'Linda', 'He', 'than', 'more'])
[[ 0.57211257 0. 0.28605628 0. 0. 0.57211257
0. 0.24639547 0. 0.31846153 0.31846153]
[ 0.62558902 0. 0.31279451 0. 0.31279451 0.31279451
0.26942653 0. 0. 0.34822873 0.34822873]
[ 0. 0.36063612 0. 0.36063612 0.41868557 0. 0.
0. 0.36063612 0.46611542 0.46611542]]
from sklearn.feature_extraction.text import CountVectorizer
count_vectorizer = CountVectorizer(min_df=1)
term_freq_matrix = count_vectorizer.fit_transform(mydoclist)
print "Vocabulary:", count_vectorizer.vocabulary_
from sklearn.feature_extraction.text import TfidfTransformer
tfidf = TfidfTransformer(norm="l2")
tfidf.fit(term_freq_matrix)
tf_idf_matrix = tfidf.transform(term_freq_matrix)
print tf_idf_matrix.todense()
Vocabulary: {u'me': 8, u'basketball': 1, u'julie': 4, u'baseball': 0, u'likes': 5, u'loves': 7, u'jane': 3, u'linda': 6, u'more': 9, u'than': 10, u'he': 2}
[[ 0. 0. 0. 0. 0.28945906 0.
0.38060387 0.57891811 0.57891811 0.22479078 0.22479078]
[ 0. 0. 0. 0.41715759 0.3172591 0.3172591
0. 0.3172591 0.6345182 0.24637999 0.24637999]
[ 0.48359121 0.48359121 0.48359121 0. 0. 0.36778358
0. 0. 0. 0.28561676 0.28561676]]
from sklearn.feature_extraction.text import TfidfVectorizer tfidf_vectorizer = TfidfVectorizer(min_df = 1) tfidf_matrix = tfidf_vectorizer.fit_transform(mydoclist) print tfidf_matrix.todense()
[[ 0. 0. 0. 0. 0.28945906 0. 0.38060387 0.57891811 0.57891811 0.22479078 0.22479078] [ 0. 0. 0. 0.41715759 0.3172591 0.3172591 0. 0.3172591 0.6345182 0.24637999 0.24637999] [ 0.48359121 0.48359121 0.48359121 0. 0. 0.36778358 0. 0. 0. 0.28561676 0.28561676]]
new_docs = ['He watches basketball and baseball', 'Julie likes to play basketball', 'Jane loves to play baseball'] new_term_freq_matrix = tfidf_vectorizer.transform(new_docs) print tfidf_vectorizer.vocabulary_ print new_term_freq_matrix.todense()
{u'me': 8, u'basketball': 1, u'julie': 4, u'baseball': 0, u'likes': 5, u'loves': 7, u'jane': 3, u'linda': 6, u'more': 9, u'than': 10, u'he': 2}
[[ 0.57735027 0.57735027 0.57735027 0. 0. 0. 0.
0. 0. 0. 0. ]
[ 0. 0.68091856 0. 0. 0.51785612 0.51785612
0. 0. 0. 0. 0. ]
[ 0.62276601 0. 0. 0.62276601 0. 0. 0.
0.4736296 0. 0. 0. ]]
import os
import csv
#os.chdir('/Users/rweiss/Dropbox/presentations/IRiSS2013/text1/fileformats/')
with open('amazon/sociology_2010.csv', 'rb') as csvfile:
amazon_reader = csv.DictReader(csvfile, delimiter=',')
amazon_reviews = [row['review_text'] for row in amazon_reader]
#your code here!!!
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有