numpy初识

1,机器学习numpy 初识

1)numpy初识

import numpy
num1= numpy.array([1,2,3])
dtype('num1') #查找类型

num1.dtype
num1.shape #查找数据维数
num1.genfromtxt("wordll.txt",delimiter=',',dtype=str,skip_header=1) #通过文本读取数据

num1[0,2] #取指定标的数据 小标为0-2的数据
matrix = numpy.array([5,6,7,8],
[5,6,7,8],
[5,6,7,8],
[5,6,7,8])
matrix[:,1] #返回 [6,6,6,6]
enq=(matrix == 8)
#返回array([flase,flase,flase,true],
[flase,flase,flase,true],
[flase,flase,flase,true],
[flase,flase,flase,true])
print(matrix[enq]) #返回 [8,8,8,8]
print(matrix[enq,:]) # 返回所在的行
================================================
2)numpy 矩阵
vetor = numpy.array([10,15,5,30])
numd=(vetor==10 | vetor==15)) #[ture,false,false,true]
vector = vetor.astype(float) # 类型返回float
print(vector.dtype) # float

#求和
matrix.sum(axis=1) # 对行求和
matrix.sum(axis=0) # 对列求和
numpy.arange(15)
a=numpy.arange(15).reshape(3,5)
a.shape
a.dtype.name
a.size
a.nidm

#初始化空矩阵
np.zeros(3,4) # 3 行 4列的空矩阵
np.ones((2,3,4),dtype=np.Int32)
np.arange(10,30,5) # [10,15,20,25]
np.arange(12).reshape(4,3)
np.random.random((2,3))
np.linspace(0,12,100) # 0-12 取100 个数的数组


#计算
np.dot(A,B) #两个矩阵的相乘 也可以A*B
np.sqrt(B) #求平方根
np.exp(B) # 平方
a = np.floor(10*np.random.random(3,4)) #向下取整
a.ravel() # 多维数组变成一位数组
a.shape=(6,2)
a.T #转置
a.reshape(3,-1) #数组转为多维数组 3 行 ,列自动分
np.vstack(A,B) #竖着拼
np.hstack(A,B) #横着拼
np.hsplit(a,3) #横着切
np.vsplit(b,3) #竖着切
np.hsplit(a,(3,4)) #3,4是切分的点

id(a) # 查看内存地址是不是一样

c = a.view();
c.shape=2.6 # 浅复制 地址不同 但会共享数据

d = a.copy(); #深复制

===================================================
a = np.arange(0,40,10)
print(a)
b = np.tile(a,(4,3)) //重复4行3列的矩阵
print(b)

np.sort(axis=1) # 排序
j=np.argsort(a) # 返回排序之后的索引值数组

=========================================================

numpy模块中的矩阵对象为numpy.matrix,包括矩阵数据的处理,矩阵的计算,以及基本的统计功能,转置,可逆性等等,包括对复数的处理,均在matrix对象中。 class numpy.matrix(data,dtype,copy):返回一个矩阵,其中data为ndarray对象或者字符形式;dtype:为data的type;copy:为bool类型。

>>> a = np.matrix('1 2 7; 3 4 8; 5 6 9')
>>> a             #矩阵的换行必须是用分号(;)隔开,内部数据必须为字符串形式(‘ ’),矩
matrix([[1, 2, 7],       #阵的元素之间必须以空格隔开。
[3, 4, 8],
[5, 6, 9]])

>>> b=np.array([[1,5],[3,2]])
>>> x=np.matrix(b)   #矩阵中的data可以为数组对象。
>>> x
matrix([[1, 5],
[3, 2]])
===========================================================================

numpy 教程参考:http://www.yiibai.com/numpy/

原文地址:https://www.cnblogs.com/minsons/p/7753030.html