numpy Task03

数组操作

更改形状
  • numpy.ndarray.shape表示数组的维度,返回一个元组,这个元组的长度就是维度的数目,即 ndim 属性(秩)。
import numpy as np

x = np.array([1,2,9,4,5,6,7,8])
print(x.shape)
x.shape = [2,4]
print(x)

(8,)
[[1 2 9 4]
[5 6 7 8]]

  • numpy.ndarray.flat 将数组转换为一维的迭代器,可以用for访问数组每一个元素。
import numpy as np
x = np.array([[11, 12, 13, 14, 15],
              [16, 17, 18, 19, 20],
              [21, 22, 23, 24, 25],
              [26, 27, 28, 29, 30],
              [31, 32, 33, 34, 35]])
y = x.flat

for i in y:
    print(i,end=',')

11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,

  • numpy.ndarray.flatten([order=‘C’]) 将数组的副本转换为一维数组,并返回。
    【order:‘C’ – 按行,‘F’ – 按列,‘A’ – 原顺序,‘k’ – 元素在内存中的出现顺序。】
import numpy as np
x = np.array([[11, 12, 13, 14, 15],
              [16, 17, 18, 19, 20],
              [21, 22, 23, 24, 25],
              [26, 27, 28, 29, 30],
              [31, 32, 33, 34, 35]])
y = x.flatten()
print(y)

[11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
35]

  • numpy.ravel(a, order=‘C’)将数组转换为一维数组,与上面不同的是,此方法返回的是数组的视图
  • reshape()函数当参数newshape = -1时,表示将数组降为一维

数组转置

  • numpy.transpose(a,axes=None)
  • numpy.ndarray.T
import numpy as np
x = np.random.rand(5,5) * 10
x = np.around(x ,2)
print(x)
print("++++++++++++++")
y = x.T
print(y)
print("++++++++++++++")
z = np.transpose(x)
print(z)

[[1.62 1.64 2.18 2.61 3.45]
[3.42 9.84 7.68 4.1 7.24]
[3.95 1.1 0.8 2.89 0.19]
[0.15 0.91 5.34 9.95 8.62]
[7.48 6.67 0.38 2.31 0.33]]
++++++++++++++
[[1.62 3.42 3.95 0.15 7.48]
[1.64 9.84 1.1 0.91 6.67]
[2.18 7.68 0.8 5.34 0.38]
[2.61 4.1 2.89 9.95 2.31]
[3.45 7.24 0.19 8.62 0.33]]
++++++++++++++
[[1.62 3.42 3.95 0.15 7.48]
[1.64 9.84 1.1 0.91 6.67]
[2.18 7.68 0.8 5.34 0.38]
[2.61 4.1 2.89 9.95 2.31]
[3.45 7.24 0.19 8.62 0.33]]

更改维度

  • 当创建了一个数组之后,还可以给它增加一个维度,这在矩阵计算中经常会用到。
    【numpy.newaxis = None None】
import numpy as np
x = np.array([1,2,9,4,5,6,7,8])
print(x.shape)
print(x)
print("++++++++++++")
y = x[:,np.newaxis]
print(y.shape)
print(y)

(8,)
[1 2 9 4 5 6 7 8]
++++++++++++
(8, 1)
[[1]
[2]
[9]
[4]
[5]
[6]
[7]
[8]]

  • numpy.squeeze(a,axis = None)从数组的形状中删除单维度条目,即把shape中为1的维度去掉
    【a表示输入是数组;axis用于指定需要删除的维度,但是指定是维度必须为单维度,否则将会报错】
import numpy as np 
x = np.arange(10)
print(x.shape)
x = x[np.newaxis,:]
print(x.shape)
y = np.squeeze(x)
print(y.shape)

(10,)
(1, 10)
(10,)

数组组合

  • 连接沿现有轴的数组序列(原来x,y都是一维的,拼接后的结果也是一维的)。
import numpy as np
x = np.array([1,2,3])
y = np.array([7,8,9])
z = np.concatenate([x,y])
print(z)

[1 2 3 7 8 9]

  • 原来x,y都是二维的,拼接后的结果也是二维的
import numpy as np
x = np.array([1,2,3]).reshape(1,3)
y = np.array([7,8,9]).reshape(1,3)
z = np.concatenate([x,y])
print(z)
print('+++++++++++++++')
z = np.concatenate([x, y], axis=1)
print(z)

[[1 2 3]
[7 8 9]]
+++++++++++++++
[[1 2 3 7 8 9]]

  • 沿着新的轴加入一系列数组(stack)
import numpy as np

x = np.array([[1, 2, 3], [4, 5, 6]])
y = np.array([[7, 8, 9], [10, 11, 12]])
z = np.stack([x, y])
print(z.shape)
print(z)

(2, 2, 3)
[[[ 1 2 3]
[ 4 5 6]]

[[ 7 8 9]
[10 11 12]]]

数组拆分
  • numpy.split(ary, indices_orsections,sxis=0) 拆分数组
import numpy as np
x = np.array([[11, 12, 13, 14],
              [16, 17, 18, 19],
              [21, 22, 23, 24]])
y = np.split(x,[1,3])
print(y)

[array([[11, 12, 13, 14]]), array([[16, 17, 18, 19],
[21, 22, 23, 24]]), array([], shape=(0, 4), dtype=int32)]

  • 垂直切分是把数组按照高度切分
import numpy as np

x = np.array([[11, 12, 13, 14],
              [16, 17, 18, 19],
              [21, 22, 23, 24]])
y = np.vsplit(x, 3)
print(y)

