Read arrays and explain them with plots

English translation

Create your own copy to run, edit, and record results.

Self-study material

1. Array shapes

First check shape and element count using an array of 12 elements.

A. Baseline example · Read and run first

import numpy as np
import matplotlib.pyplot as plt
a = np.arange(1,13).reshape(3,4)
print(a, '\nshape:',a.shape,'ndim:',a.ndim,'size:',a.size)
print('second row:',a[1,:])
print('mask:',a>7,'selected:',a[a>7])

B. Hands-on activities

  1. Create a NumPy Array from score=[728590689588]\mathrm{score}=\begin{bmatrix}72&85&90&68&95&88\end{bmatrix} and print its shape, dtype, mean, values at least 80, and their count.
  2. Arrange 1~20 into (4,5), then print the first row, last column, middle 2-row×3-column region, and even values separately.

Your prediction may describe a shape or an increasing/decreasing trend rather than an exact number. Use the example above to write code; answer explanation-only items in the Text Cell below.

# ✍ Write your own: add your code below this cell.
# You may add Code Cells if the code gets long.

C. Your record · Double-click this Text Cell to edit

2. Operations and verification

Compute and compare A*B, which multiplies matching elements, and A@B, which sums row-column products. Then compute A's Inverse and check whether A@Inverse is the Identity.

A. Baseline example · Read and run first

A=np.array([[2.,1.],[1.,3.]])
B=np.array([[1.,0.],[2.,1.]])
print('elementwise:',A*B,'matrix:',A@B)
print('inverse:',np.linalg.inv(A))
assert np.allclose(A@np.linalg.inv(A),np.eye(2))
values=np.array([3.,7.,5.]);print('max:',values.max(),'index:',values.argmax())

B. Hands-on activities

  1. For A=[2.01.01.03.0]A=\begin{bmatrix}2.0&1.0\\1.0&3.0\end{bmatrix} and B=[1.00.02.01.0]B=\begin{bmatrix}1.0&0.0\\2.0&1.0\end{bmatrix}, compute the Element-wise Product and Matrix Multiplication and explain how element (0,1) is obtained.
  2. Compute A's Determinant and Inverse and use np.allclose to verify that A@Inverse is the Identity.
  3. Change A[0,0] to 4 and repeat.

Your prediction may describe a shape or an increasing/decreasing trend rather than an exact number. Use the example above to write code; answer explanation-only items in the Text Cell below.

# ✍ Write your own: add your code below this cell.
# You may add Code Cells if the code gets long.

C. Your record · Double-click this Text Cell to edit

3. Plot the results

Compute the maximum's position and mark it on the plot.

A. Baseline example · Read and run first

x=np.linspace(0,2*np.pi,100)
y=np.sin(x)
fig,ax=plt.subplots();ax.plot(x,y,label='sin(x)');i=y.argmax()
ax.annotate('sample maximum',(x[i],y[i]),xytext=(2,0.5),arrowprops={'arrowstyle':'->'})
ax.set(xlabel='x (rad)',ylabel='value',title='Sampled sine');ax.grid();ax.legend();plt.show()

B. Hands-on activities

  1. Create x with 100 samples from 0~2π and plot sin and cos together.
  2. Then use epoch=[12345]\mathrm{epoch}=\begin{bmatrix}1&2&3&4&5\end{bmatrix}, loss=[1.81.20.90.70.6]\mathrm{loss}=\begin{bmatrix}1.8&1.2&0.9&0.7&0.6\end{bmatrix}, and accuracy=[0.40.60.70.750.78]\mathrm{accuracy}=\begin{bmatrix}0.4&0.6&0.7&0.75&0.78\end{bmatrix} to display sin, cos, Loss, and Accuracy in a 2×2 Figure.
  3. Label axes and add a Legend, locate the maximum Accuracy in code, and mark it with an annotation.

Your prediction may describe a shape or an increasing/decreasing trend rather than an exact number. Use the example above to write code; answer explanation-only items in the Text Cell below.

# ✍ Write your own: add your code below this cell.
# You may add Code Cells if the code gets long.

C. Your record · Double-click this Text Cell to edit

Practice through repetition · Reason before running

Summarize the three conditions compared in the preceding activities in this table. You do not need to repeat experiments already completed. If comparisons are insufficient, supplement them by changing just one condition.

Changed condition Predicted shape/value/result Actual result Cause of any error
⟦Enter your response 1⟧ ⟦Enter your response⟧ ⟦Enter your response⟧ ⟦Enter your response⟧
⟦Enter your response 2⟧ ⟦Enter your response⟧ ⟦Enter your response⟧ ⟦Enter your response⟧
⟦Enter your response 3⟧ ⟦Enter your response⟧ ⟦Enter your response⟧ ⟦Enter your response⟧
# ✍ Code for repeated experiments

Optional exercise · Find the cause of an error and fix the code

reshape with an incompatible element count

  1. After importing NumPy, add a Code Cell at the bottom of the notebook and run the following code.

    debug_values = np.arange(12)
    for debug_shape in [(5, 3), (3, 4)]:
        print("requested shape:", debug_shape, "elements:", debug_values.size)
        try:
            print(debug_values.reshape(debug_shape))
        except ValueError as error:
            print(type(error).__name__, str(error))
  2. In a Text Cell, tabulate the required element count and execution success for each requested shape. Also explain in one sentence the order in which values from 0 to 11 are arranged in the successful array.

Check before saving

  1. Check the response fields, outputs, and plots, then run all cells in order in a fresh runtime.
  2. Save to your Drive, then download using .ipynb.

Include code, actual outputs and plots, and your own interpretation. Submit through KLAS; check the semester schedule and latest announcements for the deadline.

Filename: Name_StudentID_Week3.ipynb.