Code source de SVM
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
""" A SVM model.
The doc is here : http://scikit-learn.org/dev/modules/svm.html#svm
and there : http://scikit-learn.org/dev/modules/generated/sklearn.svm.SVC.html#sklearn.svm.SVC
Méta-apprentissage
------------------
Pour régler les méta-paramètres des méthodes de classification,
dans chaque script, je sépare les données de *train.csv* en apprentissage
et test (selon une proportion de 55% à 85%).
.. todo::
Utiliser `sklearn.cross_validation.train_test_split
<http://scikit-learn.org/dev/modules/generated/sklearn.cross_validation.train_test_split.html#sklearn.cross_validation.train_test_split>`_
pour séparer les données de 'train.csv' en train et test.
Pour les SVM, je règle la constante C de régularisation.
**Il y a d'autres méta-paramètres**, que je n'ai pas encore cherché à modifier.
--------------------------------------------------------------------------------
Sortie du script
----------------
.. runblock:: console
$ python SVM.py
Résultats
---------
La soumission du résultat à Kaggle donne 65.07%.
--------------------------------------------------------------------------------
"""
__author__ = 'Lilian BESSON (mailto:lilian.besson[AT]normale.fr)'
from KaggleModel import *
################################################################################
# Beginning to learn
import sklearn.svm as svm
from sklearn.utils import shuffle
################################################################################
# ok, let use this 'cross validation' process to find the best
# meta parameter : C
# /!\ a lot of others meta parameters!
C_quality = {}
#: Espace de recherche
list_C = [10**i for i in xrange(-5,6)] + [0.5*10**i for i in xrange(-5,6)]
Number_try = 5 #: Nombre de tests utilisés pour méta-apprendre
proportion_train = 0.67 #: Proportion d'individus utilisés pour méta-apprendre.
print("Find the best value for the meta parameter C, with %i run for each..." % Number_try)
print("Searching in the range : %s..." % str(list_C))
print("""Using the first part (%2.2f%%, %i passengers) of the training dataset as training,
and the second part (%2.2f%%, %i passengers) as testing !"""
% ( 100.0*proportion_train, int(number_passengers*proportion_train),
100.0*(1-proportion_train), number_passengers - int(number_passengers*proportion_train) ))
for C in list_C:
# train_data = shuffle(train_data)
SVM = svm.SVC(C = C, max_iter=10000, kernel = 'rbf') # ‘linear’, ‘poly’, ‘rbf’, ‘sigmoid’
print("For C=%s, learning from the first part of the dataset..." % C)
quality=[]
for nb_essais in xrange(Number_try):
# train_data = shuffle(train_data)
SVM = SVM.fit(train_data[0:int(number_passengers*proportion_train),1::],
train_data[0:int(number_passengers*proportion_train),0])
Output = SVM.predict(train_data[number_passengers - int(number_passengers*proportion_train)::,1::])
quality.append(100.0 * Output[Output == train_data[number_passengers - int(number_passengers*proportion_train)::,0]].size / Output.size)
C_quality[C] = np.mean(quality)
print("... this value of C seems to have a (mean) quality = %2.2f%%..." % np.mean(quality))
val = C_quality.values()
#: La valeur optimale trouvée pour le paramètre n_estimators
best_C = C_quality.keys()[val.index(np.max(val))]
print("With trying each of the following C (%s), each %i times, the best one is %s. (for a quality = %2.2f%%)"
% (str(list_C), Number_try, best_C, np.max(val)))
################################################################################
print("Creating the classifier with the optimal value of C.")
SVM = svm.SVC(C = best_C, max_iter=10000, kernel = 'rbf')
print("Learning...")
SVM = SVM.fit(train_data[0::,1::],train_data[0::,0])
#: The score for this classifier.
score = (100.0*SVM.score(train_data[0::,1::], train_data[0::,0]) )
print(" Proportion of perfect fitting for the training dataset = %2.2f%%" %
score )
# ~ must be < 95%
# Predict on the testing set
test_file_object = csv.reader(open('test.csv', 'rb'))
header = test_file_object.next()
print("Predicting for the testing dataset")
Output = SVM.predict(test_data)
# Write the output
open_file_object = csv.writer(open("csv/SVM_best.csv", "wb"))
z = 0
for row in test_file_object:
row.insert(0, int(Output[z])) # Insert the prediction at the start of the row
open_file_object.writerow(row) # Write the row to the file
z += 1
print("Prediction: wrote in the file csv/SVM_best.csv.")