Numpy应用举例
使用ndarray数组可以很方便的构建数学函数,并利用其底层的矢量计算能力快速实现计算。下面以神经网络中比较常用激活函数Sigmoid和ReLU为例,介绍代码实现过程。
- 计算Sigmoid激活函数
- 计算ReLU激活函数
使用Numpy计算激活函数Sigmoid和ReLU的值,使用matplotlib画出图形,代码如下所示。
- <Figure size 576x216 with 2 Axes>
图像翻转和裁剪
图像是由像素点构成的矩阵,其数值可以用ndarray来表示。将上述介绍的操作用在图像数据对应的ndarray上,可以很轻松的实现图片的翻转、裁剪和亮度调整,具体代码和效果如下所示。
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
# 读入图片
image = Image.open('./work/images/000000001584.jpg')
image = np.array(image)
# 查看数据形状,其形状是[H, W, 3],
# 其中H代表高度, W是宽度,3代表RGB三个通道
image.shape
- (612, 612, 3)
# 原始图片
plt.imshow(image)
- <matplotlib.image.AxesImage at 0x7fefe4f56290>
- <Figure size 432x288 with 1 Axes>
# 垂直方向翻转
# 这里使用数组切片的方式来完成,
# 相当于将图片最后一行挪到第一行,
# 倒数第二行挪到第二行,...,
# 第一行挪到倒数第一行
# 负数步长表示以最后一个元素为起点,向左走寻找下一个点
# 对于列指标和RGB通道,仅使用:表示该维度不改变
image2 = image[::-1, :, :]
plt.imshow(image2)
- <matplotlib.image.AxesImage at 0x7fefe4ecc850>
- <Figure size 432x288 with 1 Axes>
# 水平方向翻转
image3 = image[:, ::-1, :]
plt.imshow(image3)
- <matplotlib.image.AxesImage at 0x7fefe4e35f10>
- <Figure size 432x288 with 1 Axes>
# 高度方向裁剪
H, W = image.shape[0], image.shape[1]
# 注意此处用整除,H_start必须为整数
H1 = H // 2
H2 = H
image4 = image[H1:H2, :, :]
plt.imshow(image4)
- <matplotlib.image.AxesImage at 0x7fefe4e2cc10>
- <Figure size 432x288 with 1 Axes>
# 宽度方向裁剪
W1 = W//6
W2 = W//3 * 2
plt.imshow(image5)
- <matplotlib.image.AxesImage at 0x7fefe4d2e050>
- <Figure size 432x288 with 1 Axes>
# 两个方向同时裁剪
W1:W2, :]
plt.imshow(image5)
- <matplotlib.image.AxesImage at 0x7fefe4d09b10>
- <Figure size 432x288 with 1 Axes>
# 调整亮度
image6 = image * 0.5
plt.imshow(image6.astype('uint8'))
- <matplotlib.image.AxesImage at 0x7fefe4367fd0>
- <Figure size 432x288 with 1 Axes>
- <matplotlib.image.AxesImage at 0x7fefe42e4990>
- <Figure size 432x288 with 1 Axes>
#高度方向每隔一行取像素点
image8 = image[::2, :, :]
plt.imshow(image8)
- <matplotlib.image.AxesImage at 0x7fefe4259e50>
- <Figure size 432x288 with 1 Axes>
#宽度方向每隔一列取像素点
image9 = image[:, ::2, :]
plt.imshow(image9)
- <matplotlib.image.AxesImage at 0x7fefe4255510>
- <Figure size 432x288 with 1 Axes>
#间隔行列采样,图像尺寸会减半,清晰度变差
image10 = image[::2, ::2, :]
plt.imshow(image10)
- (306, 306, 3)
- <Figure size 432x288 with 1 Axes>
tanh是神经网络中常用的一种激活函数,其定义如下:
请参照讲义中Sigmoid激活函数的计算程序,用numpy实现tanh函数的计算,并画出其函数曲线。
提交方式:请用numpy写出计算程序,并画出tanh函数曲线图,x的取值范围设置为[-10., 10.]。
作业1-8: 统计随机生成矩阵中有多少个元素大于0
假设使用np.random.randn生成了随机数构成的矩阵:
p = np.random.randn(10, 10)
请写一段程序统计其中有多少个元素大于0?
提交方式:提交计算的代码,能够直接运行输出统计出来的结果。