定义可视化函数
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import math
from matplotlib import cm
def visualize_2D(array, vmax, vmin):
fig_width = math.ceil(array.shape[1] * 0.5)
fig_length = math.ceil(array.shape[0] * 0.5)
fig, ax = plt.subplots(figsize = (fig_width, fig_length))
sns.heatmap(array,
vmax = vmax,
vmin = vmin,
annot = True,
fmt = '.0f',
square = True,
cmap = 'RdYlBu_r',
linewidth = .5,
cbar = False,
xticklabels = False,
yticklabels = False,
ax = ax)
def visual_1D(array):
fix, ax = plt.subplots()
colors = cm.RdYlBu_r(np.linspace(0, 1, len(array)))
for idx,num in enumerate(array):
circle_idx = plt.Circle((idx, 0 ),
0.5,
facecolor = colors[idx],
edgecolor = 'w')
ax.add_patch(circle_idx)
ax.text(idx, 0, s = str(array[idx]),
horizontalalignment = 'center',
verticalalignment = 'center'
)
ax.set_xlim(-0.6, 0.6 + len(array))
ax.set_ylim(-0.6, 0.6)
ax.axis('off')
ax.set_aspect('equal', adjustable = 'box')
1.一维数组
索引 行向量、列向量、切片、整数索引、切片、布尔索引切片
a = np.arange(-5, 6)
visual_1D(a)
a.shape
(11,)
a[0],a[-11],a[10],a[-1]
(-5, -5, 5, 5)
行向量、列向量
升维 a[:,np.newaxis] 让数组当前增加一个维度
降维 np.squeeze() 用来给压缩数组shape为1的维度
visualize_2D(a[:,np.newaxis],5,-5)
a[:,np.newaxis]
array([[-5],
[-4],
[-3],
[-2],
[-1],
[ 0],
[ 1],
[ 2],
[ 3],
[ 4],
[ 5]])
visualize_2D(a[np.newaxis,:],5,-5)
a[np.newaxis,:]
array([[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]])
a[np.newaxis,:].ndim
2
a[:,np.newaxis,np.newaxis].shape,np.squeeze(a[:,np.newaxis,np.newaxis]).ndim
((11, 1, 1), 1)
切片
visual_1D(a[0:3])
visual_1D(a[::2]) #奇数
visual_1D(a[1::2]) #偶数
visual_1D(a[::-1]) #倒序输出
整数索引
visual_1D(a[np.r_[0,1,2,-1]])
visual_1D(a[[0,1,2,-1]])
布尔索引、切片
visual_1D(a[a>0])
visual_1D(a[a<0])
2.二维数组
A_2D = np.array([[-7,-6,-5,-4,-3],
[-2,-1, 0, 1, 2],
[ 3, 4, 5, 6, 7]])
visualize_2D(A_2D, 7 , -8)
取出行
visualize_2D(A_2D[:1,:],7,-1)
visualize_2D(A_2D[2:3,:],7,-1)
取出列
visualize_2D(A_2D[:,:1],7,-7)
visualize_2D(A_2D[:,2:],7,-7)
同时对行列进行操作
visualize_2D(A_2D[1:2,1:3],7,-7)
标签:Numoy,索引,2D,002,visual,1D,newaxis,np,array
From: https://www.cnblogs.com/baidh/p/18115823