From a63319ad445b0c0bf7f9c860aaa68541c4d1639d Mon Sep 17 00:00:00 2001 From: Lino Galiana Date: Wed, 4 Oct 2023 15:29:04 +0200 Subject: [PATCH] Correction du TP numpy (#419) * clean file * Remove contextily --- content/manipulation/01_numpy.qmd | 66 +++++++++++++++++++---------- content/manipulation/04c_API_TP.qmd | 4 +- 2 files changed, 46 insertions(+), 24 deletions(-) diff --git a/content/manipulation/01_numpy.qmd b/content/manipulation/01_numpy.qmd index 500f26b6c..3ca3f333a 100644 --- a/content/manipulation/01_numpy.qmd +++ b/content/manipulation/01_numpy.qmd @@ -18,6 +18,7 @@ description: | Il est donc indispensable de revoir quelques notions sur ce package avant d'aller plus loin. image: scatter_numpy.png +echo: false --- @@ -45,10 +46,11 @@ la [cheatsheet numpy](https://www.datacamp.com/community/blog/python-numpy-cheat sur une fonction. Dans ce chapitre, on ne dérogera pas à la convention qui s'est imposée -d'importer `numpy` de la +d'importer `Numpy` de la manière suivante : ```{python import np} +#| echo: true import numpy as np ``` @@ -56,6 +58,7 @@ Nous allons également fixer la racine du générateur aléatoire de nombres afin d'avoir des résultats reproductibles : ```{python} +#| echo: true np.random.seed(12345) ``` @@ -132,12 +135,14 @@ On peut créer un `array` de plusieurs manières. Pour créer un `array` à part il suffit d'utiliser la méthode `array`: ```{python} +#| echo: true np.array([1,2,5]) ``` Il est possible d'ajouter un argument `dtype` pour contraindre le type du *array*: ```{python} +#| echo: true np.array([["a","z","e"],["r","t"],["y"]], dtype="object") ``` @@ -149,32 +154,47 @@ Il existe aussi des méthodes pratiques pour créer des array: * séquences aléatoires: fonctions de génération de nombres aléatoires: `np.rand.uniform`, `np.rand.normal`, etc. * tableau sous forme de matrice identité: `np.eye` +Ceci donne ainsi, pour les séquences logiques: ```{python} +#| echo: true np.arange(0,10) ``` ```{python} +#| echo: true np.arange(0,10,3) ``` ```{python} +#| echo: true np.linspace(0, 1, 5) ``` +Pour un _array_ initialisé à 0: + ```{python} +#| echo: true np.zeros(10, dtype=int) ``` +ou initialisé à 1: + ```{python} +#| echo: true np.ones((3, 5), dtype=float) ``` +ou encore initialisé à 3.14: + ```{python} np.full((3, 5), 3.14) ``` +Enfin, pour créer la matrice $I_3$: + ```{python} +#| echo: true np.eye(3) ``` @@ -198,9 +218,7 @@ Générer: ```{python} -#| include: false - -# Correction +#| output: false X = np.random.uniform(0,1,1000) Y = np.random.normal(0,np.sqrt(2),1000) @@ -214,6 +232,7 @@ np.var(Y) La structure la plus simple est l'_array_ unidimensionnel: ```{python} +#| echo: true x = np.arange(10) print(x) ``` @@ -245,6 +264,7 @@ x[K-1] Pour sélectionner uniquement un élément, on fera ainsi: ```{python} +#| echo: true x = np.arange(10) x[2] ``` @@ -273,7 +293,7 @@ Prenez `x = np.arange(10)` et... ```{python} -#| include: false +#| output: false # Correction x[[0,3,5]] @@ -315,6 +335,7 @@ Ces comparaisons fonctionnent aussi sur les tableaux multidimensionnels grâce a *broadcasting* sur lequel nous reviendrons : ```{python} +#| echo: true x = np.arange(10) x2 = np.array([[-1,1,-2],[-3,2,0]]) print(x) @@ -322,6 +343,7 @@ print(x2) ``` ```{python} +#| echo: true x==2 x2<0 ``` @@ -356,7 +378,7 @@ et rapportez les à la somme des valeurs de `x` (en valeur absolue) ```{python} -#| include: false +#| output: false # Correction x = np.random.normal(size=10000) @@ -381,12 +403,14 @@ Parmi elles, on peut retrouver: Soit ```{python} +#| echo: true x = np.random.normal(0, size=(3, 4)) ``` un *array* multidimensionnel et ```{python} +#| echo: true y = np.array([np.nan, 0, 1]) ``` @@ -413,7 +437,7 @@ Note : Jetez un oeil à ce que correspond le paramètre `axis` dans `numpy` en v ```{python} -#| include: false +#| output: false # Correction x = np.random.normal(0, size=(3, 4)) @@ -438,13 +462,14 @@ print(np.any(x>0, axis = 1)) Dans cette section, on utilisera un array multidimensionnel: ```{python} +#| echo: true x = np.random.normal(0, size=(3, 4)) ``` -### Statistiques sur un array +### Statistiques sur un _array_ Pour les statistiques descriptives classiques, -`numpy` propose un certain nombre de fonctions déjà implémentées, +`Numpy` propose un certain nombre de fonctions déjà implémentées, qui peuvent être combinées avec l'argument `axis` ::: {.cell .markdown} @@ -467,7 +492,7 @@ L'appliquer sur `x` en jouant avec l'argument axis ```{python} -#| include: false +#| output: false # Correction print(x) @@ -480,7 +505,7 @@ print(x.sum(axis = 1).sum()) ``` ```{python} -#| include: false +#| output: false # Correction @@ -524,12 +549,14 @@ les fonctions `np.concatenate`, `np.vstack` ou la méthode `.r_` (concaténation `np.hstack` ou la méthode `.column_stack` ou `.c_` (concaténation *column-wise*) ```{python} +#| echo: true x = np.random.normal(size = 10) ``` Pour ordonner un array, on utilise `np.sort` ```{python} +#| echo: true x = np.array([7, 2, 3, 1, 6, 5, 4]) np.sort(x) @@ -538,6 +565,7 @@ np.sort(x) Si on désire faire un ré-ordonnement partiel pour trouver les _k_ valeurs les plus petites d'un `array` sans les ordonner, on utilise `partition`: ```{python} +#| echo: true np.partition(x, 3) ``` @@ -553,6 +581,7 @@ La différence peut être comprise à partir de l'exemple suivant. Le *broadcast de transformer le scalaire `5` en *array* de dimension 3: ```{python} +#| echo: true a = np.array([0, 1, 2]) b = np.array([5, 5, 5]) @@ -628,8 +657,7 @@ for i in range(X.shape[0]): ```{python} -#| include: false -#| echo: false +#| output: false # Correction @@ -645,8 +673,7 @@ plt.scatter(X[:, 0], X[:, 1], s=100) ```{python} -#| include: false -#| echo: false +#| output: false fig = plt.figure() plt.scatter(X[:, 0], X[:, 1], s=100) @@ -659,8 +686,7 @@ Pour la question 2, vous devriez obtenir un graphique ayant cet aspect : ![](scatter_numpy.png) ```{python} -#| include: false -#| echo: false +#| output: false # 3. Construire la matrice des distances euclidiennes print(X.shape) @@ -753,7 +779,7 @@ sur votre matrice. ::: ```{python} -#| echo: false +#| output: false # Question 1 M = np.array([[0, 0, 0, 0, 1], @@ -764,7 +790,6 @@ M = np.array([[0, 0, 0, 0, 1], ``` ```{python} -#| echo: false import networkx as nx G = nx.from_numpy_array(M) @@ -775,8 +800,6 @@ plt.savefig("scatter_numpy.png", bbox_inches = "tight") ```{python} -#| echo: false - """PageRank algorithm with explicit number of iterations. Returns @@ -822,7 +845,6 @@ Le site 1 est assez central car il est référencé 2 fois. Le site 5 est lui également central puisqu'il est référencé par le site 1. ```{python} -#| echo: false v ``` diff --git a/content/manipulation/04c_API_TP.qmd b/content/manipulation/04c_API_TP.qmd index 1e1505527..b0172570f 100644 --- a/content/manipulation/04c_API_TP.qmd +++ b/content/manipulation/04c_API_TP.qmd @@ -834,7 +834,7 @@ import contextily as ctx fig,ax = plt.subplots(figsize=(10, 10)) circle.to_crs("EPSG:3857").plot(ax = ax, color = 'red') pal.to_crs("EPSG:3857").plot(ax = ax, color = 'green') -ctx.add_basemap(ax, source = ctx.providers.Stamen.Toner) +#ctx.add_basemap(ax, source = ctx.providers.Stamen.Toner) ax ``` @@ -846,7 +846,7 @@ import contextily as ctx fig,ax = plt.subplots(figsize=(10, 10)) circle.to_crs("EPSG:3857").plot(ax = ax, color = 'red') pal.to_crs("EPSG:3857").plot(ax = ax, color = 'green') -ctx.add_basemap(ax, source = ctx.providers.Stamen.Toner) +#ctx.add_basemap(ax, source = ctx.providers.Stamen.Toner) ax plt.savefig('map_buffer.png', bbox_inches='tight')