Python && 机器学习基础

Python && 机器学习基础

numpy

numpy 的数据结构
  • import numpy:引入numpy库
  • numpy.genfromtxt() : 使用numpy打开一个txt文件
  • print(help(numpy.genfromtxt)): 打印genfromtxt()的帮助文档
  • numpy.array(): 数组结构
    • numpy.array([8, 3, 7, 1]): 创建一维数组
    • numpy.array([[2, 5, 3],[12, 6, 76]]): 创建二维数组
    • numpy.array()属性:
      • .shape->显示array的维度;
      • .dtype ->显示array中的数据类型
      • numpy.array[1, 4]: 取出第一行第四列的元素(index从0开始计算)
      • numpy.array(xxx)[0:3]: 取向量的前三个值(切片,左闭右开)
      • numpy.array(xxx)[ : , 3]: 取多维向量所有样本的第三个值
      • array中的元素类型要统一,否则numpy会将值的类型自动转换
numpy的基本操作
  1. 当进行 +-*/==!= 等逻辑判断时,numpy会对array中所有元素进行判断。
import numpy
vector = numpy.array([5,10,6,7])
vector == 10
#output: array([False, true, False, False], dtype = bool) 
  1. numpy.array()的判定结果可以被当成是index,从而取得结果为true的值。
import numpy
vector = numpy.array([2,6,10,9])
#将结果为true的结果的index赋值给ten变量
ten = (vector == 10)
print(vector[ten])
#output:[10]
  1. &| 逻辑运算
  2. 类型转换
    • .astype(float):转换成float类型
  3. 最大值和最小值
    • .min()
    • .max()
  4. 求和
    • .sum(axis = 1): 按行求和,.axis = 0 则按列求和
  5. 矩阵变换
    • .reshape(r, c): reshape the array to r rows and c columns.
  6. 矩阵维度
    • .ndim:输出矩阵的维度
  7. 矩阵大小
    • .size: 返回矩阵中的元素个数。
矩阵操作

numpy.zeros((a,b)):创建一个 a 行 b 列的 0 矩阵

#创建一个起始值为10,终止值为20,步长为2的矩阵
numpy.arange(10,20,2)
#output:array([10, 12, 14, 16, 18])
#生成2行3列的随机矩阵,元素值在+1和-1之间
#random.random():在random模块下使用random函数
numpy.random.random((2,3))
#output:array([[ 0.25712849,  0.52280068,  0.37931522],[ 0.37061583,  0.66376507,  0.33100993]])

.linespace(a, b, c):在起始值 a 与终点值 b 之间平均得到 c 个元素。
**n:取n次方
A*B: 矩阵A和B求内积, 对应项相乘
A.dot(B): 矩阵的点乘
numpy. dot(A, B): 同A.dot(B)

numpy的常用函数
  • numpy.exp(A): 对矩阵A求指数函数
  • numpy.sqrt(A):对矩阵A求根
  • numpy.floor():向下取整
  • A.ravel(): 将A矩阵变换成一个向量
  • A.T: 取矩阵A的转置
  • numpy.vstack((A,B)):将A和B按照行进行拼接
  • numpy.hstack((A,B)):将A和B按照列进行拼接
  • numpy.hsplit(A,3): 将A矩阵按照列平均分成3份
  • numpy.vsplit(A,3): 将A矩阵按照行平均分成3份
  • numpy.vsplit(A,(3,4)): Split A after 3rd and 4th row
  • numpy.hsplit(A,(3,4)): Split A after 3rd and 4th column

  • array的复制

    • A=B: 将B复制给A, 复制之后A和B的id相同, AB共用一种数据
    • A=B.view(): 将B复制给A, 复制之后A和B的id不同, 但是AB仍然共用一组数据
    • A = B.copy():将B复制给A, 复制之后A和B的id不同, AB不共用一组数据
  • .argmax(axis=0):返回当前array每一行最大的元素的index
  • .argmax(axis=1):返回当前array每一列最大的元素的index
  • .tile(): 复制粘贴
  • A.sort(axis=0):对A的每一行进行从小到大的排序
  • numpy.argsort(A): 按照索引值进行排序

