- Numpy库的使用
Numpy库和Pandas库均是python机器学习中不可缺少的一个包,其重要性我就不详细说明,直接上干活
在本文中,直接套用线性代数的中矩阵代替原文中Numpy array
python下使用Numpy,首先需要引入numpy库
import numpy as np
# 以下效果相同
import numpy
python下Numpy元素的类型
import numpy as np
# arange函数是生成0-14的排列
test_numpy = np.arange(15).reshape(3, 5)
print(type(test_numpy))
# 输出的结果为
ndarray.ndim 函数,求解矩阵的维数
import numpy as np
test_numpy = np.arange(15).reshape(3, 5)
test_ndim = test_numpy.ndim
print(test_ndim)
# 输出的结果为 2
ndarray.shape 函数,求解矩阵的规模,通常情况用元组表示每一维的大小,比如一个3*2的矩阵求解结果为(3,2)
import numpy as np
test_numpy = np.arange(15).reshapes(3, 5)
print(type(test_numpy.shape))
# 输出结果为
print(test_numpy.shape)
# 输出结果为 (3, 5) Tip:有些版本会输出(3L, 5L)
ndarray.size 函数,返回矩阵元素的个数,等于ndarray.shape元素之积
import numpy as np
test_numpy = np.arange(15).reshapes(3, 5)
print(test_numpy.size)
# 输出结果为 15
ndarray.dtype 函数,返回矩阵中元素的类型,类型可以是自己创建的类型或者是标准的python类型,在Numpy中也有自己的类型,有numpy.int32, numpy.int16, numpy.float64等等类型
import numpy as np
test_numpy = np.arange(15).reshapes(3, 5)
print(test_numpy.dtype)
# 输出结果为 dtype('int32')
print(test_numpy.dtype.name)
# 输出结果为 int32
ndarray.itemsize函数,返回矩阵中每个元素所占的字节数,如同C语言中的sizeof(int)所占4个字节,ndarray.dtype表示当前元素的类型为int32,因此占32/8=4个字节
import numpy as np
test_numpy = np.arange(15).reshapes(3, 5)
print(test_numpy.itemsize)
# 输出结果为 4
import numpy as np
test_numpy = np.arange(15).reshapes(3, 5)
print(test_numpy)
# 输出结果 表明在内存中的具体情况
import numpy as np
test_numpy = np.array([1, 2, 3, 4])
# 此种方法是错误的 np.array(1, 2, 3, 4)
test_numpy_two = np.array([(1, 2, 3), (4, 5, 6)])
import numpy as np
test_numpy = np.array([1, 2], [3, 4], dtype=complex)
# test_numpy为 array([[1.+0.j, 2.+0.j], [3.+0.j, 4.+0.j]])
import numpy as np
test_numpy_1 = np.zeros((3, 4))
# 注意此处传入的参数是(3, 4),而非3,4
test_numpy_2 = np.zeros((3, 4), dtype=np.int32)
import numpy as np
test_numpy_1 = np.zeros((3, 4))
test_numpy_2 = np.zeros((3, 4), dtype=np.int32)
import numpy as np
test_numpy = np.arange(0, 15, 1)
import numpy as np
test_numpy = np.linspace(0, 15, 16)
import numpy as np
numpy_test = np.arange(15)
print(numpy_test)
矩阵的基本运算和线性代数里面矩阵的运算一致,不明白的建议翻阅《线性代数》一书
import numpy as np
test_numpy_a = np.array([5, 4, 3, 2])
test_numpy_b = np.array([4, 3, 2, 1])
# 矩阵的加法
test_numpy_c = test_numpy_a + test_numpy_b
# 此时test_numpy_c为 array([9, 7, 5, 3])
# 矩阵的减法
test_numpy_d = test_numpy_a - test_numpy_b
# 此时test_numpy_d为 array([1, 1, 1, 1])
#矩阵的数乘
test_numpy_e = test_numpy_a * 2
# 此时的test_numpy_c为 array([10, 8, 6, 4])