欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

机器学习----numpy矢量化编程

程序员文章站 2022-07-14 19:43:24
...
#Numpy 提供了专门的矩阵数据结构和线性代数库,完全实现了矢量化编程
import numpy as np
from numpy import *
mylist = [1,2,3,4,5]
a = 10
mymatrix = np.mat(mylist)
print (a*mymatrix)
#输出结果为:[[10 20 30 40 50]]


#numpy 矩阵运算
myZero = np.zeros([3,5]) # 3*5 的全零矩阵
print(myZero)
myOnes = np.ones([3,5]) # 3*5 的全 1 矩阵
print(myOnes)

myRand = np.random.rand(3,4) # 34 列的 0~1 之间的随机数矩阵
print( myRand)

myEye = np.eye(3) # 3*3 的单位阵
print (myEye)

myOnes = ones([3,3]) # 3*3 的全 1 矩阵
myEye = eye(3) # 3*3 的单位阵
print (myOnes+myEye) # 矩阵相加
print( myOnes-myEye )# 矩阵相减

mymatrix = mat( [[1,2,3],[4,5,6],[7,8,9]])
a = 10
print (a*mymatrix)

mymatrix = mat([[1,2,3],[4,5,6],[7,8,9]] )
print (sum(mymatrix))

mymatrix = mat( [[1,2,3],[4,5,6],[7,8,9]])
mymatrix2 = 1.5*ones([3,3])
print (multiply(mymatrix,mymatrix2))

mylist = mat( [[1,2,3],[4,5,6],[7,8,9]])
print (power(mymatrix,2))

mymatrix = mat([[1,2,3],[4,5,6],[7,8,9]])
mymatrix2 = mat([[1],[2],[3]])
print (mymatrix*mymatrix2)

mymatrix = mat([[1,2,3],[4,5,6],[7,8,9]])
print (mymatrix.T) # 矩阵的转置
mymatrix.transpose() # 矩阵的转置
print (mymatrix)

#矩阵操作: 行列数、切片、 复制
mymatrix = mat([[1,2,3],[4,5,6],[7,8,9]])
[m,n]=shape(mymatrix) # 矩阵的行列数
print ("矩阵的行数和列数:",m,n)
myscl1 = mymatrix[0] # 按行切片
print ("按行切片:",myscl1)
myscl2 = mymatrix.T[0] # 按列切片
print("按列切片:",myscl2)
mycpmat = mymatrix.copy() # 矩阵的复制
print ("复制矩阵:\n",mycpmat)
#比较
print ("矩阵元素的比较:\n",mymatrix < mymatrix.T)

机器学习----numpy矢量化编程
机器学习----numpy矢量化编程