第一章1.Python安装第三方库
pip install bs4 -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install requests -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install lxml -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install numpy -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install scipy -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install pandas -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install scikit-learn -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install PIL -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple Pillow
pip install Matplotlib -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install requests -i https://pypi.tuna.tsinghua.edu.cn/simple
1.3.1 numpy
scikit-learn是使用numpy数组形式的数据进行处理的,所以需要把数组转换成nump数组的形式。
import numpy
print("使用列表生成一堆数组")
data = [1,2,3,4,5,6]
print(x)#打印数组
print(x.dtype)#数组类型
print("使用列表生成二维数组")
data = [[1,2],[3,4],[5,6],[7,8]]
x= numpy.array(data)
print(x)#打印数组
print(x.ndim)#数组维度
print(x.shape)#数组每个维度的长度
1.3.2 scipy
·scipy是Python中用于进行科学计算的工具集,可以实现计算统计学分步、信号处理、计算线性代数方程等。
·sklearn需要使用scipy来实现算法的计算,使用到最多的是scipy中的sparse,使用spares函数用来生成稀疏矩阵,稀疏矩阵是用来存储那些大部分数值为0的数组。
import numpy as np
from scipy.sparse import csr_matrix
from scipy.sparse import csc_matrix
# csr 按行压缩 row
indptr = np.array([0,2,3,6]) #用于计算行/列的非零数的数量
indices = np.array([0,2,2,0,1,2]) #行/列的索引
data = np.array([1,2,3,4,5,6]) #数值
a = csr_matrix((data,indices,indptr),shape=(3,3)).toarray()
b = csr_matrix(a)
print("原始矩阵a为:\n",a)
print("按行压缩csr稀疏矩阵b为:\n",b)
# csc 按列压缩 column
a2 = csc_matrix((data,indices,indptr),shape=(3,3)).toarray()
b2 = csc_matrix(a2)
print("原始矩阵a为:\n",a2)
print("按列压缩csc稀疏矩阵b为:\n",b2)
csr---按行压缩 | csc---按列压缩 | |
indptr = np.array([0,2,3,6]) | ||
indptr[1]-indptr[0] = 2-0 = 2 | 第1行有2个非零元素 | 第1列有2个非零元素 |
indptr[2]-indptr[1] = 3-2 = 1 | 第2行有1个非零元素 | 第2列有1个非零元素 |
indptr[3]-indptr[2] = 6-3 = 3 | 第3行有3个非零元素 | 第3列有3个非零元素 |
indices = np.array([0,2,2,0,1,2]) | ||
indices[indptr[0]:indptr[1]] = indices[0:2] = [0,1] | 第1行的非零元素的列索引是0,2, 索引是[0,0],[0,1] | 第1列的非零元素的行索引是0,2, 索引是[0,0],[2,0] |
indices[indptr[1]:indptr[2]] = indices[2:3] = [2] | 第2行的非零元素的列索引是2, 索引是[1,2] | 第2列的非零元素的行索引是2, 索引是[2,1] |
indices[indptr[2]:indptr[3]] = indices[3:6] = [3,4,5] | 第3行的非零元素的列索引是3,4,5,索引是[2,3],[2,3],[3,5] | 第3列的非零元素的行索引是3,4,5,索引是[3,2],[4,2],[5,2] |