Sweety

Practice makes perfect

导航

ML&DL必备之numpy & matplotlib

Posted on 2018-01-26 22:16  蓝空  阅读(251)  评论(0编辑  收藏  举报

在学习machine learing 和Deep learning的时候不免会有一些数据的操作,科学计算和一些矩阵的操作需要用到numpy,而如果想可视化的时候,比如效果展示和调参的时候就需要画图,所以我们plot的的时候就需要用到一个很强大的包,叫matplotlib,今天对这两个包展开说明,都时经常用到的一些简单的操作!

numpy集锦

属性


array = np.array([[1,2,3],[2,3,4]])  #列表生成矩阵
array.ndim # 几维 2
array.shape #长宽 (23)
array.size #元素个数  6

创建array

np.array([1,2,3],dytpe = np.int) #int32 int64 float32
np.zeros((3,4)) #3行4列 全为0
np.ones((3,4),dtype=int) #同理
np.empty((3,4)) #几乎为0 的矩阵
np.arange(10,20,2) #起始 结束 步长 类似于python中的range  10 12 14 16 18
np.arange(12).reshape(3,4)  #生成矩阵3行4列
A.flat #将矩阵转变为一个向量 返回迭代器
A.flatten #将矩阵转变为一个向量  返回列表
np.linspace(1,10,20) #1到10分20段 生成20个数
np.random.random((2,4))  #随机生成2行4列的矩阵
np.random.normal(0, 0.05, x_data.shape)

基础运算


+ - * 
** #平方
np.sin()
print(b<3) #b是矩阵 返回[true,false,...]
a*b #矩阵点乘 a,b分别为矩阵
np.dot() 或 a.dout(b) #矩阵相乘
np.sum(arg1,arg2)    #arg1是矩阵,arg2是行(0)或者列(1)
np.min(arg1,arg2)      
np.max(arg1,arg2)
np.mean(A) 或A.mean() 或 np.average(A) 
np.median(A) #中位数
np.cumsum(A) #求前n个元素的和 [[1,2,3],[4,5,6]] => [1,3,6,10 ...]
np.diff(A)  #相邻差 
np.argmin()  #最小值的索引
np.sort(A)  #逐行排序
np.transport(A) 或 A.T #转置
np.clip(A,5,9)  #小于5的转成5,大于9的转成9,中间不变

索引

A[1][2] 或 A[1,2]
A[:,1] 第一列说有数
A[1,1:2] 第一行第1 2列

array 合并

A = np.array([1,1,1])
B= np.array([2,2,2])
np.vstack((A,B))  #上下合并 => [[1,1,1],[2,2,2]]
np.hstack((A,B))  #左右合并 => [1,1,12,2,2]]
np.concatenate((A,B,A,B),axis=1) #多个合并  第二个参数是维度
A[:,np.newaxis] #在纵向增加一个维度

array 分割

np.split(A,片段个数,axis=?)  #等量分割
np.array_split(A,片段个数,axis=?  #不等量分割
np.vsplit(A,片段个数) #纵向分割
np.hsplit(A,片段个数) #横向分割

复制

python赋值(=)存在关联性   numpy copy
copy() #没有关联的赋值 deep copy 

matplotlib集锦

example

#example
import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(-3,3,50)
y1=2*x+1
y2=x**2
plt.figure(num=?,figsize=(8,5)) #下面的在一张图里
plt.plot(x,y1)
plt.plot(x,y2,color='red',linewidth=1.0,linestyle='- -')

plt.figure(num=?,figsize=(8,5))#下面的在一张图里
plt.plot(x,y2)
plt.show()

简单修改坐标轴

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2

plt.figure()
plt.plot(x, y2)
# plot the second curve in this figure with certain parameters
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
# set x limits
plt.xlim((-1, 2))
plt.ylim((-2, 3))
plt.xlabel('I am x')
plt.ylabel('I am y')

# set new sticks
new_ticks = np.linspace(-1, 2, 5)
print(new_ticks)
plt.xticks(new_ticks)
# set tick labels
plt.yticks([-2, -1.8, -1, 1.22, 3],
           [r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$']) #机器可读数学表示字体  很像LaTeX
plt.show()

这里写图片描述

修改坐标轴进阶

修改坐标轴的位置

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2

plt.figure()
plt.plot(x, y2)
# plot the second curve in this figure with certain parameters
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
# set x limits
plt.xlim((-1, 2))
plt.ylim((-2, 3))

# set new ticks
new_ticks = np.linspace(-1, 2, 5)
plt.xticks(new_ticks)
# set tick labels
plt.yticks([-2, -1.8, -1, 1.22, 3],
           ['$really\ bad$', '$bad$', '$normal$', '$good$', '$really\ good$'])
# to use '$ $' for math text and nice looking, e.g. '$\pi$'

# gca = 'get current axis'
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')

ax.xaxis.set_ticks_position('bottom')
# ACCEPTS: [ 'top' | 'bottom' | 'both' | 'default' | 'none' ]

ax.spines['bottom'].set_position(('data', 0))
# the 1st is in 'outward' | 'axes' | 'data'
# axes: percentage of y axis
# data: depend on y data

ax.yaxis.set_ticks_position('left')
# ACCEPTS: [ 'left' | 'right' | 'both' | 'default' | 'none' ]

ax.spines['left'].set_position(('data',0))
plt.show()

这里写图片描述

图例

在example基础上修改
plt.plot(x, y1, label=’linear line’) #增加了label
plt.plot(x, y2, color=’red’, linewidth=1.0, linestyle=’–’, label=’square line’) #增加了label
plt.legend(loc=’best’) #自动找一个比较合适的位置

散点图

import matplotlib.pyplot as plt
import numpy as np


n = 1024

X = np.random.normal(0,1,n)
Y = np.random.normal(0,1,n)
T = np.arctan2(Y,X) #for color value

plt.scatter(X,Y,s=75,c=T,alpha=0.5)

plt.xlim(-1.5,1.5)
plt.ylim(-1.5,1.5)

plt.xticks(())#让坐标消失
plt.yticks(())

plt.show()

这里写图片描述

subplot多合一显示

均匀

#两行两列
plt.figure(figsize=(6, 4))
# plt.subplot(n_rows, n_cols, plot_num)
plt.subplot(2, 2, 1) #行 列  第几个
plt.plot([0, 1], [0, 1])

plt.subplot(2,2,2)
plt.plot([0, 1], [0, 2])

plt.subplot(2,2,3)
plt.plot([0, 1], [0, 3])

plt.subplot(2,2,4)
plt.plot([0, 1], [0, 4])

plt.tight_layout()

不均匀

plt.figure(figsize=(6, 4))
# plt.subplot(n_rows, n_cols, plot_num)
plt.subplot(2, 1, 1)  #两行,一列,第一个
# figure splits into 2 rows, 1 col, plot to the 1st sub-fig
plt.plot([0, 1], [0, 1])

plt.subplot(2,3,4)#两行 三列 第4个
# figure splits into 2 rows, 3 col, plot to the 4th sub-fig
plt.plot([0, 1], [0, 2])

plt.subplot(2,3,5)
# figure splits into 2 rows, 3 col, plot to the 5th sub-fig
plt.plot([0, 1], [0, 3])

plt.subplot(2,3,6)
# figure splits into 2 rows, 3 col, plot to the 6th sub-fig
plt.plot([0, 1], [0, 4])

这里写图片描述