usr bin python coding utf-8 import codecs from sklearn import svm impo

  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
#!/usr/bin/python
# coding: utf-8
import codecs
from sklearn import svm
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve, auc
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import label_binarize
from sklearn.multiclass import OneVsRestClassifier
def generate_profiles(list_of_documents):
list_of_files = [codecs.open('Korpusa/%s' % x, 'r') for x in list_of_documents]
list_of_profiles = []
for f in list_of_files:
print f
text = f.read()
profile = {}
for i in xrange(L-N+1):
if (i % 10000) == 0: print "i = %s" % i
gram = text[i:i+N].lower()
if gram in profile.keys():
profile[gram] += 1
else:
profile[gram] = 1
list_of_profiles.append(profile)
return list_of_profiles
def merge_several_profiles(list_of_profiles):
keys = set()
for profile in list_of_profiles:
keys.update(profile.keys())
list_of_merged_profiles = []
for profile in list_of_profiles:
list_of_merged_profiles.append(profile)
for key in keys:
if key not in profile.keys():
profile[key] = 0
return list_of_merged_profiles
def return_vectors(list_of_merged_profiles):
list_of_items = [sorted(x.items()) for x in list_of_merged_profiles]
vectors = []
for items in list_of_items:
# item = ((..., ...), (..., ...), (..., ...), ...)
vector = tuple(x[1] for x in items)
vectors.append(vector)
return vectors
def make_vectors(list_of_files, list_of_examples):
profiles = generate_profiles(list_of_files+list_of_examples)
merged = merged = merge_several_profiles(profiles)
vectors = return_vectors(merged)
n = len(list_of_examples)
return vectors[:-n], vectors[-n:]
def check(clf, example, author):
if clf.predict([example])[0] == author:
return u"да"
else:
return u"нет"
N = 4
L = 30000
tolstoy_files = ['AnnaKarenina.txt', 'DvaGusara.txt', 'Detstvo.txt', 'Otrochestvo.txt', 'Unost.txt']
tolstoy_example = 'VoynaIMir.txt'
pushkin_files = ['Dubrovsky.txt', 'IstoriyaSelaGorukhino.txt', 'PikovayaDama.txt', 'IstoriyaPugacheva.txt', 'EgipetskiyeNochi.txt']
pushkin_example = 'KapitanskayaDochka.txt'
lermontoff_files = ['PanoramaMoskvy.txt', 'KnyaginyaLigovskaya.txt', 'Kavkazec.txt', 'Shtoss.txt', 'Vadim.txt']
lermontoff_example = 'GeroyNashegoVremeni.txt'
vectors, examples = make_vectors(tolstoy_files + pushkin_files + lermontoff_files, [tolstoy_example, pushkin_example, lermontoff_example])
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! новое начинается вот отсюда:
clf = OneVsRestClassifier(svm.SVC())
classes_list = [u'Tolstoy', u'Pushkin', u'Lermontov']
classes = [u'Tolstoy']*5 + [u'Pushkin']*5 + [u'Lermontov']*5
X, y = vectors, classes
#print u'Является ли автором "Войны и мира" Pushkin? Ответ - %s.' % check(clf, examples[0], u"Pushkin")
#print u'Является ли автором "Капитанской дочки" Pushkin? Ответ - %s.' % check(clf, examples[1], u"Pushkin")
#print u'Является ли автором "Героя нашего времени" Lermontov? Ответ - %s.' % check(clf, examples[2], u"Lermontov")
y = label_binarize(y, classes=classes_list)
n_classes = y.shape[1]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.5,
random_state=0)
#y_score = clf.fit(vectors, classes).decision_function(examples)
y_score = clf.fit(X_train, y_train).decision_function(X_test)
# Compute ROC curve and ROC area for each class
fpr = dict()
tpr = dict()
roc_auc = dict()
for i in range(n_classes):
fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_score[:, i])
roc_auc[i] = auc(fpr[i], tpr[i])
# Compute micro-average ROC curve and ROC area
fpr["micro"], tpr["micro"], _ = roc_curve(y_test.ravel(), y_score.ravel())
roc_auc["micro"] = auc(fpr["micro"], tpr["micro"])
# Drawing a plot
plt.figure()
plt.plot(fpr["micro"], tpr["micro"],
label='micro-average ROC curve (area = {0:0.2f})'
''.format(roc_auc["micro"]))
for i in range(n_classes):
plt.plot(fpr[i], tpr[i], label='ROC curve of class {0} (area = {1:0.2f})'
''.format(classes_list[i], roc_auc[i]))
plt.plot([0, 1], [0, 1], 'k--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Some extension of Receiver operating characteristic to multi-class')
plt.legend(loc="lower right")
plt.show()