CMU 11-785 recitation numpy操作

import numpy as np
'''
https://github.com/cmudeeplearning11785/Spring2019_Tutorials/blob/master/recitation-0/Numpy%20%26%20PyTorch.ipynb
在python中调用numpy package主要是为了实现vectorization向量化的操作
假设现在要实现 y=wx+b 等式,分别写出在不适用numpy工具包和使用numoy工具包下的代码段
'''
def wx_b_nonp():#不适用numypy工具包,只使用python中的内部结构list实现
    W = [[1, 1, 1],
         [2, 2, 2],
         [3, 3, 3]]

    x = [7, 8, 5]
    b = [1, 1, 1]

    # Output
    y = [0, 0, 0]
    input_dim=len(x)
    output_dim=len(y)
    for i in range(output_dim):
        for j in range(input_dim):
            y[i]+=x[j]*W[i][j]
        y[i]+=b[i]
    return y
def wx_b_np():
    W = np.array([[1, 1, 1],
         [2, 2, 2],
         [3, 3, 3]])

    x = np.array([7, 8, 5])
    b = np.array([1, 1, 1])

    y=W.dot(x)+b
    return y

output1=wx_b_nonp()
output2=wx_b_np()
print(output1,output2)
'''[21, 41, 61] [21 41 61]'''

T=np.random.random((2,3,4))
print(T)
W=T[1]
print(W.shape,W.dtype)#(3, 4) float64

X=np.full((4,3),11785,dtype=np.uint32)
print(X.shape,X.dtype,np.min(X),np.max(X))
'''
(4, 3) uint32 11785 11785
'''

y=W.dot(X)#(3, 3)
print(y.shape)

X2=np.zeros(X.shape)
is_true=np.array_equal(W.dot(X2),np.zeros((3,3)))#判断两个numpy数组是否相等
print(is_true)#True

#numpy数组的element wise operations
y=np.arange(10)
out=(y==np.array(range(10)))
print(out)#[ True  True  True  True  True  True  True  True  True  True]

out2=np.sqrt(y**2)

y.min(), y.max(), y.std(), y.sum()

np.save('1.npy',np.array(range(2*4*3)).reshape(2,4,3))
T=np.load('1.npy')
print(T)
#numpy也可以进行切片和索引
T1=np.array(range(12)).reshape(2,3,2)
print(T1)
print(T1%10==0)
print(T1[T1%10==0])#numpy数组支持布尔索引
'''
[[[ 0  1]
  [ 2  3]
  [ 4  5]]

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

 [[False False]
  [False False]
  [ True False]]]
[ 0 10]
'''
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值