<jupyter_start><jupyter_text>This is a very basic Numpy TutorialIn Python the [Numpy Library](https://numpy.org/devdocs/user/index.html), is used in mathematical, scientific, engineering, and data science programming.Numpy has a selection fo special libraries for: Linear Algebra and Matrix Algebra, Statistics, Fast Fourier Transforms, among others.<jupyter_code># Load into memory all libraries to be used 
# We import NumPy and use np as a reference to it.
# Also the graphics library Matplotlib is loaded, and plt as a reference.
import numpy as np
import matplotlib.pyplot as plt

# Use SHIFT+ENTER to process input cell<jupyter_output><empty_output><jupyter_text>Use of elementary mathematical functions. Example of use of trigonometric functions:$\sin(x)$, $\cos(x)$, $\tan(x)$,... The number $\pi$ is defined in numpy.Also $x$ will be defined as an array of values: $0, \pi/4, \pi/2, 3 \pi/4, \pi$(**Note**: Jupyter Notebooks accepts LaTEX mathematical notation)<jupyter_code># x is an array of 5 points, 
x = np.array([0, np.pi/4, np.pi/2, 3*np.pi/4, np.pi])
y = np.sin(x)
print('x=', x, '\n', 'y=', y)
# the \n is newline printing command
# We use the following code to plot this function with a grid 
# We don't need to understad all the code at this point.

fig, ax = plt.subplots()
ax.plot(x, y)

ax.set(xlabel='x', ylabel='y',
       title='A simple $\sin(x)$ plot')
ax.grid()

#fig.savefig("test.png")
plt.show()<jupyter_output><empty_output><jupyter_text>Not a beautiful plot. The *x* array has only 5 points.So we use the *np.arange* function.*numpy.arange(start, stop, step)*. **Note:** The arange does not include last point.<jupyter_code># Redefine the x array with 20 points, therefore we recompute y.
x=np.arange(0, np.pi, np.pi/20)
y = np.sin(x)
x
# We reuse the plotting code
# We use the following code to plot this function
# We don't need to understad all the code at this point.

fig, ax = plt.subplots()
ax.plot(x, y)

ax.set(xlabel='x', ylabel='y',
       title='A more refined $\sin(x)$ plot')
ax.grid()

#fig.savefig("test.png")
plt.show()<jupyter_output><empty_output><jupyter_text>If we want to include the endpoint in the *x* array, there is another function*numpy.linspace(start, stop, num, endpoint)*<jupyter_code># Redefine the x array with 20 points, therefore we recompute y.
# A second function z=cos(2x) is added
x=np.linspace(0, np.pi, num=20, endpoint=True)
y = np.sin(x)
z = np.cos(2*x)
x

# We reuse the plotting code
# We use the following code to plot this function
# We don't need to understad all the code at this point.

fig, ax = plt.subplots()
ax.plot(x, y)
ax.plot(x, z) # Added a second plot

ax.set(xlabel='x', ylabel='y',
       title='A $\sin(x)$ and $\cos(2 x)$ plot')
ax.grid()

#fig.savefig("test.png")
plt.show()<jupyter_output><empty_output><jupyter_text>Similar applies to:*   **Basic functions:**  x**2, np.pow(x,n), np.sqrt(x), np.abs(x), np.max(x), np.min(x), ...*   **Exponential and logarithmic functions:** np.$\exp(x)$, np.$\log(x)$, np.${\log}{10(x)}$, ...*   **hyperbolic functions:** np.$\sinh(x)$, np.$\cosh(x)$, np.$\tanh(x)$, ... For more Numpy information and examples, please visit the [NumPy Tutorial](https://numpy.org/devdocs/user/quickstart.html) and the user guide on [mathematical functions](https://numpy.org/doc/stable/reference/routines.math.html).  Basic Statistics **Numpy also provides statistical functions.**With the [Statistics package](https://numpy.org/doc/stable/reference/routines.statistics.html), includes the common functions: weighted average, arithmetic mean, median, standard deviation, variance and others.<jupyter_code># Uniform random number generator [0, 1), between 0 and 1, excluding 1. 
rng = np.random.default_rng()

# Produce 1 random number
x1 = rng.random()
x1

# Produce an arrar of 5 random numbers
x5 = rng.random((5,)) 
x5
# Produce a random 3 rows and 2 columns array, with random values between -1 and 1.
x23 = rng.random((3, 2)) - 1
x23
# Compute the mean, std dev and median
x5_mean = np.mean(x5)
x5_std = np.std(x5)
x5_median = np.median(x5)
print('x5 mean = ', x5_mean, ', stddev = ', x5_std, ', median = ', x5_median)<jupyter_output>x5 mean =  0.41119136566975933 , stddev =  0.2596956032241648 , median =  0.3777002771870772<jupyter_text>**Note:** Python starts counting at 0. So the x23 array, has rows 0,1,2 and columns 0,1. We show how to extract information from a multidimensional array.<jupyter_code># To extract second column (i.e. column 1), we type
x23[:,1]
# where the : symbol means all rows
# To extract the third row (i.e. row 1), we type
x23[2,:]
# where the : symbol means all colun¡mns in this case
# To extract a specific value, for example third row and second column
x23[2,1]<jupyter_output><empty_output><jupyter_text>**Plotting a histogram**<jupyter_code># Will use a pseudorandom generator 
rng = np.random.default_rng()
# Generate 200 random numbers of a Standard Gaussian distribution.
a = rng.standard_normal(200)
# Plot the histogram using Matplotlib hist function 
_ = plt.hist(a, bins='auto', facecolor='steelblue', alpha=0.75)
plt.grid(True)
plt.xlabel('Values')
plt.ylabel('Frequency')
plt.title('Histogram of Normal Distribution')
plt.show()<jupyter_output><empty_output><jupyter_text>**Linear Regression (Least squares fit)**Lets design an artificial set of (x,y) values, simulating a random distributed set of points along a line. Numpy has a Least Squares fit function in its Linalg library.<jupyter_code># Construct the experimental data
# The y values are distributed along a straight line of slope 2 with +/- 5 error.

x = np.linspace(0, 10, num=20, endpoint=True)
y = 2*x + 5*rng.random((20,))
y<jupyter_output><empty_output><jupyter_text>The least squares problem can be writen as$y = \mathbf{A} p$, where $\mathbf{A} = [[x \ \ 1]]$ is the matrix composed by the x values and 1 values. And  $p = m,c$, is the constant parameter matrix where $m$ is the slope of the fitted line, and $c$ is the intersection point at $x=0$.<jupyter_code># We construct an array of array and transpose it.
# This would be our experimental data sample.
A = np.vstack([x, np.ones(len(x))]).T
A
# We call the lstsq function from the Linear Algebra library of Numpy to solve for m and c. 
m, c = np.linalg.lstsq(A, y, rcond=None)[0]
print('Linear fit: Slope m = ', m, ', and intersection point c = ', c)

# Plot the Least squares linear fit
_ = plt.plot(x, y, 'o', label='Original data', markersize=6)
_ = plt.plot(x, m*x + c, 'r', label='Fitted line')
_ = plt.legend()
plt.grid(True)
plt.xlabel('x')
plt.ylabel('Value')
plt.title('Least squares fit')
plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13687066626469702, 'fraction_numerical': 0.023967440458245403, 'mean_word_length': 4.769565217391304, 'pattern_counts': {'":': 0, '<': 36, '<?xml version=': 0, '>': 36, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '9', 'dir': 'jupyter-structured-clean-dedup', 'id': '473420', 'license': 'CC0-1.0', 'n_tokens_mistral': 2404, 'n_tokens_neox': 2269, 'n_words': 802, 'path': 'NumPy_BasicTutorial.ipynb', 'repo_name': 'clizarraga-UAD7/Notebooks', 'size': '6634'}