Python深度学习读书笔记_第二章: 对于张量(tensor)计算的一些总结

读了《Python深度学习》这本书的第二章,对张量运算有所理解,因而记录总结一下。

逐元素运算

relu运算和加法运算都是逐元素的运算,所谓逐元素,是指对张量中的每一个元素逐一进行运算。

其中,relu(X)是max(X,0)

# 逐元素relu运算
def naive_relu(x):
    assert len(x.shape) == 2   # x 是一个Numpy的2D张量
    x = x.copy()
    for i in range(x.shape[0]):   # 避免覆盖输入张量
        for j in range(x.shape[1]):
            x[i, j] = max(x[i, j], 0)
    return x
# 逐元素加法运算
def naive_add(x, y):
    assert len(x.shape) == 2    # x,y是Numpy的2D张量
    assert x.shape == y.shape
    
    x = x.copy()
    for i in range(x.shape[0]):
        for j in range(x.shape[1]):
            x[i, j] += y[i, j]
    return x

在矩阵和向量相加时,向量会被广播,让向量和矩阵每一行相加。

# 矩阵和向量相加
def naive_add_matrix_and_vector(x, y):
    assert len(x.shape) == 2    # x是一个Numpy的2D张量
    assert len(y.shape) == 1    # y是一个Numpy的向量
    assert x.shape[1] == y.shape[0]
    
    x = x.copy()
    for i in range(x.shape[0]):
        for j in range(x.shape[1]):
            x[i, j] += y[j]
    return x
x = np.array([[1,2,3],
     [4,5,6]])
y = np.array([1,2,3])
z = naive_add_matrix_and_vector(x, y)
z

下面这个例子,利用广播将逐元素的maxinum运算应用于两个形状不同的张量。

import numpy as np

x = np.random.random((2,1))
y = np.random.random((1))
z = np.maximum(x, y)
print(x)
print(y)
print(z)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值