Skip to content

Commit 9fd42b4

Browse files
authored
Merge pull request #1 from jetbrains-academy/sofia/random
Sofia/random
2 parents 139d405 + eced588 commit 9fd42b4

File tree

13 files changed

+206
-0
lines changed

13 files changed

+206
-0
lines changed

Numpy/Array Basics/Random Sampling/__init__.py

Whitespace-only changes.
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
type: edu
2+
files:
3+
- name: task.py
4+
visible: true
5+
placeholders:
6+
- offset: 58
7+
length: 23
8+
placeholder_text: '# TODO'
9+
- offset: 137
10+
length: 27
11+
placeholder_text: '# TODO'
12+
- offset: 95
13+
length: 6
14+
placeholder_text: '# TODO'
15+
- name: tests/test_task.py
16+
visible: false
17+
- name: __init__.py
18+
visible: false
19+
- name: tests/__init__.py
20+
visible: false
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
## Random Sampling
2+
3+
Sometimes you might need to fill an array with random numbers or sample them from
4+
different statistical distributions.
5+
Numpy's `random` module allows you to do this. It is a suite of functions based on
6+
pseudorandom number generation. It is called pseudorandom because "random" means something that
7+
can not be predicted logically, and if a program generates a "random" number
8+
it can be predicted, thus it is not truly random.
9+
10+
The function `numpy.random.random` returns random floats in the half-open interval `[0.0, 1.0)`:
11+
12+
```python
13+
a = np.random.random(5)
14+
print(a)
15+
```
16+
Output:
17+
```text
18+
[0.73719247 0.38265166 0.48330973 0.27551432 0.88136674]
19+
```
20+
21+
### Random Generator
22+
Call [`default_rng`](https://numpy.org/doc/stable/reference/random/generator.html#numpy.random.default_rng)
23+
to get a new instance of a [`Generator`](https://numpy.org/doc/stable/reference/random/generator.html#numpy.random.Generator),
24+
then call its methods to obtain samples from different distributions.
25+
```python
26+
rng = np.random.default_rng()
27+
a = rng.integers(1000) # Randomly pick one integer from 0 to 1000
28+
print(a)
29+
```
30+
Output:
31+
```text
32+
346
33+
```
34+
`random.Generator.integers` returns random integers from a half-open interval: low (inclusive) to high (exclusive),
35+
or if you specify `endpoint=True`, then the interval is closed: low (inclusive) to high (inclusive).
36+
Integers are returned from the "discrete uniform" distribution.
37+
38+
Print 10 random integers from the interval `[0, 2)`:
39+
40+
```python
41+
print(rng.integers(2, size=10))
42+
```
43+
Output:
44+
```text
45+
[1 1 0 1 0 0 0 1 0 0]
46+
```
47+
Generate a 2 x 4 array of integers between `0` and `4`, inclusive:
48+
```python
49+
print(rng.integers(4, size=(2, 4), endpoint=True))
50+
```
51+
Equivalent to:
52+
```python
53+
print(rng.integers(5, size=(2, 4)))
54+
```
55+
Output:
56+
```text
57+
[[1 2 0 3]
58+
[4 2 4 3]]
59+
```
60+
61+
### Task
62+
Using the function [`numpy.random.Generator.normal`](https://numpy.org/doc/stable/reference/random/generated/numpy.random.Generator.normal.html?highlight=random%20normal#numpy.random.Generator.normal),
63+
draw 1000 samples from the normal distribution with mean equal to `1` and standard deviation equal to `0.5`.
64+
You can visualize your sample and make sure the mean and variance are ok by running the script – we predefined the
65+
code for that in the `if __name__ == '__main__':` block.
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import numpy as np
2+
import matplotlib.pyplot as plt
3+
4+
rng = np.random.default_rng()
5+
6+
mu, sigma = 1, 0.5 # Mean and standard deviation
7+
s = rng.normal(mu, sigma, 1000)
8+
9+
10+
if __name__ == '__main__':
11+
# Verify the mean and the variance:
12+
print(abs(mu - np.mean(s))) # Difference should be close to 0.0
13+
print(abs(sigma - np.std(s, ddof=1))) # Difference should be close to 0.0
14+
15+
count, bins, ignored = plt.hist(s, 30, density=True)
16+
plt.plot(bins, 1 / (sigma * np.sqrt(2 * np.pi)) *
17+
np.exp(- (bins - mu) ** 2 / (2 * sigma ** 2)),
18+
linewidth=2, color='r')
19+
plt.show()
20+

Numpy/Array Basics/Random Sampling/tests/__init__.py

Whitespace-only changes.
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import unittest
2+
import numpy as np
3+
4+
from task import *
5+
6+
7+
class TestCase(unittest.TestCase):
8+
def test_normal(self):
9+
self.assertEqual(s.shape, (1000,), msg="Draw 1000 samples")
10+
self.assertEqual(round(abs(mu - np.mean(s)), 1), 0.0, msg="Mean should be close to 0.0")
11+
self.assertEqual(round(abs(sigma - np.std(s, ddof=1)), 1), 0.0, msg="Variance should be close to 0.0")
12+

Numpy/Array Basics/Reshape/__init__.py

Whitespace-only changes.
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
type: edu
2+
files:
3+
- name: task.py
4+
visible: true
5+
placeholders:
6+
- offset: 24
7+
length: 20
8+
placeholder_text: '# TODO'
9+
- offset: 49
10+
length: 15
11+
placeholder_text: '# TODO'
12+
- name: tests/test_task.py
13+
visible: false
14+
- name: __init__.py
15+
visible: false
16+
- name: tests/__init__.py
17+
visible: false

Numpy/Array Basics/Reshape/task.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
## Reshape
2+
3+
Reshaping means changing the `shape` of an array without changing its data.
4+
As we mentioned earlier, the `shape` of an array is the number of elements in each dimension.
5+
By reshaping we can add or remove dimensions or change the number of elements in each dimension.
6+
7+
The function [`numpy.reshape`](https://numpy.org/doc/stable/reference/generated/numpy.reshape.html#numpy.reshape)
8+
is used for reshaping, and it accepts three arguments:
9+
10+
- The array to be reshaped.
11+
- The new shape as an `int` or tuple of `int`s.
12+
- An optional argument `order`, which defines the order in which the elements are read and placed into the reshaped array.
13+
14+
### Examples
15+
1. Reshape 1D array into a 2D array:
16+
```python
17+
a = np.arange(10)
18+
print(np.reshape(a, (2, 5)))
19+
```
20+
Output:
21+
```text
22+
[[0 1 2 3 4]
23+
[5 6 7 8 9]]
24+
```
25+
2. Reshape a 2D array into a 1D array:
26+
```python
27+
a = np.array([[1, 2, 3], [4, 5, 6]])
28+
print(np.reshape(a, 6))
29+
```
30+
Output:
31+
```text
32+
[1 2 3 4 5 6]
33+
```
34+
35+
The latter can also be achieved by using `numpy.ndarray.flatten`:
36+
```python
37+
a = np.array([[1, 2, 3], [4, 5, 6]])
38+
print(a.flatten())
39+
```
40+
Output:
41+
```text
42+
[1 2 3 4 5 6]
43+
```
44+
45+
### Task
46+
1. Create an array `a` of integers in the interval from `12` to `30` with step `3`.
47+
2. Reshape it so that it has 2 rows and 3 columns.
48+
49+
<div class="hint">For (1) you can use the <code>arange</code> function.</div>

Numpy/Array Basics/Reshape/task.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import numpy as np
2+
3+
a = np.arange(12, 30, 3)
4+
b = a.reshape(2, 3)
5+
6+
if __name__ == "__main__":
7+
print(a)
8+
print('shape : ', a.shape)
9+
print('\nAfter reshaping : ')
10+
print(b)
11+
print('shape : ', b.shape)

0 commit comments

Comments
 (0)