1.导入
机器学习中的数据——矩阵 h w
一行对应一个样本,一列对应一个特征(指标)
如何在计算机中进行保存? 具体而言,如何利用Python进行保存——矩阵。
而Numpy则可以进行许多的矩阵运算,且效率较高。
2.基本使用
2.1 导入数据
2.1.1 从文件导入
import numpy
world_alcohol = numpy.genfromtxt("world_alcohol.txt" , delimiter="," , dtype=str)
print(type(world_alcohol))
print(world_alcohol)
print(help(numpy.genfromtxt))
- 导入科学计算库
- genfromtxt函数的使用 数据文件所在位置、数据分隔符、数据类型
- type ndarray ---- numpy中最核心的结构 可以看作是一个list of list,也就是一个矩阵
- 函数的帮助文档 help(函数) 参数、举例
2.1.2 固定写入
vector = numpy.array([5,10,15,20])
matrix = numpy.array([[5,10,15],[20,25,30],[35,40,45]])
print vector
#(4,)
print(vector.shape)
print matrix
#(3,3)
print(matrix.shape)
- array函数 导入后均为ndarray格式
- 值得注意的一点是,之前一直在说ndarray是一个矩阵,即python中的list of list结构,但与python中可以存不同数据类型的list不同,array中只能存放相同的数据类型
- shape 描述矩阵的格式 debug时非常重要
2.2 数据选取----索引
注意的一点是索引是从0开始的,即[0]即代表了第一个样本
third_country = world_alcohol[2,2]
#第三个样本的第三项
切片 左闭右开区间
2.2.1 一维数组
vector = numpy.array([5,10,15,20])
#切片 左闭右开区间 [5 10 15]
print(vector[0:3])
2.2.2 矩阵
matrix = numpy.array([
[5,10,15],
[20,25,30],
[35,40,45]
])
取某一列 相当于取所有样本的同一特征 :表示所有(all) [10 25 40]
print(matrix[:,1])
取某两列 0:2相当于切片 左闭右开 相当于取了第0列和第1列 so不相邻怎么取?
print(matrix[:,0:2])