Notebook Articles

Take notes and save or share what you have learned

Articles: 586

Calculer la moyenne et la déviation standard d'un échantillon avec python

Pour calculer la moyenne et la déviation standard d'un échantillon avec python on peut utiliser numpy avec les fonctions [numpy.mean](https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.mean.html) et [numpy.std](https://docs.scipy.org/doc/numpy-1.14.2/reference/generated/numpy.std.html) respectivement. Pour tester, considérons un ensemble de nombres aléatoires générés depuis une distribution gaussienne avec comme vrai moyenne (mu = 10) et déviation standard (sigma = 2.0): >>

How to calculate the mean and standard deviation of a sample in python ?

From a sample of data stored in an array, a solution to calculate the mean and standrad deviation in python is to use numpy with the functions [numpy.mean](https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.mean.html) and [numpy.std](https://docs.scipy.org/doc/numpy-1.14.2/reference/generated/numpy.std.html) respectively. For testing, let generate random numbers from a normal distribution with a true mean (mu = 10) and standard deviation (sigma = 2.0:) >>> import numpy as n

How to extract html color codes (hex codes) from a seaborn palette ?

To extract html color codes from a seaborn palette, a solution is to use the method as_hex(): [image:seaborn-blue-color-palettes-25-0 size:50 caption:How to extract html color codes (hex codes) from a seaborn palette ?] >>> import seaborn as sns >>> pal = sns.color_palette("Blues") >>> print(pal.as_hex()) returns ['#dbe9f6', '#bad6eb', '#89bedc', '#539ecd', '#2b7bba', '#0b559f'] Hexadecimal code can be then be use in a matplotlib figure fro example: [image:extract

Extraire le code couleur html (hexadécimal) d'une palette seaborn avec python ?

Il est possible d'extraire le code couleur html (hexadécimal) d'une palette seaborn en utilisant la méthode as_hex() [image:seaborn-blue-color-palettes-25-0 size:50 caption:Comment extraire le code couleur html (hexadécimal) d'une palette seaborn avec python ?] >>> import seaborn as sns >>> pal = sns.color_palette("Blues") >>> print(pal.as_hex()) donne ['#dbe9f6', '#bad6eb', '#89bedc', '#539ecd', '#2b7bba', '#0b559f'] On peut alors utiliser ces codes dans une figure

Comment intégrer une distribution (gaussienne) normale simple avec python ?

Exemple de comment intégrer une distribution (gaussienne) normale simple avec python en utilisant [quad](https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.quad.html): [image:integrate-normal-distribution size:50 caption:Comment intégrer une distribution (gaussienne) normale simple avec python ?] from scipy.integrate import quad import matplotlib.pyplot as plt import scipy.stats import numpy as np #-------------------------------------------------------------

How to integrate a simple normal distribution in python ?

To integrate a simple normal distribution in python, a solution is to use [quad](https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.quad.html), example: [image:integrate-normal-distribution size:50 caption:How to integrate a normal distribution in python ?] from scipy.integrate import quad import matplotlib.pyplot as plt import scipy.stats import numpy as np #----------------------------------------------------------------------------------------# # Normal

How to integrate a function using python ?

To integrate a function using python, a solution is ti use the scipy method quad. Example, let's try to integrate the function \begin{equation} f: x\rightarrow cos(x) \end{equation} between $0$ andt $\frac{9\pi}{2}$. from scipy.integrate import quad import numpy as np xmin = 0.0 xmax = 9.0 * ( np.pi / 2.0 ) def function(x): return np.cos(x) res, err = quad(function, xmin, xmax) print 'norm: ', res Example using matplotlib [image:389 size:50 capti

How to perform a numerical integration using python ?

To do a numerical integration with python, a solution is to use the trapezoidal rule from numpy [numpy.trapz](https://docs.scipy.org/doc/numpy/reference/generated/numpy.trapz.html) or the Simpson's rule from scipy [scipy.integrate.simps](https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.simps.html): Note: to do an integration from a known function see the scipy method called [quad](/Articles/How-to-integrate-a-function-using-python-/) from scipy.integrate import simps

How to plot a normal distribution with matplotlib in python ?

Example of python code to plot a normal distribution with matplotlib: [image:normal-distribution-1 size:50 caption:How to plot a normal distribution with matplotlib in python ?] import matplotlib.pyplot as plt import scipy.stats import numpy as np x_min = 0.0 x_max = 16.0 mean = 8.0 std = 2.0 x = np.linspace(x_min, x_max, 100) y = scipy.stats.norm.pdf(x,mean,std) plt.plot(x,y, color='coral') plt.grid() plt.xlim(x_min,x_max) plt.ylim(0,0.25) plt

Courbe ROC pour tester la performance d'une classification discrète avec python

Analyse R.O.C (receiver operating characteristic) pour tester la performance d'une classification discrète en utilisant le python. [TOC] ### Introduction Question de départ: pour un x donné, est-ce qu'il appartient à la population A ou non ? Soit une simple classification définie par un seuil (par exemple $x_s = 10$), si $x >= x_s$ $x \in A$ si $x < x_s$ alors $x \notin A$ [images:roc-curve-discrete-classifier-01;roc-curve-discrete-classifier-02 dim:1*2 size:100 caption:Courbe R.O.C

How to add (insert) a new element in a tuple with python ?

Tuples are immutable, to add a new element it is necessary to create a new tuple by concatenating multiples tuples or transform it to a list, examples: Let's consider the following tuple: >>> t = ('Ben',34,'Lille') ### Add an element at the end: >>> t = t + ('Computer Scientist',) >>> t ('Ben', 34, 'Lille', 'Computer Scientist') Note: do not forget the comma ('Computer Scientist',) if not it is a string and not a tuple ! ### Add an element at the beginning:

Comment ajouter un élément à un tuple en python ?

Contrairement à une liste, un tuple est une séquence d'élément(s) qui ne peut pas être modifiée directement. Par contre il est possible de concatener plusieurs tuples (c.a.d créer un nouveau tuple) ou de transformer un tuple en liste et le reconvertir ensuite en tuple, exemples: Soit le tuple suivant: >>> t = ('Ben',34,'Lille') ### Ajouter un élément à la fin: >>> t = t + ('Computer Scientist',) >>> t ('Ben', 34, 'Lille', 'Computer Scientist') Note: attention à n

How to change the font size of the title in a matplotlib figure ?

To change the font size of the title in a matplotlib figure, use the parameter fontsize: title('mytitle', fontsize=8) [image:487 size:50 caption:How to change the font size of the title in a matplotlib figure ?] #!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) x = np.arange(-4,8,0.1) y = 6.0 / ( 1.0 + np.exp(-0.6*x) ) line, = plt.plot(x, y, '--', linewidth=2) ax.grid(True) plt.title('

How to sort a list of tuples by a given element in python ?

Let's consider a list of tuples generated randomly: >>> import random >>> l = [(random.randint(0, 100),random.randint(0, 100)) for i in range(10)] >>> l [(69, 38), (92, 75), (37, 89), (64, 52), (70, 72), (84, 44), (13, 0), (20, 67), (38, 56), (40, 98)] to sort the list by the first tuple element, a solution is to use [sorted()](https://docs.python.org/3.4/library/functions.html#sorted): >>> sorted(l) [(13, 0), (20, 67), (37, 89), (38, 56), (40, 98), (64, 52),

Comment trier une liste de tuple par rapport à un élément donnée en python ?

Considérons une liste de tuple générée aléatoirement, comme dans cet exemple: >>> import random >>> l = [(random.randint(0, 100),random.randint(0, 100)) for i in range(10)] >>> l [(69, 38), (92, 75), (37, 89), (64, 52), (70, 72), (84, 44), (13, 0), (20, 67), (38, 56), (40, 98)] pour trier la liste par rapport au premier élément, on peut directement appliquer [sorted()](https://docs.python.org/3.4/library/functions.html#sorted): >>> sorted(l) [(13, 0), (20, 67

Create random numbers from a normal distribution with numpy in python ?

### Standard Normal Distribution Example of python code to generate random numbers from a standard normal distribution and how to plot a normal distribution using matplotlib: [image:numpy-random-numbers-stantard-normal-distribution size:50 caption:Create random numbers from a standard normal distribution with numpy in python] import numpy as np import matplotlib.pyplot as plt data = np.random.randn(100000) hx, hy, _ = plt.hist(data, bins=50, normed=1,color="lightblue") pl

How to create a list using if ... else in python ?

To create a list in python, a solution is to use list comprehension, example: >>> l = [i for i in range(10)] >>> l [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Now, it is also possible to add a if ... else condition: >>> l = [-1 if i < 5 else 1 for i in range(10)] >>> l [-1, -1, -1, -1, -1, 1, 1, 1, 1, 1] ### References Links | Site ------------- | ------------- [if/else in Python's list comprehension?](https://stackoverflow.com/questions/4260280/if-else-in-

Comment créer une liste avec une condition if ... else sous python ?

Pour créer une liste avec python on peut procéder comme ceci: >>> l = [i for i in range(10)] >>> l [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Maintenant on peut aussi ajouter une condition if ... else comme dans cet exemple >>> l = [-1 if i < 5 else 1 for i in range(10)] >>> l [-1, -1, -1, -1, -1, 1, 1, 1, 1, 1] ### Références Liens | Site ------------- | ------------- [if/else in Python's list comprehension?](https://stackoverflow.com/questions/4260280/if

How to calculate and plot the derivative of a function using matplotlib and python ?

To calculate the derivative of a function f at a given point x, a solution with python is to use the scipy function called [derivative](http://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.derivative.html). Let's consider the following function: $f(x)=x^2$ quand x=2. [image:147 size:50 caption:How to calculate and plot the derivative of a function using matplotlib and python ?] >>> from scipy import misc >>> >>> def fonction(x): ... return x*x ...

Implémenter une régression linéaire polynomiale avec scikit-learn et python 3

Pour calculer une régression linéaire polynomiale avec python, il existe le module [scikit-learn](http://scikit-learn.org/stable/index.html), exemple: [image:polynomial-linear-regression size:50 caption:Implémenter une régression linéaire polynomiale avec scikit-learn et python 3] from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures from sklearn.metrics import mean_squared_error, r2_score import matplotlib.pyplot as plt impo

How to get the length of a string in a template with Django ?

To get the length of a string in a template with Django, a solution is to use the filter [length](https://docs.djangoproject.com/en/2.1/ref/templates/builtins/#length): {{ value|length }} Example: {{ title|slice:":35" }} {% if title|length > 35 %}...{% endif %} returns with title = "Mon titre est tres tres tres longgggg" Mon titre est tres tres tres longgg ... ### References Links | Site ------------- | ------------- [filter length](https://docs.djangoproject.

How to implement a polynomial linear regression using scikit-learn and python 3 ?

To perform a polynomial linear regression with python 3, a solution is to use the module called [scikit-learn](http://scikit-learn.org/stable/index.html), example of implementation: [image:polynomial-linear-regression size:50 caption:How to implement a polynomial linear regression using scikit-learn and python 3 ?] from sklearn.linear_model import LinearRegression from sklearn.preprocessing import PolynomialFeatures from sklearn.metrics import mean_squared_error, r2_score imp

How to transform (convert) a list to an array in python ?

In python, to convert a list to an array, a solution is to use the numpy function called [asarray()](http://docs.scipy.org/doc/numpy/reference/generated/numpy.asarray.html), example: >>> l = [4,1,7,3,2] >>> type(l) <type 'list'> >>> import numpy as np >>> A = np.asarray(l) >>> A array([4, 1, 7, 3, 2]) >>> type(A) <type 'numpy.ndarray'> >>> len(l) 5 >>> A.shape (5,) >>> A.dtype dtype('int32') Note: To change the shape

How to implement a simple linear regression using scikit-learn and python 3 ?

To perform a simple linear regression with python 3, a solution is to use the module called [scikit-learn](http://scikit-learn.org/stable/index.html), example of implementation: [image:553 size:50 caption:How to implement a simple linear regression using scikit-learn and python 3 ?] from sklearn import linear_model import matplotlib.pyplot as plt import numpy as np import random #----------------------------------------------------------------------------------------# # Step

Obtenir la taille d'une chaîne de caractères dans un template avec Django

Pour obtenir la taille d'une chaîne de caractères dans un template avec Django il existe le filtre [length](https://docs.djangoproject.com/en/2.1/ref/templates/builtins/#length): {{ value|length }} Exemple d'utilisation: {{ title|slice:":35" }} {% if title|length > 35 %}...{% endif %} donne avec title = "Mon titre est tres tres tres longgggg" Mon titre est tres tres tres longgg ... ### Références Liens | Site ------------- | ------------- [filter length](https

About


An article helps to save or share information. After creating an article it is possible to add multiple authors and manage the permissions

Create an article

Search


Use the following form to retrieve an article: