matplotlib与seaborn的一些使用

1.plt.plot画线画点 

a = np.array([[1, 2], [3, 4]])
print(a[:, 0])
plt.plot(a[:, 0], a[:, 1])
plt.show()
plt.plot(a[:, 0], a[:, 1],  'o',color='red')
plt.show()#添加风格
plt.plot(x,y,color='red',linewidth=1.0,linestyle='--')
#设置x轴范围
plt.xlim((-1,2))
# 设置y轴范围
plt.ylim((-2, 3))

#标题变为figure3,长宽为8,5
plt.figure(num=3,figsize=(8,5))
a = np.array([[1, 2], [3, 4]])
plt.plot(a[:, 0], a[:, 1])
plt.show()

2.plt.scatter散点图

n=1024
X=np.random.normal(0,1,n)
Y = np.random.normal(0, 1, n)
print(Y)
T=np.arctan2(Y,X) #for color value
#c表示颜色序列
plt.scatter(X,Y,s=75,c=T,alpha=0.5)
#不要坐标刻度
plt.xticks(())
plt.yticks(())
plt.show()

3.生成柱状图

方法1:

"""生成柱状图"""
def write_bar():num_list = [0.42974282, 0.08665644 ,0.39311899 ,0.09048176]name_list=['pig_length','pig_photo_center','disk_length','disk_photo_center']plt.ylabel('feature importance')plt.bar(range(len(num_list)), num_list,tick_label=name_list)# plt.xticks(name_list,rotation = 20)plt.xticks(rotation = 20)plt.show()

方法2:

name_list = ['detected', 'Undetectable']
num_list = [91,134-91]
rects = plt.bar(range(len(num_list)), num_list, color='gr')
# X轴标题
index = [0, 1]
plt.xticks(index, name_list)
plt.ylabel('photos')  # X轴标签
for rect in rects:height = rect.get_height()plt.text(rect.get_x() + rect.get_width() / 2, height, str(height), ha='center', va='bottom')
plt.show()

方法3(推荐使用):


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt_, count_values = np.unique([1, 1, 2, 2, 2, 3], return_counts=True)
print('count_values:', count_values)class_names = ['mountain', 'street', 'glacier']#柱状图
pd.DataFrame({'train': count_values,'test': count_values},index=class_names).plot.bar()
plt.show()

4.直方图

    import numpy as npimport matplotlib.mlab as mlabimport matplotlib.pyplot as plt# example datamu = 100  # mean of distributionsigma = 15  # standard deviation of distributionx = mu + sigma * np.random.randn(10000)num_bins = 50# the histogram of the datan, bins, patches = plt.hist(x, num_bins, normed=1, facecolor='blue', alpha=0.5)# add a 'best fit' liney = mlab.normpdf(bins, mu, sigma)plt.plot(bins, y, 'r--')plt.xlabel('Smarts')plt.ylabel('Probability')plt.title(r'Histogram of IQ: $\mu=100$, $\sigma=15$')## Tweak spacing to prevent clipping of ylabelplt.subplots_adjust(left=0.15)plt.show()import seaborn as snssns.set_palette("hls")  # 设置所有图的颜色,使用hls色彩空间sns.distplot(x, kde_kws={'label':"label"},color="r", bins=30, kde=True)plt.xlabel('Smarts')plt.ylabel('Probability')plt.title(r'Histogram of IQ: $\mu=100$, $\sigma=15$')plt.show()

示例:产生均值为0,标准差为0.1的10000个点 

mu, sigma = 0, 0.1
y=np.random.normal(mu, sigma,10000)
count, x, ignored=plt.hist(y,bins=50,density=True)
plt.plot(x, 1/(sigma * np.sqrt(2 * np.pi)) * np.exp( - (x - mu)**2 / (2 * sigma**2) ),
linewidth=2, color='r')
plt.show()

"""长度误差直方图"""
pig_length_list = list(map(float, pig_length_list))
pig_error_list = list(map(float, pig_error_list))
print(len(pig_error_list))
# sns.distplot(pig_error_list, hist=True, kde=True)
r=plt.hist2d(pig_length_list,pig_error_list,bins=(30,30),cmap=plt.cm.jet)
plt.xlabel('length')
plt.ylabel('Abs Error')
plt.colorbar(r[3])
plt.show()

from matplotlib import colors
r=plt.hist2d(pig_length_list,pig_error_list,bins=(30,30),cmap=plt.cm.jet,norm=colors.LogNorm())
plt.xlabel('length')
plt.ylabel('ABS Error')
plt.colorbar(r[3])
plt.show()

pig_length_list = list(map(float, pig_length_list))
pig_error_list = list(map(float, pig_error_list))
print(len(pig_error_list))
ax = sns.kdeplot(pig_length_list, pig_error_list, cmap=plt.cm.jet, shade=True, cbar=True, n_levels=30)
ax.set(xlabel='real length', ylabel='length abs error',ylim=(-20, 20))
# r=plt.hist2d(pig_length_list,pig_error_list,bins=(30,30),cmap=plt.cm.jet)
# plt.xlabel('length')
# plt.ylabel('ABS Error')
# plt.colorbar(r[3])
plt.show()

"""长度误差密度图"""
pig_length_list = list(map(float, pig_length_list))
pig_error_list = list(map(float, pig_error_list))
print(len(pig_error_list))
ax = sns.kdeplot(pig_length_list, pig_error_list, cmap=plt.cm.jet, shade=True, cbar=True, n_levels=30,shade_lowest=False)
ax.set(xlabel='real length', ylabel='length abs error',ylim=(-20, 20))
# from matplotlib import colors
# r=plt.hist2d(pig_length_list,pig_error_list,bins=(30,30),cmap=plt.cm.jet,norm=colors.LogNorm())
# plt.xlabel('length')
# plt.ylabel('ABS Error')
# plt.colorbar(r[3])
plt.show()

5.绘制3D曲线

from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)
R = X**2 +Y**2
# Z = np.sin(R)# 具体函数方法可用 help(function) 查看,如:help(ax.plot_surface)
ax.plot_surface(X, Y, R, rstride=1, cstride=1, cmap='rainbow')plt.show()

from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X ** 2 + Y ** 2)# 具体函数方法可用 help(function) 查看,如:help(ax.plot_surface)
#rstride行跨 cstride列跨
ax.plot_surface(X, Y, R, rstride=1, cstride=1, cmap='rainbow')#投影 offset把图形压缩到xoy里面,z=0的位置
ax.contourf(X,Y,R,zdir='z',offset=0,cmap='rainbow')
ax.set_zlim(0,4)
plt.show()

from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)
R = X**2 - Y**2
# Z = np.sin(R)# 具体函数方法可用 help(function) 查看,如:help(ax.plot_surface)
ax.plot_surface(X, Y, R, rstride=1, cstride=1, cmap='rainbow')plt.show()

import numpy as np
import matplotlib.pyplot as plt
import math
import mpl_toolkits.mplot3d# x, y = np.mgrid[-2:2:200j, -2:2:200j]
x = np.arange(-6, 6, 0.25)
y = np.arange(-6, 6, 0.25)
x, y = np.meshgrid(x, y)
# z=(1/2*math.pi*3**2)*np.exp(-(x**2+y**2)/2*3**2)
z = np.exp(-(x**2+y**2 - 0)/2*1**2)
ax = plt.subplot(111, projection='3d')
ax.plot_surface(x, y, z, rstride=1, cstride=1, cmap='rainbow', alpha=0.9)#绘面ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.show()

X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)# 具体函数方法可用 help(function) 查看,如:help(ax.plot_surface)
plt.imshow(R)
plt.colorbar()
plt.show()

6.3D直方图

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as npfig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x, y = np.random.rand(2, 100) * 4
hist, xedges, yedges = np.histogram2d(x, y, bins=4, range=[[0, 4], [0, 4]])# Construct arrays for the anchor positions of the 16 bars.
# Note: np.meshgrid gives arrays in (ny, nx) so we use 'F' to flatten xpos,
# ypos in column-major order. For numpy >= 1.7, we could instead call meshgrid
# with indexing='ij'.
xpos, ypos = np.meshgrid(xedges[:-1] + 0.25, yedges[:-1] + 0.25)
xpos = xpos.flatten('F')
ypos = ypos.flatten('F')
zpos = np.zeros_like(xpos)# Construct arrays with the dimensions for the 16 bars.
dx = 0.5 * np.ones_like(zpos)
dy = dx.copy()
dz = hist.flatten()ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='b', zsort='average')plt.show()

7.3D条状图

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as npfig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
for c, z in zip(['r', 'g', 'b', 'y'], [30, 20, 10, 0]):xs = np.arange(20)ys = np.random.rand(20)# You can provide either a single color or an array. To demonstrate this,# the first bar of each set will be colored cyan.cs = [c] * len(xs)cs[0] = 'c'ax.bar(xs, ys, zs=z, zdir='y', color=cs, alpha=0.8)ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')plt.show()

8.plt.legend 

steps = np.linspace(0, np.pi*2, 256, dtype=np.float32)
sin_np = np.sin(steps)
print(sin_np.shape)
cos_np = np.cos(steps)
plt.figure()
plt.title('Sin and Cos',fontsize='18')
plt.plot(steps,sin_np,'r-',label='sin')
plt.plot(steps,cos_np,'b-',label='cos')
plt.legend(loc='best')
plt.show()

9.plt.subplot 

x = np.arange(0, 3 * np.pi, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)# Set up a subplot grid that has height 2 and width 1,
# and set the first such subplot as active.
plt.subplot(2, 1, 1)
# Make the first plot
plt.plot(x, y_sin)
plt.title('Sine')
# Set the second subplot as active, and make the second plot.
plt.subplot(2, 1, 2)
plt.plot(x, y_cos)
plt.title('Cosine')
# Show the figure.
plt.show()

10.等比显示

plt.gca().set_aspect('equal')

11.画饼状图:


#饼状图
plt.pie(count_values,#和类别数相等的labels=class_names,#加上labelautopct='%1.1f%%')#加上百分比
plt.axis('equal')
plt.title('Proportion of each observed category')
plt.savefig('./pie.jpg')
plt.show()

import numpy as np
import matplotlib.pyplot as plty1 = []
y2 = []
y3 = []
years = []
for i in range(7):years.append(i)y1.append(round(25000*np.exp(0.05*i), 2))y2.append(round(25000 * (1 + 0.06) ** (i),2))y3.append(round(25000 * (1+0.02)**(4*i),2))print(y1)
print(y2)
print(y3)
plt.plot(years, y1, color='red', linewidth=1.0, label='option 1')#, linestyle='--')
plt.plot(years, y2, color='green', linewidth=1.0, label='option 2')#, linestyle='--')
plt.plot(years, y3, color='blue', linewidth=1.0, label='option 3')#, linestyle='--')
#设置x轴范围
plt.xlim((0, 10))
# 设置y轴范围
plt.ylim((25000, 40000))
plt.ylabel('Principal and interest')
plt.xlabel('Year')
plt.legend(loc='best')
# plt.yticks(np.linspace(25000, 40000, 500))
plt.savefig('./hu1.jpg')
plt.show()plt.figure(figsize=(20, 8))
# plt.title('Principal and interest')
col = ['year' + str(i) for i in years]
row = ['op1', 'op2', 'op3']
vals = []
vals.append(y1)
vals.append(y2)
vals.append(y3)
vals = np.array(vals)
# colors = ["#e41a1c","#377eb8","#00ccff"]*7
rcolors = plt.cm.BuPu(np.full(3, 0.1))
ccolors = plt.cm.BuPu(np.full(7, 0.1))
tab = plt.table(cellText=vals,colLabels=col,rowLabels=row,rowColours=rcolors,colColours=ccolors,loc='center',cellLoc='center',rowLoc='center')
tab.scale(1, 2)
plt.axis('off')
plt.savefig('./hu2.jpg')
plt.show()op1_interest = y1[-1] - 25000
op2_interest = y2[-1] - 25000
op3_interest = y3[-1] - 25000
def plot_pie(interest, name):plt.figure()plt.title(name)patches, texts, autotexts = plt.pie(x=[interest, 25000],#指定绘图数据colors=["#d5695d", "#5d8ca8"],labels=['Total interest', 'Initial investment'],autopct='%.2f%%',)plt.legend(patches, ['Total interest', 'Initial investment'],  # 添加图例# title="Pie Learning",loc="best",# fontsize=15,bbox_to_anchor=(1, 0, 0.5, 1))plt.savefig('./hu+{}.jpg'.format(name))plt.show()
plot_pie(op1_interest, 'option1')
plot_pie(op2_interest, 'option2')
plot_pie(op3_interest, 'option3')

12.生成两类数据

import torch
import matplotlib.pyplot as plt
from torch import nn, optim
from torch.autograd import Variableimport numpy as npdef produce_data():# 假数据n_data = torch.ones(100, 2)  # 数据的基本形态x0 = torch.normal(2 * n_data, 1)  # 类型0 x data (tensor), shape=(100, 2)y0 = torch.zeros(100)  # 类型0 y data (tensor), shape=(100, 1)x1 = torch.normal(-2 * n_data, 1)  # 类型1 x data (tensor), shape=(100, 1)y1 = torch.ones(100)  # 类型1 y data (tensor), shape=(100, 1)print(x0.shape)# 注意 x, y 数据的数据形式是一定要像下面一样 (torch.cat 是在合并数据)x = torch.cat((x0, x1), 0).type(torch.FloatTensor)  # FloatTensor = 32-bit floatingprint(x.shape)y = torch.cat((y0, y1), 0).type(torch.FloatTensor)  # LongTensor = 64-bit integerprint(y.shape)# 画图plt.scatter(x.data.numpy()[:, 0], x.data.numpy()[:, 1], c=y.data.numpy(), s=100, lw=0, cmap='RdYlGn')plt.show()return x, y
if __name__ == '__main__':produce_data()

13.plot的一些应用

import numpy as np
import matplotlib.pyplot as plt
import matplotlib
x = np.arange(-4,4,0.5)
# print(x)
# fname 为 你下载的字体库路径,注意 SimHei.ttf 字体的路径
zhfont1 = matplotlib.font_manager.FontProperties(fname='/usr/share/fonts/truetype/arphic/uming.ttc')
plt.rcParams['xtick.direction'] = 'in'#将x周的刻度线方向设置向内
plt.rcParams['ytick.direction'] = 'in'#将y轴的刻度方向设置向内plt.axis([-3, 3, -2, 3])
# plt.title("Matplotlib demo")
plt.xlabel("输入",fontproperties=zhfont1)
plt.ylabel("输出",fontproperties=zhfont1)sigmoid_y = 1/(1+np.exp(-x))
print(sigmoid_y)plt.plot(x,sigmoid_y,'s',color='black',label='Sigmoid')
# plt.show()tanh_y = (np.exp(x)-np.exp(-x))/(np.exp(x)+np.exp(-x))
print(tanh_y)
# plt.rcParams['xtick.direction'] = 'in'#将x周的刻度线方向设置向内
# plt.rcParams['ytick.direction'] = 'in'#将y轴的刻度方向设置向内
plt.plot(x,tanh_y,'.-',color='black',label='Tanh')
# plt.show()relu_y = [i if i>0 else 0 for i in x ]
print(relu_y)
# plt.rcParams['xtick.direction'] = 'in'#将x周的刻度线方向设置向内
# plt.rcParams['ytick.direction'] = 'in'#将y轴的刻度方向设置向内
plt.plot(x,relu_y,'-',color='black',label='Relu')
# plt.show()elu_y = [i if i>0 else 0.3*(np.exp(i)-1) for i in x ]
print(elu_y)
# plt.rcParams['xtick.direction'] = 'in'#将x周的刻度线方向设置向内
# plt.rcParams['ytick.direction'] = 'in'#将y轴的刻度方向设置向内
plt.plot(x,elu_y, '^',color='black',label='Elu')
plt.legend(loc='best')
# plt.show()
plt.savefig('hha.jpg')

14-1.ax画3d图与线段等比缩放


import matplotlib.pyplot as plt
ax = plt.subplot(111, projection='3d')point_a = np.array([[1, 2, 3],[2, 2, 2]]).astype(np.float32)
point_ori_a_length = np.linalg.norm(point_a[1, :] - point_a[0, :])point_b = np.array([[2, 2, 2],[5, 5, 5]]).astype(np.float32)
point_ori_b_length = np.linalg.norm(point_b[1, :] - point_b[0, :])
print('==point_ori_a_length:', point_ori_a_length)
print('==point_ori_b_length:', point_ori_b_length)
print('==point_ori_b_length / point_ori_a_length:', point_ori_b_length / point_ori_a_length)ax.plot(point_a[:, 0], point_a[:, 1], point_a[:, 2])
ax.plot(point_b[:, 0], point_b[:, 1], point_b[:, 2])
plt.xlim(1, 6)
plt.ylim(1, 6)
ax.set_zlim(1, 6)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.show()ax = plt.subplot(111, projection='3d')point_a[1, :] = point_a[0, :] + (point_a[1, :] - point_a[0, :]) / point_ori_a_lengthpoint_b[1, :] = point_b[0, :] + (point_b[1, :] - point_b[0, :]) / point_ori_a_length
dis_ = point_b[1, :] - point_b[0, :]
point_b[0, :] = point_a[1, :]
point_b[1, :] = point_b[0, :] + dis_
point_now_a_length = np.linalg.norm(point_a[1, :] - point_a[0, :])
point_now_b_length = np.linalg.norm(point_b[1, :] - point_b[0, :])
print('==point_now_a_length:', point_now_a_length)
print('==point_now_b_length:', point_now_b_length)
print('==point_now_b_length / point_now_a_length:', point_now_b_length / point_now_a_length)
ax.plot(point_a[:, 0], point_a[:, 1], point_a[:, 2])
ax.plot(point_b[:, 0], point_b[:, 1], point_b[:, 2])
plt.xlim(1, 6)
plt.ylim(1, 6)
ax.set_zlim(1, 6)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.show()

  

  

14-2.显示3d手同时用ax.text显示序号

注意的是cv2放在plt后面


import matplotlib.pyplot as plt
import cv2
import mpl_toolkits.mplot3d
import numpy as npcamera_hand_right_3dkpts = np.array([[0.8647481799125671, -38.08830642700195, 335.964599609375], [0.6563963294029236, -38.625457763671875, 332.47576904296875], [0.14763949811458588, -40.26291275024414, 328.74615478515625], [0.006336620077490807, -42.1802978515625, 326.2594909667969], [-0.3949889540672302, -43.737998962402344, 324.50811767578125], [1.0360386371612549, -44.29584503173828, 329.23480224609375], [1.794701099395752, -47.37247085571289, 327.18402099609375], [2.4282193183898926, -49.27631378173828, 326.35888671875], [3.095630407333374, -50.87310791015625, 325.6286926269531], [1.8775584697723389, -45.17683410644531, 330.75909423828125], [3.0296430587768555, -48.540794372558594, 328.830810546875], [4.360949993133545, -50.52870178222656, 327.6854553222656], [5.470311641693115, -52.16162872314453, 326.7551574707031], [2.8303887844085693, -45.574363708496094, 332.34515380859375], [4.117491722106934, -48.58415603637695, 330.589111328125], [5.522796154022217, -50.38448715209961, 329.4515075683594], [6.774843692779541, -51.6481819152832, 328.4239196777344], [3.768697500228882, -45.72537612915039, 333.8792419433594], [4.950739860534668, -48.10667037963867, 332.6934814453125], [6.098034858703613, -49.30638885498047, 331.6702575683594], [7.019787788391113, -50.42774200439453, 330.9171142578125]])
camera_hand_right_3dkpts = camera_hand_right_3dkpts.transpose()
print(camera_hand_right_3dkpts.shape)
hand_edges = np.array([[0, 1], [1, 2], [2, 3], [3, 4],[0, 5], [5, 6], [6, 7], [7, 8],[0, 9], [9, 10], [10, 11], [11, 12],[0, 13], [13, 14], [14, 15], [15, 16],[0, 17], [17, 18], [18, 19], [19, 20]])
ax = plt.axes(projection='3d')
for i, edge in enumerate(hand_edges):ax.plot(camera_hand_right_3dkpts[0, edge], camera_hand_right_3dkpts[1, edge], camera_hand_right_3dkpts[2, edge])
# ax.set_xlabel('x')
# ax.set_ylabel('y')
# ax.set_zlabel('z')
# plt.xlim(-30, -42)
# plt.ylim(-150, -154)
# ax.set_zlim(70, 95)
# axis_limit = 700
x_c = np.mean(camera_hand_right_3dkpts[0, :])
y_c = np.mean(camera_hand_right_3dkpts[1, :])
z_c = np.mean(camera_hand_right_3dkpts[2, :])
# axis_limit = 50
#
# ax.set_xlim3d([x_c - axis_limit / 2, x_c + axis_limit / 2])
# ax.set_ylim3d([y_c - axis_limit / 2, y_c + axis_limit / 2])
# ax.set_zlim3d([3 * z_c / 4, z_c])
ax.set_aspect('auto')
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])
ax.set_xticklabels(['x'])
ax.set_yticklabels(['y'])
ax.set_zticklabels(['z'])
x_3d = camera_hand_right_3dkpts[0, :].transpose()
y_3d = camera_hand_right_3dkpts[1, :].transpose()
z_3d = camera_hand_right_3dkpts[2, :].transpose()ax.scatter(x_3d,y_3d,z_3d,marker='o',color=(0, 0, 1),  # rgb
)
for i, _ in enumerate(hand_edges):ax.text(x_3d[i], y_3d[i], z_3d[i], i)
plt.show()

14-3.变换视角

plt坐标系如下左图,而我们一般3d坐标是如下右图有时候为了与2d图片对上,将x,y变换到x,z方便查看,乘以一个矩阵变换一下.

            vis_R = np.array([[1, 0, 0],[0, 0, -1],[0, 1, 0]])keypoints_3d[:, :3] = keypoints_3d[:, :3] @ vis_R

同时为了,将视角变化一下,在限定一下范围

        axis_azimuth = -90axis_elev = 0ax.view_init(elev=axis_elev,azim=axis_azimuth,)h = 2d_img_hw = 2d_img_wx_c = np.mean(x_3d)y_c = np.mean(y_3d)z_c = np.mean(z_3d)ax.set_xlim3d([x_c - w / 2, x_c + w / 2])# ax.set_ylim3d([y_c - h / 2, y_c + h / 2])ax.set_zlim3d([z_c - h / 2, z_c + h / 2])

不同视角的手,其中负号代码逆时针转

z0y0视角:                   z0y45视角:

  

z45y0视角:                   z45y45视角: 

 

 z-90y0视角:

 

  15.plt.text在点处写文字

import matplotlib.pyplot as plt
import numpy as npprecision = np.array([1.        , 1.        , 1.        , 1.        , 1.        ,1.        , 1.        , 1.        , 1.        , 1.        ,1.        , 1.        , 0.99883178, 0.99833749, 0.99833749,0.99833749, 0.99833749, 0.99833749, 0.99785484, 0.99785484,0.99785484, 0.99785484, 0.99785484, 0.99785484, 0.99785484,0.99785484, 0.99785484, 0.99785484, 0.99785484, 0.99785484,0.99785484, 0.99785484, 0.99785484, 0.99785484, 0.99785484,0.99785484, 0.99785484, 0.99785484, 0.99785484, 0.99785484,0.99785484, 0.99776999, 0.99776999, 0.99776999, 0.99776999,0.99776999, 0.99768465, 0.99768465, 0.99768465, 0.99768465,0.99768465, 0.99768465, 0.99768465, 0.99768465, 0.99768465,0.99768465, 0.99768465, 0.99768465, 0.99768465, 0.99768465,0.99768465, 0.99768465, 0.99768465, 0.997593  , 0.997593  ,0.997593  , 0.99744572, 0.99744572, 0.99730402, 0.99730402,0.99694439, 0.99677224, 0.99663965, 0.99650553, 0.99650553,0.99619338, 0.99587397, 0.99571615, 0.99540272, 0.99509893,0.99463807, 0.99403509, 0.99372494, 0.99293591, 0.99118943,0.98993795, 0.98874359, 0.98677335, 0.9854745 , 0.98343158,0.98100471, 0.9796647 , 0.97644179, 0.97417309, 0.97098646,0.96825863, 0.96327888, 0.95922441, 0.94851402, 0.82842664,0.        ])recall = np.linspace(.0, 1.00, int(np.round((1.00 - .0) / .01)) + 1,endpoint=True)
PrecisIndmaxscore = [86, 0.7205873131752014]
APmaxscore = 0.13149480521678925
iouThr = 0.5ap = sum(precision) / len(precision)
x1 = recall[np.nonzero(precision)[0][-1]]
y1 = precision[np.nonzero(precision)[0][-1]]plt.figure()
plt.text(x1, y1, 'ApScore: ' + str(APmaxscore)[:5], fontsize=8)
if PrecisIndmaxscore[0] != -1:x2 = recall[PrecisIndmaxscore[0]]y2 = precision[PrecisIndmaxscore[0]]plt.text(x2, y2, 'PScore: ' + str(PrecisIndmaxscore[-1])[:5], fontsize=8)plt.title('IOU={}'.format(str(iouThr)[:4]))
plt.xlabel("Recall")
plt.ylabel("Precision")
plt.plot(recall, precision, label='AP: ' + str(ap)[:5])#marker='o')
plt.legend()
# plt.savefig(os.path.join(savepath, "iou_{:2}.jpg".format(str(iouThrs[i])[:4])))
plt.show()

15.plt.sublpot

画多个图在一个图上

import matplotlib.pyplot as plt
import numpy as np
import seaborn as snslengths = np.random.randint(0, 10, 1000)
plt.figure(figsize=(12.8, 9.6)) #1280*960
plt.subplot(2, 2, 1, frameon=False) # 两行两列,位置是1的子图
plt.title('One')
plt.xlabel('x1')
plt.ylabel('y1')
sns.set_palette("hls")  # 设置所有图的颜色,使用hls色彩空间
sns.distplot(lengths, kde_kws={'label': "label"}, color="r", bins=30, kde=True)plt.subplot(2, 2, 2, frameon=False)# 两行两列,位置是1的子图
plt.title('Two')
plt.xlabel('x1')
plt.ylabel('y1')
sns.set_palette("hls")  # 设置所有图的颜色,使用hls色彩空间
sns.distplot(lengths, kde_kws={'label': "label"}, color="r", bins=30, kde=True)plt.show()

16.误差折线图

import numpy as np
import matplotlib.pyplot as pltfig = plt.figure()
x = np.arange(10)
y = 2.5 * np.sin(x / 20 * np.pi)
yerr = np.linspace(0.05, 0.2, 20).reshape(2, 10)
# print(y)
# print(yerr)
plt.errorbar(x, y + 3, yerr=yerr, label='both limits (default)')plt.errorbar(x, y + 2, yerr=yerr, uplims=True, label='uplims=True')plt.errorbar(x, y + 1, yerr=yerr, uplims=True, lolims=True,label='uplims=True, lolims=True')upperlimits = [True, False] * 5
lowerlimits = [False, True] * 5
plt.errorbar(x, y, yerr=yerr, uplims=upperlimits, lolims=lowerlimits,label='subsets of uplims and lolims')plt.legend(loc='lower right')
plt.show()

 

参考:

Python--matplotlib绘图可视化知识点整理 - 止战 - 博客园

Intel Image Classification (CNN - Keras) | Kaggle

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/493433.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

无人驾驶汽车想要“普渡众生”,还要经历15个磨难

来源:Forbes 、网易智能摘要:无人驾驶汽车的未来与电动平衡车的历史有什么关系吗?电动平衡车也曾被预言将彻底改变交通。史蒂夫•乔布斯曾经说,城市将围绕这一设备重新设计;约翰•杜尔说,它将比互联网更大…

SQL的各种使用方法

一、Select语句例子 使用子查询查询employees表中,属于某一部门员工的姓名、职位、工薪、部门编号的信息 提示: 1)、需要关联employees表、departments表 2)、已知的信息为部门名称,部门名称由用户自己给出 按照要求写出SQL语句。 答案及…

正常矩形计算IOU与与NMS,多边形计算IOU

一.计算IOU def intersect(box_a, box_b):max_xy np.minimum(box_a[:, 2:], box_b[2:])min_xy np.maximum(box_a[:, :2], box_b[:2])inter np.clip((max_xy - min_xy), a_min0, a_maxnp.inf)return inter[:, 0] * inter[:, 1]def jaccard_numpy(box_a, box_b):&…

产业互联网受瞩目:互联网主战场从To C转向To B | 企鹅经济学

来源:科技日报摘要:最近,要论在互联网圈最火的词,非“产业互联网”莫属。如今,言必提产业互联网,已成为互联网圈的一种风潮。互联网的“上半场”已接近尾声,“下半场”的序幕正被拉开&#xff0…

json的用法

json格式 JSON格式:http://www.json.org/ python和JSON的关系请参考:http://docs.python.org/library/json.html JSON建构有两种结构: 1. “名称/值”对的集合(A collection of name/value pairs)。不同的语言中&#…

数据库设计方法

一、延续训练题 假设你是一个小的录影带出租店的老板。你的出租店里面有3000部电影。每部电影都有DVD或VHS录像带号码。对于每部电影,需要知道它的标题和类别(如,喜剧,悬疑,剧情,动作,战争&…

谷歌首席科学家:搞研究的痛苦,搞工程的人不懂

来源:量子位作者:Vincent Vanhoucke谷歌首席科学家、谷歌大脑技术负责人Vincent Vanhoucke(万努克)最近发出的一篇“劝退文”,引发海外科研学者的热议。在这博客中,万努克直言以研究为业,固然令…

L1/L2/smooth_l1_loss/center_loss+Dice Loss+focal loss+各种IOU loss+kl散度

一.L1/L2/smooth_l1_loss/center_loss公式与代码 1.公式 L2公式: smooth_L1公式: 2.三种函数numpy代码实现 import numpy as np import matplotlib.pyplot as plt#y |x| def L1():x np.arange(-2, 2, 0.01)y abs(x)plt.figure()plt.plot(x, y, …

虚拟机中Linux安装Tools

1. 插入光盘后将文件拷贝到常用放置软件的目录 2. 解压文件 3. 然后进入解压后的文件夹里找到安装文件进行安装(注意使用root权限安装) 4. 安装时也是一个交互的过程 5. 完成安装 转载于:https://www.cnblogs.com/ywj2013/p/3578931.html

世界创新竞争力发展报告:中美日创新产出竞争力居前三

来源:皮书说11月21日,由福建师范大学、中国科学技术交流中心联合攻关,具体由全国经济综合竞争力研究中心福建师范大学分中心组织研究的《世界创新竞争力黄皮书:世界创新竞争力发展报告(2011~2017&#xff0…

二分法查找+树

一,查找存在的一个数,该数在列表中唯一 二分法查找是针对有序数据的查找方法,时间复杂度是O(logn)。。 其中 n/2^k1 时,k 的值就是总共缩小的次数。而每一次缩小操作只涉及两个数据的大小比较,所以, 经过了…

Oracle 软件的安装

1、在oracle主页上注册登录 2、下载64位,将我接受许可协议,下载1of2和2of2,并解压到同一个文件夹 3、安装oracle软件 双击database文件夹里面的setup.exe,启动OUI去掉:我希望通过....只安装软件,不创建数据库选择语言…

算法笔试题

一,搜索连通域 M, N list(map(int, input().split(,))) print(M,N) book [] for i in range(M):line list(map(int, input().split(,)))book.append(line) print(book) # MN3 # book[[1, 0, 0], [0, 1, 0], [0, 1, 1]] print(book,book) class Solution:def __i…

Linux之vim编辑器

目录 vim编辑器 vim编辑器指令 命令模式指令 光标相关 移动光标相关 文本操作 底行模式指令 插入模式 vim配置 面试官:小伙子,你是用什么环境编写代码的? 小明:vs2019 面试官:小伙子,你是用什么环…

Verilog HDL设计实现m序列+选择器

设计m序列发生器,其特征方程为,输出数字序列信号m_sequence码速率为10Mbps;设计串行转并行电路,每4位m序列并行输出,先输入的串行数据位于并行输出数据的高位。设计测试程序,进行功能仿真,将Ver…

深度分享:世界顶级神经科学家王小勤教授CCL 2018主旨报告(PPT全文,经报告人同意发布)...

报告人:王小勤 清华大学脑与智能实验室主任来源:TsinghuaNLP公众号人类的语言处理系统起始于听觉系统,大脑通过听觉系统来感知自然界多姿多彩的声学环境。在我们日常听见的众多声音中,语音和音乐是我们人类相互交流最为重要的两类…

贪心算法+回溯算法+动态规划

一.贪心算法 1.分饼干问题 #思路:排序加贪心 先让胃口小的孩子满足 class Solution:def findContentChildren(self, g, s):print(g:, g)print(s:, s)g sorted(g)#孩子s sorted(s)#饼干res 0for j in range(len(s)):#遍历饼干 先给胃口小的分配if res<len(g):if g[res]&…

小谈@override

override是jdk1.5增加的注解&#xff0c;主要是用来声明子类的某方法覆盖了父类的某方法。非常简单的注解&#xff0c;但是有个小问题&#xff1a; 项目最开始使用的是jdk1.6&#xff0c;mvc模式&#xff1a;接口 ----> 实现类。后来项目改成了jdk1.5&#xff0c;结果所有实…

单片机期末复习代码

1、左右来回循环的流水灯的电路连接见图4-6&#xff0c;显示规律如图4-7。实现本任务要求&#xff0c;可以有多种软件实现方法。下面列出了3种&#xff0c;具体如下 数组的字节操作实现 #include <reg51.h> #define uchar unsigned char uch…

中国AI专利数稳居第一!世界各国AI专利深度盘点

来源&#xff1a;智东西摘要&#xff1a;深入分析AI技术在世界范围内的专利申请数据&#xff0c;从专利申请的角度发现AI领域发展活跃的技术。最近两年&#xff0c;随着人工智能技术在国内的蓬勃发展&#xff0c;一些研究机构对国内外的技术现状进行了不同角度的分析&#xff0…