单独把这几道题目拿出来,归为一类吧,都是标准化算法。
本讲的主要内容:
首先给出Z-Score标准化公式:
Z = X − m e a n ( X ) s d ( X ) Z=\frac{X-mean(X)}{sd(X)} Z=sd(X)X−mean(X)
其实知道了公式就好算了,只是对之前的一些计算进行了一个综合
def zscore(a,axis=None):
amean = np.mean(a, axis=axis,keepdims=True )
astd = np.std(a, axis=axis, keepdims=True)
return (a - amean)/astd
a = np.random.randint(1, 10, 10)
print(zscore(a))
输出:
[-0.55418416 1.07576925 0.74977857 1.07576925 0.42378789 1.40175994
-0.55418416 -1.20616553 -1.20616553 -1.20616553]
公式:
Y = Z − m i n ( Z ) m a x ( Z ) − m i n ( Z ) Y = \frac{Z-min(Z)}{max(Z) - min(Z)} Y=max(Z)−min(Z)Z−min(Z)
还是一样
def minmax(a, axis=None):
a_min = np.min(a, axis=axis, keepdims=True)
a_max = np.max(a, axis=axis, keepdims=True)
return (a - a_min)/(a_max - a_min)
a = np.random.randint(1, 10, (3,3))
print(minmax(a))
输出:
[[0.57142857 0.42857143 1. ]
[0.28571429 0.28571429 0.42857143]
[1. 1. 0. ]]
L2范数的计算公式:
L 2 = x 1 2 + x 2 2 + . . . + x i 2 L_{2} = \sqrt{x_{1}^{2} + x_{2}^{2}+...+x_{i}^{2}} L2=x12+x22+...+xi2
根据计算公式写出函数:
def l2_normalize(v, axis=-1, order=2):
l2 = np.linalg.norm(v, ord=order, axis=axis, keepdims=True)
l2[l2==0] = 1
return v/l2
z = np.random.randint(1, 10, (3,3))
print(l2_normalize(z))
输出:
[[0.11547005 0.80829038 0.57735027]
[0.88345221 0.33129458 0.33129458]
[0.64465837 0.24174689 0.72524067]]
这是最后一个实验了,实验楼这一波广告。。猝不及防。。
直接附上参考答案好了:
from io import BytesIO
from PIL import Image
import PIL, requests
# 通过链接下载图像
URL = 'https://static.shiyanlou.com/img/logo-black.png'
response = requests.get(URL)
# 将内容读取为图像
I = Image.open(BytesIO(response.content))
# 将图像转换为 Ndarray
shiyanlou = np.asarray(I)
shiyanlou
Numpy100题的实验终于整理完了耶!
完结撒花!
以上~