Files
pytorch-study/03.ipynb
2025-06-11 17:23:34 +08:00

38 KiB
Raw Blame History

In [16]:
import numpy as np
In [17]:
arr_1_d = np.asarray([1, ])
print(arr_1_d)
[1]
In [27]:
arr_2_d = np.asarray([[1, 2], [3, 4]])
print(arr_2_d)
[[1 2]
 [3 4]]

ndim

ndim表示数组维度或轴的个数。刚才创建的数组arr_1_d的轴的个数就是1arr_2_d的轴的个数就是2。

In [21]:
print(arr_1_d.ndim)
print(arr_2_d.ndim)
1
2

shape

shape表示数组的维度或形状 是一个整数的元组元组的长度等于ndim。

arr_1_d的形状就是1一个向量 arr_2_d的形状就是(2, 2)(一个矩阵)。

In [36]:
print(arr_1_d.shape)
print(arr_2_d.shape)
(1,)
(2, 2)
In [64]:
arr_3_d = np.arange(6).reshape((2, 3))
np.reshape(arr_3_d, (6, 1), 'F')
Out[64]:
array([[0],
       [3],
       [1],
       [4],
       [2],
       [5]])
In [68]:
np.arange(5)
np.arange(2, 6)
np.arange(2, 6, 2)
Out[68]:
array([2, 4])
In [73]:
np.linspace(0, 1, 5)  # 从0到1生成5个数
Out[73]:
array([0.  , 0.25, 0.5 , 0.75, 1.  ])
In [81]:
x = np.arange(-50, 51, 2)
y = x ** 2

import matplotlib.pyplot as plt

plt.plot(x, y, color='blue', label='y = x^2')  # 绘制y = x^2的图像
plt.xlabel('x')  # x轴标签
plt.ylabel('y')  # x轴和y轴标签
plt.title('y = x^2')  # 图表标题
plt.legend()  # 图例
plt.grid()  # 网格线
plt.show()
No description has been provided for this image
In [89]:
interest_score = np.random.randint(10, size=(4, 3))
print(interest_score)

print(np.sum(interest_score, axis=0))  # 按列求和
[[4 0 4]
 [9 7 9]
 [5 3 6]
 [9 6 1]]
[27 16 20]
In [97]:
arr_4_d=np.arange(18).reshape(3,2,3)
In [98]:
print(arr_4_d)
[[[ 0  1  2]
  [ 3  4  5]]

 [[ 6  7  8]
  [ 9 10 11]]

 [[12 13 14]
  [15 16 17]]]
In [99]:
np.max(arr_4_d,axis=0)
Out[99]:
array([[12, 13, 14],
       [15, 16, 17]])
In [100]:
arr_4_d.ravel()
Out[100]:
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17])