Skip to content

Commit

Permalink
Correction du TP numpy (#419)
Browse files Browse the repository at this point in the history
* clean file

* Remove contextily
  • Loading branch information
linogaliana committed Oct 4, 2023
1 parent 5ab34aa commit a63319a
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 24 deletions.
66 changes: 44 additions & 22 deletions content/manipulation/01_numpy.qmd
Expand Up @@ -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
---


Expand Down Expand Up @@ -45,17 +46,19 @@ 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
```

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)
```

Expand Down Expand Up @@ -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")
```

Expand All @@ -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)
```

Expand All @@ -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)
Expand All @@ -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)
```
Expand Down Expand Up @@ -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]
```
Expand Down Expand Up @@ -273,7 +293,7 @@ Prenez `x = np.arange(10)` et...


```{python}
#| include: false
#| output: false
# Correction
x[[0,3,5]]
Expand Down Expand Up @@ -315,13 +335,15 @@ 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)
print(x2)
```

```{python}
#| echo: true
x==2
x2<0
```
Expand Down Expand Up @@ -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)
Expand All @@ -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])
```

Expand All @@ -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))
Expand All @@ -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}
Expand All @@ -467,7 +492,7 @@ L'appliquer sur `x` en jouant avec l'argument axis


```{python}
#| include: false
#| output: false
# Correction
print(x)
Expand All @@ -480,7 +505,7 @@ print(x.sum(axis = 1).sum())
```

```{python}
#| include: false
#| output: false
# Correction
Expand Down Expand Up @@ -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)
Expand All @@ -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)
```

Expand All @@ -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])
Expand Down Expand Up @@ -628,8 +657,7 @@ for i in range(X.shape[0]):


```{python}
#| include: false
#| echo: false
#| output: false
# Correction
Expand All @@ -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)
Expand All @@ -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)
Expand Down Expand Up @@ -753,7 +779,7 @@ sur votre matrice.
:::

```{python}
#| echo: false
#| output: false
# Question 1
M = np.array([[0, 0, 0, 0, 1],
Expand All @@ -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)
Expand All @@ -775,8 +800,6 @@ plt.savefig("scatter_numpy.png", bbox_inches = "tight")


```{python}
#| echo: false
"""PageRank algorithm with explicit number of iterations.
Returns
Expand Down Expand Up @@ -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
```

Expand Down
4 changes: 2 additions & 2 deletions content/manipulation/04c_API_TP.qmd
Expand Up @@ -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
```

Expand All @@ -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')
Expand Down

0 comments on commit a63319a

Please sign in to comment.