2. Python - alexattia/myWiki GitHub Wiki
Python est un langage script et interactif. Comme dans matlab, vous pouvez exécuter des fonctions, faire des calculs et utiliser des affichages graphiques, par le biais de scripts ou directement dans la console. Python est un langage faiblement typé. Le symbole # sert pour les commentaires.
Table of Contents:
##1. Opérations de bases .
les nombres : comme une calculette
1+1
2*2.5
3/2. #réel
3/2 #entier
3**4 #puissance
les booléens :
3<2
2<3 and 2<5
(not (3==5 or 2>4))
variables :
a=1;b=2<4;
print a,b
type(a)
type(b)
les listes :
a=[0,1,2,3];b=[4,5,6]
a
c=a+b
c[0]
c[1:]
c[1:3]
c[-1] #dernier élément du tableau
c[-3:-1]
len(c)
les dictionnaires :
d={"a":2, "b":3, "c":4}
d["a"]
d["d"]="e"
d
2. Fonctions :
une fonction peut être soit appliquée à une variable (comme dans len(a)) soit dépendre de la variable et être appliquée à partir de la variable :
a= [1,2,3,4,2,2]
a.count(2)
a.pop()
Fonctions utiles pour les : listes : count, append, index, reverse, remove, sort **dictionnaires **: clear, keys, values, items (que renvoie cette dernière ? )
Fonctions utiles en général : range(1,20,2) len([1,2,3]) zip(liste1,liste2) : si liste1=[x1,x2,x3,x4] et liste2=[y1,y2,y3,y4], le résultat est la liste des tuples des i-emes éléments des listes : [ (x1,y1), (x2,y2), (x3,y3), (x4,y4)]
3. Boucles et structures
python utilise l'indentation pour délimiter les structures. Attention donc, un (ou plusieurs) espace en début de ligne marque le début d'un bloc. La fin d'un bloc se fait en revenant à l'indentation précédente. Astuce : pour copier avec l'indentation, copier comme d'habitude puis dans ipython instruction : %paste
Exemples basiques :
x=0
for i in range(10):
x=x+i
print x
while x>10:
x=x-1
print x
Construction de liste :
x=range(10)
y=range(10,20)
l1=[2*a for a in x] # construit la liste composée des 2*a pour a parcourant x
l2=[a+b for a,b in zip(x,y)] #construit la liste x+y
l3=[a for a in x if (x%2 == 0)] #construit la liste des nombres pairs de x
[internal-ref] Definition de fonction:
def sommeListe(l):
x=0
for y in l:
x=x+y
return y
##4. Module : numpy et matplotlib Un module sous python est l'équivalent d'une bibliothèque de fonctions (ou package). Pour charger un module : import module Pour accéder à une fonction/variable/module du module : module.fonction.
Numpy Permet d'avoir un ensemble d'outils mathématiques très proche de matlab. En particulier : tableaux, génération aléatoire, algèbre linéaire, opération de tris, ... Par convention, on l'importe sous le nom de np : import numpy as np.
Tableaux
vec=np.zeros(10) # vecteur de taille 10 de 0.
vec2=np.arange(0.1,0.5,0.001) #vecteur de nombre de 0,1 à 0,5 (exclut) avec le pas
tab0=np.zeros((10,1)) #matrice de 2 dimensions, 10x1 != de vecteur !!!
tab1=np.ones((10,4))
np.array(range(10)) #création d'un tableau à partir d'une liste
tabr=np.random.normal(size=(10,5)) #matrice de nombres aléatoires tirés selon la loi normale
vec.shape #dimension du tableau
tabr.size #nombre d'elements du tableaux
tabr.reshape((5,10)) #changer la forme d'une matrice, le nombre d'éléments reste constant !
tabr.transpose()
np.maximum(tab0) #maximum colonne par colonne
Matrices
tab1*tab2 # attention produit point à point
tab1.dot(tab2) #produit matriciel
tab1.mean() #moyenne sur l'ensemble
tab1.mean(0) #selon la première dimension
tab1<0.5 # matrice de valeurs booléennes, vrai si la condition est vérifiée
np.sort(tab1) #sur toutes les dimensions
np.sort(tab1,0) #sur la première dimension
np.savetxt("montableau",tab) #sauver une matrice
np.load("montableau") #lire une matrice
np.hstack((tab1,vec.reshape(10,1))) #empiler des matrices (attention, tuple de matrice !!) horizontalement
np.vstack((tab1,tab2.transpose,tab1)) #et verticalement
matplotlib Syntaxe très proche de matlab import matplotlib.pyplot as plt %matplotlib inline : permet de mettre les graphiques sur la meme page sur un Jupyter notebook
plt.figure() #commence une nouvelle figure
plt.plot(x,y)
plt.show() # obligatoire à la fin pour afficher
plt.plot(x,y,"go-",label="sin") #g pour green, o pour le symbole des points, - pour tracer la ligne entre les points
plt.plot(x,np.cos(x),"b+",label="cos") #b pour blue, + pour le symbole, sans trait entre les points.
plt.legend()
5. Pandas
Python library for using data structure and data analysis tools. Pandas is composed of Dataframe and a dataframe is composed of series (such as column, one dimension array with index). Here you can find doc for regular functions on df and series, date functions, groups functionnalities, apply/map functions and general tips.
Pandas function
Code | Description |
---|---|
df=pd.DataFrame() |
creation of the dataframe |
pd.read_json or pd.read_csv |
load from a json or a csv |
pd.concat(list_of_files) |
concatenate multiple files into a single file |
df["series"].function |
apply a function to a serie |
df.reset_index() |
reset index from 0 to n |
df.set_index('series', inplace=True) |
set the index to a serie/column (BUT delete it from the dataframe) |
df.sort_values(by="serie") |
sort the dataframe by a serie values |
df.drop_duplicates() |
remove duplicates |
df.drop(labels=['series1,serie2], axis=1) |
remove 2 series/columns |
df['serie'].map(lambda x:function(x)) |
apply a anonymous function elementwise, see below |
df1.merge(df2,how='left', left_on='serie1', right_on='serie2') |
merge two dataframe using a similar column |
df['serie'].values |
return a array of the serie values |
df['serie'].value_counts() |
return the number of different entries of this serie |
df[df['serie']==j] |
return all the data i with i['serie']=j |
df[df['serie'].isin([i,j,k])] |
return all the data i with i['serie']=i or j or k |
df.iloc[j] |
return the j row |
df.iloc[:j] |
return the dataframe to the row j |
Tip : Specifying dtypes helps reduce memory requirements and load frame much faster, for example : pd.read_csv('train.csv', dtype={'a':bool,'b':np.int32, 'c':np.int32}, usecols=['a','b','c'])
Date function
Code | Description |
---|---|
df['date']=pd.to_datetime(arrond['time_from_epoch'],unit='s') |
convert date from epoch to regular date time |
df.set_index('date', inplace=True) |
useful for extract information |
df['day']=df.index.day |
extract day from the date time using the index |
df['month']=df.index.month |
idem for monnth, hour, weekday ... |
Apply, Map, ApplyMap
- Dataframe's apply method applies function on 1D arraw to each row or column.
f = lambda x: ... // df.apply(f)
- Dataframe's applymap is an elementwise function for an entire dataframe, it's a map method
df.applymap(f)
- Series's map methode. Elementwise function too
df['serie'].map(f)
The function f has to have only 1 arg! It can be useful for example to convert a string column to integer column using a python dictionnarydf['serie'].apply(lambda x:dictionnary(x))
.
Useful tip : If we want to work on strings, for example with a function on strings, and this function have two attribute but we use an apply/map function. We can use the split method. We separate the substrings of a string using '\t' and them using .split to use the string as a table of the substrings.
a='hello',b='the',c='world'
s=a+'\t'+b+'\t'+c
s/split('\t')[1] --> Out: 'the'
Other statistics (or not) function could be used : .mean()
, sum, converting (.apply(float)
, integer ...), etc.
Dataframe Groups
df.groupby()
splits the data into different groups depending on a variable. It returns a object with multiple methods. We can groups depends on several variables.
df.groupby('serie').groups
is a dictionary whose keys are the computed unique groups and corresponding values are the axis labels belonging to each group.
df.groupby('serie1')['serie2'].count()
returns the number of entries of each value of series 2 for each value of serie1 (or it could be each couple of ['serieA', 'serieB']).
The aggregation functionality provided by the agg()
function allows multiple statistics to be calculated per group in one calculation. Instructions for aggregation are provided in the form of a python dictionary. For example :
aggregations = {
'duration':'sum',
'max': lambda x: max(x)
}
df.groupby('serie').agg(aggregations)
It creates two new columns where it performs the sum and the max for each group.
6. Scikit Learn
Machine learning python library. Very easy to use and useful. Many estimator, learning curves, plotting, etc.
from sklearn import linear_model
from sklearn.ensemble import RandomForestRegressor, BaggingRegressor
Linear Regression
ln = linear_model.LinearRegression()
ln.fit (X_train, Y_train)
predict = ln.predict(X_train)
Splitting the data
X_train, X_test, Y_train, Y_test = sklearn.cross_validation.train_test_split(train_gen, target_gen, test_size=0.33, random_state=42) ##test=33% of the dataset
ln.fit(X_train,Y_train)
predict_train=ln.predict(X_train)
predict_test=ln.predict(X_test)
Mean Square Error : np.mean((Y_train - predict_train) ** 2)
Add polynomial features
def add_polynomial_terms(train, test, degree):
poly = sklearn.preprocessing.PolynomialFeatures(degree=degree)
train_poly = poly.fit_transform(train)
test_poly = poly.fit_transform(test)
return train_poly, test_poly
Plotting Learning Curves
def plot_learning_curve(estimator, title, X, y, cv=None, n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)):
plt.figure()
plt.title(title)
plt.xlabel("Training examples")
plt.ylabel("Score")
train_sizes, train_scores, test_scores = sklearn.learning_curve.learning_curve(
estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)
train_scores_mean = np.mean(train_scores, axis=1)
train_scores_std = np.std(train_scores, axis=1)
test_scores_mean = np.mean(test_scores, axis=1)
test_scores_std = np.std(test_scores, axis=1)
plt.grid()
plt.fill_between(train_sizes, train_scores_mean - train_scores_std,train_scores_mean + train_scores_std, alpha=0.1, color="r")
plt.fill_between(train_sizes, test_scores_mean - test_scores_std,test_scores_mean + test_scores_std, alpha=0.1, color="g")
plt.plot(train_sizes, train_scores_mean, 'o-', color="r", label="Training score")
plt.plot(train_sizes, test_scores_mean, 'o-', color="g", label="Cross-validation score")
plt.legend(loc="best")
return plt
title = "Learning Curves (Linear Regression)"
estimator = linear_model.LinearRegression()
plot_learning_curve(estimator, title, X_train, Y_train)
plt.show()