-
Notifications
You must be signed in to change notification settings - Fork 2
/
logisticRegression.py
158 lines (117 loc) · 5.29 KB
/
logisticRegression.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
156
157
import pandas as pd
import numpy as np
from sklearn.cross_validation import train_test_split
import re, nltk
from nltk.stem.porter import PorterStemmer
from nltk.stem.snowball import SnowballStemmer
from nltk.stem import WordNetLemmatizer
import random
from sklearn.linear_model import LogisticRegression
from sklearn.cross_validation import cross_val_score
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
from scipy.sparse import vstack,hstack
from numpy import array
import matplotlib.pyplot as plt
train_data_df = pd.read_csv('trainset.csv', header=None, delimiter="\t", quoting=3)
test_data_df = pd.read_csv('popularTest.csv', header=None,delimiter="\t" , quoting=3)
train_data_df.columns = ["Popularity","Title","Tags","Body"]
test_data_df.columns = ["Title","Tags","Body"]
print train_data_df.shape
print test_data_df.shape
print train_data_df.Popularity.value_counts()
#stemmer = SnowballStemmer('english')
#stemmer = WordNetLemmatizer()
stemmer = PorterStemmer()
def stem_tokens(tokens, stemmer):
stemmed = []
for item in tokens:
stemmed.append(stemmer.stem(item))
return stemmed
def tokenize(text):
text = re.sub("[^a-zA-Z]", " ", text)
text = re.sub("(http://)", " ", text)
text = re.sub(" +"," ", text)
text = re.sub("\\b[a-zA-Z0-9]{10,100}\\b"," ",text)
text = re.sub("\\b[a-zA-Z0-9]{0,1}\\b"," ",text)
tokens = nltk.word_tokenize(text)
stems = stem_tokens(tokens, stemmer)
return stems
vectorizer = CountVectorizer(analyzer = 'word',tokenizer = tokenize,lowercase = True,stop_words = 'english',max_features = 85)
vectorizer1 = CountVectorizer(analyzer = 'word',tokenizer = tokenize,lowercase = True,stop_words = 'english',max_features = 5)
vectorizer2 = CountVectorizer(analyzer = 'word',tokenizer = tokenize,lowercase = True,stop_words = 'english',max_features = 3)
corpus_data_features = vectorizer.fit_transform(train_data_df.Body.tolist() + test_data_df.Body.tolist())
corpus_data_features1 = vectorizer1.fit_transform(train_data_df.Title.tolist() + test_data_df.Title.tolist())
corpus_data_features2 = vectorizer2.fit_transform(train_data_df.Tags.tolist() + test_data_df.Tags.tolist())
corpus_data_features_nd = corpus_data_features.toarray()
corpus_data_features_nd1 = corpus_data_features1.toarray()
corpus_data_features_nd2 = corpus_data_features2.toarray()
corpus_data_features_nd = corpus_data_features_nd * 0.2
corpus_data_features_nd1 = corpus_data_features_nd1 * 0.5
corpus_data_features_nd2 = corpus_data_features_nd2 * 0.3
body_title_corpus = []
body_title_tags_corpus = []
for i in range(len(corpus_data_features_nd)):
body_title_corpus.append(np.concatenate((corpus_data_features_nd[i], corpus_data_features_nd1[i])))
body_title_corpus = array(body_title_corpus)
for i in range(len(corpus_data_features_nd)):
body_title_tags_corpus.append(np.concatenate((body_title_corpus[i], corpus_data_features_nd2[i])))
body_title_tags_corpus = array(body_title_tags_corpus)
print body_title_tags_corpus
X_train, X_test, y_train, y_test = train_test_split(body_title_tags_corpus[0:len(train_data_df)], train_data_df.Popularity, random_state=2)
print body_title_tags_corpus.shape
value_list = []
accu_list = []
precision_list = []
recall_list = []
f1_list = []
value = float(10)
# get predictions
for i in range(1,11):
value_list.append(value/10)
logreg_model = LogisticRegression(penalty = 'l1',dual = False,C = value/10)
#logreg_model = logreg_model.fit(X=X_train, y=y_train)
#y_pred = logreg_model.predict(X_test)
accu_score = cross_val_score(logreg_model,body_title_tags_corpus[0:len(train_data_df)],train_data_df.Popularity ,cv=10 ,scoring='accuracy').mean()
#print "\n"
#print "accuracy score : ",accu_score
accu_list.append(accu_score)
precision_score = cross_val_score(logreg_model,body_title_tags_corpus[0:len(train_data_df)],train_data_df.Popularity,cv=10,scoring='precision').mean()
#print "\n"
#print "precision score : ",precision_score
precision_list.append(precision_score)
recall_score = cross_val_score(logreg_model,body_title_tags_corpus[0:len(train_data_df)],train_data_df.Popularity,cv=10,scoring='recall').mean()
#print "\n"
#print "recall score : ",recall_score
recall_list.append(recall_score)
f1_score = cross_val_score(logreg_model,body_title_tags_corpus[0:len(train_data_df)],train_data_df.Popularity,cv=10,scoring='f1').mean()
#print "\n"
#print "f1 score : ",f1_score,"\n"
f1_list.append(f1_score)
value -= 1
x = 0
for i in range(len(accu_list)) :
x += accu_list[i]
print x/len(accu_list)
x = 0
for i in range(len(accu_list)) :
x += precision_list[i]
print x/len(accu_list)
x = 0
for i in range(len(accu_list)) :
x += recall_list[i]
print x/len(accu_list)
x = 0
for i in range(len(accu_list)) :
x += f1_list[i]
print x/len(accu_list)
plt.plot(value_list,accu_list,'-y',linewidth = 4,label = "accuracy")
plt.plot(value_list,precision_list,'-r', linewidth = 4, label = "precision")
plt.plot(value_list,recall_list,'-b', linewidth = 4, label = "recall")
plt.plot(value_list,f1_list,'-g', linewidth = 4, label = "f1 score")
plt.legend(fontsize = 21)
plt.xticks(fontsize = 21, fontweight = 'semibold')
plt.yticks(fontsize = 21,fontweight = 'semibold')
plt.xlabel("C values", fontsize = 21,fontweight = 'semibold')
plt.ylabel("Evaluation Scores", fontsize = 21,fontweight = 'semibold')
plt.show()