您的位置:首页 > 编程语言 > Python开发

python numpy:1 numpy.array和numpy.matrix常用函数使用

2016-01-09 21:03 876 查看
#-*- encoding:utf-8 -*-
import numpy
import io
from io import StringIO
#import io.StringIO

def createArray():
d = numpy.zeros((3,4))
print(d.dtype)
print(d.dtype.itemsize)
oneMatrix = numpy.ones((3,3))
print(oneMatrix ,int)
emptyMatrix = numpy.empty((2,3))
print(emptyMatrix)
#注意最后一个取不到
myArange = numpy.arange(10,30,5)
print(myArange)
#arange默认为连续数组
arange2 = numpy.arange(7 , dtype=int)
print(arange2)

def toType():
x = numpy.float32(1.0)
print(x)
y = numpy.int_([1,2,3])
print(y)
z = numpy.arange(3,dtype=numpy.uint8)
print(z)
#转换数组元素的类型
z = z.astype(float)
print(z)
print(z.dtype)
#查看矩阵类型
d = numpy.dtype(int)
print(d)
#判断矩阵类型是否是指定类型
flag = numpy.issubdtype(d,int)
print(flag)

#将python数组转换为numpy数组
def toNumpyArray():
#默认是双精度浮点数float64
x = numpy.array([2,3,1,0])
print(x)
arr = numpy.arange(2,10,dtype=numpy.float)
print(arr)
arr2 = numpy.arange(2,3,0.1)
print(arr2)

#linspace(beg,end,num),间隔=(end-beg)/(num-1)
arr3 = numpy.linspace(1,4,6)
print(arr3)
ind = numpy.indices((3,3))
print(ind)

#读取字符串,生成矩阵
data = "1, 2, 3\n4, 5, 6"
#注意:需要的是字符流,需要编码为utf-8的字符流,解码为字符串(更高级)
arr4 = numpy.genfromtxt(io.BytesIO(data.encode("utf-8")) ,delimiter=',',dtype='f8' )
#arr4 = numpy.genfromtxt(data ,delimiter=',' )
print(arr4)

def shape_test():
#shape():作用:读取矩阵的长度,输入参数为矩阵
res = numpy.shape([1])
print(res)
res2 = numpy.shape([ [1],[2] ])
print(res2)

def create_unitMatrix():
#创建单位矩阵
e = numpy.eye(3)
print(e)
print("单位矩阵的形状:")
print(e.shape)

#转置矩阵
def transportMatrix():
x = numpy.linspace(0,4,5)
print("转置前")
print(x)
print(x.shape)
x.shape=(5,1)
y = numpy.transpose(x)
print("转置后")
print(y)
#transpose的操作依赖于shape参数,对于一维的shape.转置不起作用,[,,]表示行矩阵,[ [,,] ]表示列矩阵

'''
matrix必须是2维,但是numpy arrays可以是多维的
'''
def matrixCompute():
a = numpy.matrix(
[
[1,2,3],
[4,5,6],
[7,8,9]
]
)
m = numpy.ones((3,1),int)
res = a * m
print("验证矩阵乘法结果")
print(res)
#矩阵加减法
print("矩阵加法结果")
e = a + a
print(e)
print("矩阵减法结果")
e = a - a
print(e)

#矩阵乘法
print("矩阵乘法结果")
b = a * a
print(b)
print("dot点乘结果")
d = numpy.dot(a,a)
print(d)

print("转置矩阵函数")
g = a.transpose()
print(g)
print("转置矩阵T")
g = a.T
print(g)

print("逆矩阵**")
f = a**(-1)
print(f)

print("逆矩阵I")
f = a.I
print(f)

#行列式
j = numpy.linalg.det(a)
print("行列式")
print(j)

#矩阵乘法
def matrixMultiply_test():
# 矩阵中 * 是数组对应元素项城 , dot才是真正的矩阵乘法,我们应该用dot
a = numpy.array( [ [1,2],[1,1] ] )
b = numpy.array( [ [1,2],[1,1] ] )
c = a * b
print("矩阵对应元素相乘")
print(c)
d = numpy.dot(a,b)
print("矩阵真实乘法")
print(d)
e = numpy.eye(3)
print("单位矩阵")
print(e)
print("常数乘以单位矩阵")
print(3*e)

'''
数组按行求和,按列求和
'''
def matrix_sum():
#axis = 0表示按列求和,axis=1按行求和
c = numpy.array( [ [0,1],[0,1] ] )
a = numpy.sum( [ [0,1],[0,1] ] , axis = 0)
print(a)
b = numpy.sum( [ [0,1],[0,1] ] , axis = 1)
print(b)

d  = c.sum(axis = 0)
print(d)
e = c.sum(axis = 1)
print(e)

def generateWeightMatrix(Matrix):
M = len(Matrix[0])
if M == 0:
return False
resultArr = numpy.ones((1, M))
for row in Matrix:
rowVal = row.sum()
newRow = []
if rowVal != 0:
newRow = (1.0/rowVal) * row
else:
newRow = row
resultArr = numpy.insert(resultArr , len(resultArr) , values=numpy.array(newRow) , axis=0)
#删除第一行
resultArr = numpy.delete(resultArr , 0 , 0)
return resultArr

'''
矩阵遍历
'''
def matrix_visit():
#e = numpy.eye(3)
e = numpy.array( [ [1,0,1],[0,1,0],[0,0,0] ] )
M = len(e[0])
rowVecror = e.sum(axis = 1)
#print(rowVecror)
#print(e)
resultArr = numpy.ones((1, M))
#resultArr = numpy.array([])
#resultArr = numpy.array([])
newArr = []
print("求权值前")
for row in e:
print(row)
rowVal = row.sum()
newRow = []
if rowVal != 0:
newRow = (1.0/rowVal) * row
#print(newRow)

else:
newRow = row
#print(newRow)
resultArr = numpy.insert(resultArr , len(resultArr) , values=numpy.array(newRow) , axis=0)
#resultArr = newArr
print("求权值后")
#需要删除一行 numpy.delete(arr,obj,axis=None)
resultArr = numpy.delete(resultArr , 0 , 0)
print(resultArr)

#遍历数组每个元素,用flat
'''
for ele in e.flat:
print(ele)
'''

'''
修改矩阵,添加一行或一列
'''
def modifyMatrix():
e = numpy.ones((2,2))
print(e)
a = numpy.array([1,1])
#a = numpy.ones(2)
print(a)
b = numpy.array([3,3])
#e.c_[a]
'''
numpy.insert(arr,obj,values,axis=None)
arr:输入数组
'''
#注意insert是返回一个新的数组,axis=0是添加行
newe = numpy.insert(e , 0 , values=b , axis=0 , )
print("添加一行后的结果")
print(newe)
arr = []
emptyArr = numpy.array([])
newe = numpy.insert(emptyArr , 0 , values = b , axis=0)
print(newe)

def flat_test():
R = numpy.array([1,2,3])
for x in R.flat:
print(x)
val = str(x)
print(val)

results = [ str(round(x,5)) for x in R.flat]
results = "\t".join(results)
print(results)
#results = [ str(round(x) ,5 )) for x in R.flat ]

if __name__ == "__main__":
#createArray()
#toType()
#toNumpyArray()
'''
shape_test()
create_unitMatrix()
transportMatrix()
'''
#matrixCompute()
#matrixMultiply_test()
#matrix_sum()
#matrix_visit()
#modifyMatrix()
flat_test()
Matrix = numpy.array( [ [1,0,1],[0,1,0],[0,0,0] ] )
resultMatrix = generateWeightMatrix(Matrix)
print(resultMatrix)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python numpy