pandas

pandas主要用于数据的处理

pandas数据选择
  • pandas.read_csv("food_info.csv"): 读取csv文件
  • .head(n):得到数据的前n行
  • .tail(n): 得到数据的尾n行
  • .columns: 返回列名
  • .shape: 返回行列数
  • .loc[n]: 取得第n行数据
#通过列名索引,得到列的切片
ndb_col = food_info("NDB_NO")
#在food_info文件中查找名称为"NDB_NO"的列并返回
  • .endwith(): 取得特定结尾的行
pandas数据类型
  • object: For String values
  • int: For integer values
  • float: For float values
  • datetime: For time values
  • bool: for boolean values
pandas数据预处理
  • .sort_values("column", inplace=True): 以column列为基准进行排序, inplace= True即新生成结果, 不会替换原有结果, 默认为升序排列
  • .sort_values("column", inplace=True ascending = False): 同上, 但是为降序排列
  • .isnull(): 判断是否有缺失值
  • len():统计个数
  • .mean():求平均值, 忽略缺失值
  • pivot_table(index="basic standard", values="statistic", aggfunc= way): 以 basic standard为基准, 通过way的方式统计 statistic 数据, aggfunc默认为mean
  • dropna(axis = 1):去掉指定列的缺失值样本
  • .apply():执行一个自定义的函数, 用于调用函数
def hundredth_row(column):
    #Extract the hundredth item
    hundredth_item = column.loc[99]
    return hundredth_item

hundredth_row = titanic_survival.apply(hundredth_row)
print hundredth_row

Matplotlib

Matplotlib画折线图
imoprt pandas
#import the pyplot library in matplotlib
import matplotlib.pyplot as plot
#read the .csv file
unrate = pandas.read_csv('unrate.csv')
#transfer the DATE column in .csv file to datetime version by using the function to_datetime
unrate['DATE'] = pandas.to_datetime(unrate['DATE'])
#plot nothing
plot.plot()
#show the canvas
plot.show()
figure = unrate[0: 12]
plot.plot(figure['DATE'], figure['VALUE'])
plot.show()
plot.xticks(rotation = 45)

.plot(x , y): 画折线图, 以 x 参数为 x 轴, 以 y 参数为 y 轴
.xticks(rotation = XX): 变换坐标的角度, 转换XX角度
xlable('XXXX'): add lable to x-axis which indicates the name of x - axis
ylable('XXXX'): add lable to y-axis which indicates the name of y - axis
.title('XXXX'): add the title to the whole chart

Matplotlib 画子图

.add_subplot(r, c, x): 添加 r 行, c 列个子图, 并选择第 x 个子图画图
figure(figsize = (3,3)):指定子图的长和宽
.plot(x, y, c='', lable = label): c 参数指定画出折现的color, 当需要在同一个子图中华多个折线时, 只需要 plot 多次即可, 使用lable参数为每个单独的折线添加label, 但是此时label并不会立即显示
.legend(loc = 'XXX'): 将plot中的label显示在折线图的XXX位置

Matplotlib散点图和柱形图
  1. 柱形图
    .bar(position, height, width):生成柱形图, 以positon作为柱形图中每个柱离远点的距离, 以height作为每个柱的高度, width作为每个柱的宽度
    .barh(position, height, width):画横向柱形图
  2. 散点图
    .scatter(x,y): x作为x轴参数, y作为y轴参数画散点图
Matplotlib柱形图与盒图
  1. 柱形图
    .hist(XXX, bins= ): 画出区间数量为bins的柱形图, bins的默认值为10
    .set_ylim(a,b):设定y轴的区间为[a: b]
  2. 盒图
    boxplot():画盒图
Matplotlib细节设置

tick_param(bottom="", top="", left="", right=""):去掉轴标线
(a/255, b/255, c/255):获取值为abc的颜色参数

Reference

以上内容, 摘自
http://edu.csdn.net/course/play/6108/114224

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值