Solucion-Parcial-.. - Jupyter Notebook
Solucion-Parcial-.. - Jupyter Notebook
- Jupyter Notebook
Provides the NumPy Array as an alternative to the regular Python List to execute element-wise (i.e. element by element)
operations among the elements of a sequence of numbers as well as execute arithmetic operators, such as +, -, * and /; and
relational operetions, such as >, <, == among vectors, matrices and tensors.
NumPy Array
In computer science an Array is a data structure (class) that stores values very much like lists, except that the type of objects
stored in them is constrained, that is, all of the elements should be of the same type. The biggest advantage of using an array is
that it can be used to store vectors, matrices and tensors; and therefore, we can execute element-wise operations and
vector/matrix operations using arrays.
The NumPy package provides a container for the array data structure, this is called the NumPy Array
(https://docs.scipy.org/doc/numpy-1.10.0/glossary.html#term-array). Arrays may have several dimensions; for example, a 1-
dimensional array (1D array) can be used to store a vector with the coordinates of a point in 3D space. In NumPy dimensions are
also called axes. A 2-dimensional array has two corresponding axes: the first running vertically downwards across rows (axis 0),
and the second running horizontally across columns (axis 1).
78382numpy_arrays.png
The compational representation of the vector is, 𝑎𝑟𝑟𝑎𝑦([7,2,9,10]) , it has just one axis. In addtion, this axis has 4 elements in it,
so we say it has a length of 4. In the next example, we want to store a matrix (2 dimensions) in an array, so the array has 2 axes.
The first axis (axis 0) has a length of 2, the second axis (axis 1) has a length of 3. This array has 6 components.
𝑀𝑎𝑡𝑟𝑖𝑥 : ∗𝑀𝑎𝑡ℎ𝑒𝑚𝑎𝑡𝑖𝑐𝑎𝑙𝑅𝑒𝑝𝑟𝑒𝑠𝑒𝑛𝑡𝑎𝑡𝑖𝑜𝑛
𝐴𝑚,𝑛 = [ 𝐴𝐴1121 𝐴𝐴1222 𝐴𝐴1323 ]
𝐸𝑥𝑎𝑚𝑝𝑙𝑒
5.2 3.0 4.5
[ 9.1 0.1 0.3 ]
∗𝐶𝑜𝑚𝑝𝑢𝑡𝑎𝑡𝑖𝑜𝑛𝑎𝑙𝑅𝑒𝑝𝑟𝑒𝑠𝑒𝑛𝑡𝑎𝑡𝑖𝑜𝑛
𝑎𝑟𝑟𝑎𝑦([[5.2,3.0,4.5],[9.1,0.1,0.3]])
Tensor - nD array
A tensor is an array of mathematical objects (usually numbers or functions) which transforms according to certain rules under
coordinates change. In an 𝑛𝐷 space (ex. 2D and 3D), a tensor of rank- has𝑘 𝑛𝑘 components which may be specified with
0
reference to a given coordinate system. Accordingly, a scalar, such as temperature, is a rank- tensor with (assuming a 3D space)
302 = 1 1 31 = 3
component, a vector, such as force, is a rank- tensor with components, and stress is a rank- tensor with 2
3 =9
components. So the rank is independent of the number of space dimensions (nD).
Notes: Stress is a physical quantity that expresses the internal forces that neighbouring particles of a continuous material exert on
each other
2
A very common structure is the rank- tensor, a 3x3 matrix which represents the map of one 3D thing into another 3D thing.
2
"General Relativity" uses a lot of rank- tensors in 4 dimensions of space time, represented by a 4x4 matrix.
In the next figure is graphically illustrated the structure of a rank-3 tensor in a 3D space. (Taken from Taha Sochi, Principles of
tensor calculus).
3-rank_tensor.png
localhost:8889/notebooks/Solucion-Parcial-Andres-Peña...ipynb# 1/11
16/4/23, 21:29 Solucion-Parcial-Andres-Peña.. - Jupyter Notebook
conv_rgb.png
RESPUESTA: Este tensor tiene tres ejes y cada eje tiene una longitud de 3
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
In [5]: #We want to check the dimensions of the previous vector and matrix
print(vector_object.ndim)
print(matrix_object.ndim)
1
2
It is expected that a vector has a dimension equals to 1, and a matrix a dimension equals to 2
(4,)
(2, 3)
localhost:8889/notebooks/Solucion-Parcial-Andres-Peña...ipynb# 2/11
16/4/23, 21:29 Solucion-Parcial-Andres-Peña.. - Jupyter Notebook
matrixmul.png
Element-wise multiplication
𝑐1 = 𝑎1 𝑏1
𝑐2 = 𝑎2 𝑏2
Matrix multiplication
𝑐1 = 𝑎1 𝑏1 + 𝑎2 𝑏4 + 𝑎3 𝑏7
𝑐2 = 𝑎1 𝑏2 + 𝑎2 𝑏5 + 𝑎3 𝑏8
𝑛
𝑐𝑖𝑗 = 𝑎𝑖1 𝑏1𝑗 + 𝑎𝑖2 𝑏2𝑗 + ⋯ + 𝑎𝑖𝑛 𝑏𝑛𝑗 = ∑ 𝑎𝑖𝑘 𝑏𝑘𝑗
𝑘=1
BMI = weight
height
kg
2 m
In [7]: #height is a list with the height of several people
height = [1.73, 1.56, 1.67, 1.69]
# mass or weight
weight = [80.3, 55.6, 65.5, 70.6]
#Let´s try to calculate the BMI for all of the people just by doing arithmetic operatorions between lists
BMI_calculation = weight / height **2
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[7], line 6
4 weight = [80.3, 55.6, 65.5, 70.6]
5 #Let´s try to calculate the BMI for all of the people just by doing arithmetic operatorions betwe
en lists
----> 6 BMI_calculation = weight / height **2
The output returns TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'
This means we are not able to do this calculation that way. Probably we will need to do something like this:
In [ ]: %%time
height = [1.73, 1.56, 1.67, 1.69]
# mass or weight
weight = [80.3, 55.6, 65.5, 70.6]
bmi_list = []
for i in range(4):
bmi_list.append(weight[i] / (height[i]**2))
print(bmi_list)
Array Concepts
localhost:8889/notebooks/Solucion-Parcial-Andres-Peña...ipynb# 3/11
16/4/23, 21:29 Solucion-Parcial-Andres-Peña.. - Jupyter Notebook
Vectorization
Vectorization efficiently applies operations to groups of elements. Using vectorization we can execute element-wise operations
Unlike lists, numpy arrays can execute element-wise operations, such as arithmetic (+,-,*,/) and relational (>,<,==,!=) operations
among arrays and even with numerical values.
In [ ]: %%time
height = [1.73, 1.56, 1.67, 1.69, 1.66]
# mass or weight
weight = [80.3, 55.6, 65.5, 70.6, 62]
#Create the arrays
height_array = np.array(height)
weight_array = np.array(weight)
#Aritmethic operarion between an array and a numerical value
square_height = height_array ** 2
#Arithmetic operation among arrays
bmi = weight_array / square_height
bmi
#print(bmi)
Indexing
Indexing an array returns single elements, subarrays or elements that satisfy a specific condition.
In [ ]: print(light)
In [ ]: print(bmi[light])
localhost:8889/notebooks/Solucion-Parcial-Andres-Peña...ipynb# 4/11
16/4/23, 21:29 Solucion-Parcial-Andres-Peña.. - Jupyter Notebook
In [ ]: print(B)
𝐶 = 𝐶𝑚,𝑛 = [ 𝐴𝐴1323 ] = [ 02 ]
In [ ]: C = np.array([A[0,2],A[1,2]])
In [ ]: print(C[0:,None])
In [ ]: print(C)
In [ ]: A = np.array([[1,0,0],[0,1,2]])
S = sum(A)
print(S)
Broadcasting
Let's explore the broadcasting in the element-wise multiplication of two-dimensional arrays.
𝐵∘𝐶
in code B * C .
localhost:8889/notebooks/Solucion-Parcial-Andres-Peña...ipynb# 5/11
16/4/23, 21:29 Solucion-Parcial-Andres-Peña.. - Jupyter Notebook
𝐵 ∘ 𝐶 = [1 0 ] ∘ [0]
In [ ]: print(B*C)
Matrix Multiplication
Let's explore a matrix multiplication
𝐵⋅𝐶
in code B @ C .
𝐵 ⋅ 𝐶 = [ 10 01 ][ 02 ]
In [ ]: print(B@C)
RESPUESTA: El BROADCASTING es la multiplicacion de elemento a elemento entre matrices y con arreglos multidimensionales
con diferentes dimensiones, lo cual nos quiere dar a entender que estas se multiplican elemento a elemento entre las filas y las
columnas teniendo asi una matriz con el numero de columnas de la primera y el numero de filas de la segunda. Por otro lado la
MULTIPLIACION DE MATRICES tiene que cumplir que el numero de las columnas de la primera matriz debe ser igual al numero
de filas de la segunda matriz, en el cual se determinara cada termino de la matriz con la multiplicacion y sumatoria de las filas y
columnas.
Test (80%):
We want to calculate the weighted grade (from 0 to 5) that gets a student who took several quizzes and did several projects during
an academic period. The number of quizzes and projects is variable. It's known that there are 3 academic periods in the semester.
The first one accounts for 35% of the final grade, the second one another 35%, and the third one the remaining 30%, for a total of
100%. However, in every academic period, projects weigh more than quizzes, at least in the first and second periods quizzes
weigh 10% and projects 25%, but these percentages can also be variables. Each quiz weighs the same, as well as each project
weighs the same too. Quizzes a projects grades are from 0 to 100.
Requirements:
1. The data must be modeled as a matrix, rows are students and colunms are the grades that got each student in each of the
quizzes and projects. Create an excel file to fill out a table with the grades of at least 3 students in order to test your program;
however, the solution must work for any number of students, and no matter how many quices and proyects a student took in a
academic period --- Read the excel file using pandas library and convert the data to numpy array.
2. The number of quizzes and projects are inputs as well as their percentage in an academic period. You may also create a table
in excel to read this data.
3. Define the variables for the problem and create a mathematical model for the solution. The model should have matrix and
vector operations.
4. Solve the problem using array arithmetic with numpy. Use vectorization instead of "for loops". In addition, you may use
broadcasting and matrix multiplications.
5. The output must be a column vector with weighted grades (from 0 to 5), where each element of the vector is the weighted
grade of each student.
6. Find the average grade for the course (all the students). Use the methods of the numpy array objects.
∗ ∗ 𝑆𝑂𝐿𝑈𝐶𝐼𝑂𝑁 ∗ ∗
localhost:8889/notebooks/Solucion-Parcial-Andres-Peña...ipynb# 6/11
16/4/23, 21:29 Solucion-Parcial-Andres-Peña.. - Jupyter Notebook
Entrada
Nn: Vector del numero de notas de proyectos y quices para los cortes
grades: Matriz de notas de quices, talleres y proyecto de 0 a 100 para los 3 cortes, para cada estudiante
Salida
V_grades: vector para las calificaciones ponderadas por estudiante (Estas van entre 0 y 5)
𝑀𝑂𝐷𝐸𝐿𝑂 − 𝑀𝐴𝑇𝐸𝑀𝐴𝑇𝐼𝐶𝑂
Variables: s = #estudiantes, n = #notas de proyectos y quices por corte, c = #corte
𝑝𝑛𝑛𝑞1
𝑃𝑜𝑟𝑐𝑒𝑛𝑡𝑎𝑗𝑒 − 𝑑𝑒 − 𝑁𝑜𝑡𝑎𝑠 = 𝑃 𝑁𝑛𝑐,1 = 𝑝𝑛...𝑛𝑝1
𝑝𝑛
𝑛𝑐
🔻
[ 𝑄111 𝑄121 𝑃111 𝑃121 𝑄211 𝑄221 𝑃211 𝑃221 𝑄311 𝑄321 𝑃311 𝑃321 𝑄112 𝑄122 𝑃112 𝑃122 𝑄212
🔻
𝑄111
𝑄121
𝑃𝑃111
𝑄122111
𝑃 𝑁12,1 = 𝑄𝑃 221
𝑃212211
𝑄311
𝑄321
𝑃311
𝑃321
🔻
𝑔1,𝑛𝑞1 𝑔1,𝑛𝑝1 .. 𝑔1,𝑛𝑞𝑐 𝑔1,𝑛𝑝𝑐
𝐺𝑟𝑎𝑑𝑒𝑠 = 𝐺𝑠,𝑛 = 𝑔2,𝑛𝑞. 1 𝑔2,𝑛𝑝. 1 .. 𝑔2,𝑛𝑞. 𝑐 𝑔2,𝑛𝑝. 𝑐
. . 𝑔𝑠,𝑛𝑞𝑐 𝑔𝑠,𝑛𝑝𝑐
NOTAS POR ESTUDIANTE:
𝑀𝑢𝑙𝑡𝑖𝑝𝑙𝑖𝑐𝑎𝑐𝑖𝑜𝑛 − 𝑑𝑒 − 𝑀𝑎𝑡𝑟𝑖𝑐𝑒𝑠
localhost:8889/notebooks/Solucion-Parcial-Andres-Peña...ipynb# 7/11
16/4/23, 21:29 Solucion-Parcial-Andres-Peña.. - Jupyter Notebook
𝑁 𝑠𝑛𝑓,𝑠 = 𝐺 ⋅ 𝑃𝑁
🔻
𝑛
𝑁 𝑠𝑖𝑗 = 𝑔𝑖1 𝑝𝑛1𝑗 + 𝑔𝑖2 𝑝𝑛2𝑗 + ⋯ + 𝑔𝑖𝑛 𝑝𝑛𝑛𝑗 = ∑ 𝑔𝑖𝑘 𝑝𝑛𝑘𝑗
𝑘=1
🔻
𝑁𝑠𝑛𝑓1
𝑁 𝑠𝑛𝑓,𝑠 = ...
𝑁𝑠
𝑛𝑓𝑠
localhost:8889/notebooks/Solucion-Parcial-Andres-Peña...ipynb# 8/11
16/4/23, 21:29 Solucion-Parcial-Andres-Peña.. - Jupyter Notebook
In [10]: Notas_Estudiantes.head(30)
Out[10]:
Programación Unnamed: Unnamed:
Unnamed: 2 30 ene 06 feb 06 feb.1 13 feb 13 feb
MECA B 1 3
Quiz de
Conceptos
Complejidad
Notación básicos de Quiz
0 NaN NaN NaN NaN Funciones de tiempo
O grande matemáticas Indexa
de
con python
algoritmos
ABRIR
1 NaN NaN NaN 100 100 100 100 1
CLASSROOM
Media de la
3 NaN NaN 0.694348 78.26087 43.478261 63.043478 68.26087 78.260
clase
Peña Andres
4 [email protected] 0.795455 100 50 50 80
Bohorquez Felipe
Camacho Andres
5 [email protected] 0.695455 100 30 50 50 1
Pinto Julian
Carlos
6 Lemus López [email protected] 0.727273 100 50 100 90 1
David
Cristian
7 Bolivar Rincon [email protected] 0.490909 0 0 0 40
Camilo
Cristian
8 Aponte Prieto [email protected] 0.754545 100 0 100 80 1
David
Daniel
9 Peña Diaz [email protected] 0.777273 100 100 50 80
Alberto
Gutierrez Daniel
10 [email protected] 0.609091 100 0 100 40 1
Rodriguez Andres
Duvan
11 Pérez Melo [email protected] 0.704545 100 50 0 100 1
Santiago
Gonzalez Gabriel
12 [email protected] 0.781818 100 50 50 80
Tellez Eduardo
Marquez Hugo
13 [email protected] 0.559091 100 20 50 0 1
Garcia Esteban
Velasquez Jonathan
14 [email protected] 0.727273 100 20 50 60
Sanchez Stiven
Juan
15 Rojas Arango [email protected] 0.720000 0 50 50 80 1
Nicolas
Juan
16 Florez Forero [email protected] 0.786364 100 50 100 80
Pablo
Julian
17 Leon Pedreros [email protected] 0.754545 100 0 100 80 1
Andres
Gonzalez
18 Luis Felipe [email protected] 0.781818 100 20 50 100 1
Latorre
Villarreal Maria
19 [email protected] 0.136364 100 0 50 0
Moreno Paula
Rocha
20 Nicolas [email protected] 0.536364 0 50 0 60
Sanchez
Araque
22 Rafael Isai [email protected] 0.813636 100 100 50 80 1
Monterroso
Samuel
24 Chaparro Ortiz [email protected] 0.859091 100 40 100 90 1
Alejandro
Herrera
25 Santiago [email protected] 0.750000 0 100 100 70 1
Rodriguez
Rivera
26 Santiago [email protected] 0.709091 0 100 50 80
Mendivelso
localhost:8889/notebooks/Solucion-Parcial-Andres-Peña...ipynb# 9/11
16/4/23, 21:29 Solucion-Parcial-Andres-Peña.. - Jupyter Notebook
[[5.0 2.5 2.5 4.0 2.5 5.0 5.0 5.0 5.0 2.5 4.75 0.0]
[5.0 1.5 2.5 2.5 5.0 5.0 5.0 5.0 0.0 2.5 4.25 0.0]
[5.0 2.5 5.0 4.5 5.0 5.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0]]
In [15]: #Aqui realizamos e importamos otro excel con las notas ponderadas de los quices, talleres y proyecto final
Entrada = pd.read_excel("ponderadosPC2.xlsx", index_col = 0)
In [16]: Entrada.head()
Out[16]:
T1 Q1 P1
Programacion
12.0
localhost:8889/notebooks/Solucion-Parcial-Andres-Peña...ipynb# 10/11
16/4/23, 21:29 Solucion-Parcial-Andres-Peña.. - Jupyter Notebook
In [22]: Notas_C1.shape
In [23]: ponderados_C1.shape
Out[23]: (12,)
In [26]: print(Nota_C1)
In [ ]:
localhost:8889/notebooks/Solucion-Parcial-Andres-Peña...ipynb# 11/11