[array([[11, 12, 13, 14]]), array([[16, 17, 18, 19]]), array([[21, 22, 23, 24]])]

  • 水平切分是把数组按照宽度切分。
import numpy as np

x = np.array([[11, 12, 13, 14],
              [16, 17, 18, 19],
              [21, 22, 23, 24]])
y = np.hsplit(x, 2)
print(y)

[array([[11, 12],
[16, 17],
[21, 22]]), array([[13, 14],
[18, 19],
[23, 24]])]

数组平铺
  • numpy.tile(A,reps)将原矩阵横向、纵向地复制
import numpy as np

x = np.array([[1, 2], [3, 4]])
print(x)
print("++++++++++")
y = np.tile(x,(1,3))
print(y)

[[1 2]
[3 4]]
++++++++++
[[1 2 1 2 1 2]
[3 4 3 4 3 4]]

  • numpy.repeat(a, repeats, axis=None)【axis=0,沿着y轴复制,增加了行数;axis=1,沿着x轴复制,增加了列数;repeats,可以为一个数,也可以为一个矩阵;axis=None时就会flatten当前矩阵,实际上变成了一个行向量】
import numpy as np

x = np.array([[1, 2], [3, 4]])
y = np.repeat(x, 2, axis=1)
print(y)

[[1 1 2 2]
[3 3 4 4]]

添加和删除元素
  • numpy.unique(ar, return_index=False, return_inverse=False,return_counts=False, axis=None)
### 使用NumPy实现LSTM神经网络 为了理解如何使用NumPy来构建一个简单的LSTM单元,可以考虑以下简化版本的LSTM模型。此方法有助于深入理解LSTM的工作原理及其内部机制。 #### 初始化权重矩阵和偏置向量 定义函数用于初始化LSTM所需的权重矩阵和偏置项: ```python def initialize_parameters(n_x, n_a): """ Initialize parameters with small random values. Arguments: n_x -- number of units in the input vector (dimensionality of a single time step data point) n_a -- number of LSTM units Returns: params -- python dictionary containing initialized weights and biases """ Wf = np.random.randn(n_a, n_a + n_x) * 0.01 # Forget gate weight matrix bf = np.zeros((n_a, 1)) # Forget gate bias vector Wi = np.random.randn(n_a, n_a + n_x) * 0.01 # Input update gate weight matrix bi = np.zeros((n_a, 1)) # Input update gate bias vector Wo = np.random.randn(n_a, n_a + n_x) * 0.01 # Output gate weight matrix bo = np.zeros((n_a, 1)) # Output gate bias vector Wc = np.random.randn(n_a, n_a + n_x) * 0.01 # Candidate cell state weight matrix bc = np.zeros((n_a, 1)) # Candidate cell state bias vector params = {"Wf": Wf, "bf": bf, "Wi": Wi, "bi": bi, "Wo": Wo, "bo": bo, "Wc": Wc, "bc": bc} return params ``` #### 单步前向传播过程 接下来是单个时间步骤内的前向计算逻辑,它接收当前时刻输入xt及时刻t−1的状态ht−1和记忆ct−1作为输入,并输出新的状态ht和更新后的记忆ct: ```python def lstm_cell_forward(xt, a_prev, c_prev, parameters): """ Implement the forward propagation for the LSTM-cell. Arguments: xt -- your input data at timestep "t", numpy array of shape (n_x, m). a_prev -- Hidden state at timestep "t-1", numpy array of shape (n_a, m) c_prev -- Memory state at timestep "t-1", numpy array of shape (n_a, m) parameters -- Weight matrix of the forget gate, numpy array of shape (n_a, n_a + n_x) bf -- Bias of the forget gate, numpy array of shape (n_a, 1) ... Returns: a_next -- next hidden state, of shape (n_a, m) c_next -- next memory state, of shape (n_a, m) yt_pred -- prediction at timestep "t", numpy array of shape (n_y, m) cache -- tuple of values needed for the backward pass, contains (a_next, c_next, a_prev, c_prev, ft, it, ct_hat, ot, xt, parameters) """ # Retrieve parameters from "parameters" Wf = parameters["Wf"] bf = parameters["bf"] Wi = parameters["Wi"] bi = parameters["bi"] Wo = parameters["Wo"] bo = parameters["bo"] Wc = parameters["Wc"] bc = parameters["bc"] # Concatenate a_prev and xt to get concatenated input concat = np.concatenate([a_prev, xt], axis=0) # Compute all gates using activation functions sigmoid or tanh where appropriate ft = sigmoid(np.dot(Wf, concat) + bf) # Forget gate activations it = sigmoid(np.dot(Wi, concat) + bi) # Update gate activations cct = np.tanh(np.dot(Wc, concat) + bc) # Cell candidate value c_next = ft * c_prev + it * cct # New cell state ot = sigmoid(np.dot(Wo, concat) + bo) # Output gate activations a_next = ot * np.tanh(c_next) # Next hidden state # Define predictions as output layer's result after applying softmax function on top of 'ot' yt_pred = None # Placeholder; actual implementation depends on task requirements # Store intermediate results into `cache` variable which will be used during backpropagation phase later cache = (a_next, c_next, a_prev, c_prev, ft, it, cct, ot, xt, parameters) return a_next, c_next, yt_pred, cache ``` 上述代码片段展示了如何利用NumPy库创建并执行一次完整的LSTM细胞操作[^1]。需要注意的是,在实际应用中还需要编写反向传播算法以便能够调整参数从而最小化损失函数;此外,对于具体的预测任务还需设计相应的输出层结构。
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BigCabbageFy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值