-
Notifications
You must be signed in to change notification settings - Fork 0
/
svc_reuters_on_trained.py
155 lines (119 loc) · 4.32 KB
/
svc_reuters_on_trained.py
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
import time
from gensim.models import Word2Vec
import pandas as pd
import time
from nltk.corpus import stopwords
import numpy as np
from KaggleWord2VecUtility import KaggleWord2VecUtility
from numpy import float32
import math
from sklearn.ensemble import RandomForestClassifier
import sys
from sklearn.externals import joblib
from sklearn.feature_extraction.text import TfidfVectorizer,HashingVectorizer
from sklearn import svm
import pickle
import cPickle
from math import *
from sklearn.mixture import GaussianMixture
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import MultiLabelBinarizer
from pandas import DataFrame
from gensim.models import KeyedVectors
filename = sys.argv[1]
dims = int(sys.argv[2])
# Word Vectors
Glove = KeyedVectors.load(filename)
start = time.time()
all = pd.read_pickle('all.pkl')
# Computing tf-idf values.
traindata = []
for i in range( 0, len(all["text"])):
traindata.append(" ".join(KaggleWord2VecUtility.review_to_wordlist(all["text"][i], True)))
tfv = TfidfVectorizer(strip_accents='unicode',dtype=np.float32)
tfidfmatrix_traindata = tfv.fit_transform(traindata)
featurenames = tfv.get_feature_names()
idf = tfv._tfidf.idf_
# Creating a dictionary with word mapped to its idf value
print "Creating word-idf dictionary for Training set..."
word_idf_dict = {}
for pair in zip(featurenames, idf):
word_idf_dict[pair[0]] = pair[1]
temp_time = time.time() - start
print "Creating Document Vectors...:", temp_time, "seconds."
# Create train and text data.
lb = MultiLabelBinarizer()
Y = lb.fit_transform(all.tags)
train_data, test_data, Y_train, Y_test = train_test_split(all["text"], Y, test_size=0.3, random_state=42)
train = DataFrame({'text': []})
test = DataFrame({'text': []})
train["text"] = train_data.reset_index(drop=True)
test["text"] = test_data.reset_index(drop=True)
# gwbowv is a matrix which contain normalised normalised gwbowv.
gwbowv = np.zeros( (train["text"].size, dims), dtype="float32")
counter = 0
min_no = 0
max_no = 0
for review in train["text"]:
# Get the wordlist in each text article.
words = KaggleWord2VecUtility.review_to_wordlist( review, remove_stopwords=True )
word_to_tf = {}
for x in words:
if x in word_to_tf:
word_to_tf[x] += 1
else:
word_to_tf[x] = 1
document_vector = np.zeros(dims, dtype="float32")
for word in word_to_tf:
if word in Glove:
document_vector += (word_to_tf[word]*word_idf_dict[word]) * Glove[word]
#print("Word Available")
else:
pass
#print("X X X Word Not Available")
#if word in Glove:
#document_vector += (word_to_tf[word]*word_idf_dict[word])*Glove[word]
#else:
# document_vector += (word_to_tf[word]*word_idf_dict[word])*Glove['unk']
# These words will be passed to generate the document vector
gwbowv[counter] = document_vector # Code to construct the document vector
counter+=1
if counter % 1000 == 0:
print "Train text Covered : ",counter
#print "Document Vector", document_vector
endtime_gwbowv = time.time() - start
gwbowv_test = np.zeros( (test["text"].size, dims), dtype="float32")
counter = 0
for review in test["text"]:
# Get the wordlist in each text article.
words = KaggleWord2VecUtility.review_to_wordlist( review, remove_stopwords=True )
word_to_tf = {}
for x in words:
if x in word_to_tf:
word_to_tf[x] += 1
else:
word_to_tf[x] = 1
document_vector = np.zeros(dims, dtype="float32")
for word in word_to_tf:
if word in Glove:
document_vector += (word_to_tf[word]*word_idf_dict[word]) * Glove[word]
#print("Word Available")
else:
pass
#print("X X X Word Not Available")
#if word in Glove:
#document_vector += (word_to_tf[word]*word_idf_dict[word])*Glove[word]
#else:
# document_vector += (word_to_tf[word]*word_idf_dict[word])*Glove['unk']
# These words will be passed to generate the document vector
gwbowv[counter] = document_vector # Code to construct the document vector
counter+=1
if counter % 1000 == 0:
print "Test Text Covered : ",counter
#print "Document Vector", document_vector
#saving gwbowv train and test matrices
np.save('Reuters_train_trained_{}'.format(dims), gwbowv)
np.save('Reuters_test_trained_{}'.format(dims), gwbowv_test)
endtime = time.time() - start
print "Total time taken: ", endtime, "seconds."
print "********************************************************"