本文整理汇总了Python中matplotlib.pyplot.clf方法的典型用法代码示例。如果您正苦于以下问题:Python pyplot.clf方法的具体用法?Python pyplot.clf怎么用?Python pyplot.clf使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类matplotlib.pyplot
的用法示例。
在下文中一共展示了pyplot.clf方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: classify
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import clf [as 别名]
def classify(self, features, show=False):
recs, _ = features.shape
result_shape = (features.shape[0], len(self.root))
scores = np.zeros(result_shape)
print scores.shape
R = Record(np.arange(recs, dtype=int), features)
for i, T in enumerate(self.root):
for idxs, result in classify(T, R):
for idx in idxs.indexes():
scores[idx, i] = float(result[0]) / sum(result.values())
if show:
plt.cla()
plt.clf()
plt.close()
plt.imshow(scores, cmap=plt.cm.gray)
plt.title('Scores matrix')
plt.savefig(r"../scratch/tree_scores.png", bbox_inches='tight')
return scores
示例2: plot_precision_recall
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import clf [as 别名]
def plot_precision_recall(train_precision, train_recall, val_precision=None, val_recall=None, resume_epoch = 0, nepochs = -1, save_dir=None, online=False, seq_name = None, object_id = -1):
assert len(range(resume_epoch + 1, nepochs+1)) == len(train_precision)
xaxis = range(resume_epoch + 1, nepochs+1)
plt.plot(xaxis, train_precision, label = "train_precision")
plt.plot(xaxis, train_recall, label = "train_recall")
if not online:
plt.plot(xaxis, val_precision, label = "val_precision")
plt.plot(xaxis, val_recall, label = "val_recall")
plt.legend()
if online:
plt.savefig(os.path.join(save_dir, 'plots', seq_name, str(object_id),'accuracies.png'))
else:
plt.savefig(os.path.join(save_dir, 'plots', 'accuracies.png'))
plt.clf()
示例3: plot_images_grid
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import clf [as 别名]
def plot_images_grid(x: torch.tensor, export_img, title: str = '', nrow=8, padding=2, normalize=False, pad_value=0):
"""Plot 4D Tensor of images of shape (B x C x H x W) as a grid."""
grid = make_grid(x, nrow=nrow, padding=padding, normalize=normalize, pad_value=pad_value)
npgrid = grid.cpu().numpy()
plt.imshow(np.transpose(npgrid, (1, 2, 0)), interpolation='nearest')
ax = plt.gca()
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
if not (title == ''):
plt.title(title)
plt.savefig(export_img, bbox_inches='tight', pad_inches=0.1)
plt.clf()
示例4: plot_wcc_distribution
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import clf [as 别名]
def plot_wcc_distribution(_g, _plot_img):
"""Plot weakly connected components size distributions
:param _g: Transaction graph
:param _plot_img: WCC size distribution image (log-log plot)
:return:
"""
all_wcc = nx.weakly_connected_components(_g)
wcc_sizes = Counter([len(wcc) for wcc in all_wcc])
size_seq = sorted(wcc_sizes.keys())
size_hist = [wcc_sizes[x] for x in size_seq]
plt.figure(figsize=(16, 12))
plt.clf()
plt.loglog(size_seq, size_hist, 'ro-')
plt.title("WCC Size Distribution")
plt.xlabel("Size")
plt.ylabel("Number of WCCs")
plt.savefig(_plot_img)
示例5: drawComplex
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import clf [as 别名]
def drawComplex(data, ph, axes=[-6, 8, -6, 6]):
plt.clf()
plt.axis(axes) # axes = [x1, x2, y1, y2]
plt.scatter(data[:, 0], data[:, 1]) # plotting just for clarity
for i, txt in enumerate(data):
plt.annotate(i, (data[i][0] + 0.05, data[i][1])) # add labels
# add lines for edges
for edge in [e for e in ph.ripsComplex if len(e) == 2]:
# print(edge)
pt1, pt2 = [data[pt] for pt in [n for n in edge]]
# plt.gca().add_line(plt.Line2D(pt1,pt2))
line = plt.Polygon([pt1, pt2], closed=None, fill=None, edgecolor='r')
plt.gca().add_line(line)
# add triangles
for triangle in [t for t in ph.ripsComplex if len(t) == 3]:
pt1, pt2, pt3 = [data[pt] for pt in [n for n in triangle]]
line = plt.Polygon([pt1, pt2, pt3], closed=False,
color="blue", alpha=0.3, fill=True, edgecolor=None)
plt.gca().add_line(line)
plt.show()
示例6: drawComplex
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import clf [as 别名]
def drawComplex(origData, ripsComplex, axes=[-6,8,-6,6]):
plt.clf()
plt.axis(axes)
plt.scatter(origData[:,0],origData[:,1]) #plotting just for clarity
for i, txt in enumerate(origData):
plt.annotate(i, (origData[i][0]+0.05, origData[i][1])) #add labels
#add lines for edges
for edge in [e for e in ripsComplex if len(e)==2]:
#print(edge)
pt1,pt2 = [origData[pt] for pt in [n for n in edge]]
#plt.gca().add_line(plt.Line2D(pt1,pt2))
line = plt.Polygon([pt1,pt2], closed=None, fill=None, edgecolor='r')
plt.gca().add_line(line)
#add triangles
for triangle in [t for t in ripsComplex if len(t)==3]:
pt1,pt2,pt3 = [origData[pt] for pt in [n for n in triangle]]
line = plt.Polygon([pt1,pt2,pt3], closed=False, color="blue",alpha=0.3, fill=True, edgecolor=None)
plt.gca().add_line(line)
plt.show()
示例7: plot_durations
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import clf [as 别名]
def plot_durations(episode_durations):
plt.ion()
plt.figure(2)
plt.clf()
duration_t = torch.FloatTensor(episode_durations)
plt.title('Training')
plt.xlabel('Episodes')
plt.ylabel('Duration')
plt.plot(duration_t.numpy())
if len(duration_t) >= 100:
means = duration_t.unfold(0,100,1).mean(1).view(-1)
means = torch.cat((torch.zeros(99), means))
plt.plot(means.numpy())
plt.pause(0.00001)
示例8: image
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import clf [as 别名]
def image(path: str, costs: Dict[str, int]) -> str:
ys = ['0', '1', '2', '3', '4', '5', '6', '7+', 'X']
xs = [costs.get(k, 0) for k in ys]
sns.set_style('white')
sns.set(font='Concourse C3', font_scale=3)
g = sns.barplot(ys, xs, palette=['#cccccc'] * len(ys))
g.axes.yaxis.set_ticklabels([])
rects = g.patches
sns.set(font='Concourse C3', font_scale=2)
for rect, label in zip(rects, xs):
if label == 0:
continue
height = rect.get_height()
g.text(rect.get_x() + rect.get_width()/2, height + 0.5, label, ha='center', va='bottom')
g.margins(y=0, x=0)
sns.despine(left=True, bottom=True)
g.get_figure().savefig(path, transparent=True, pad_inches=0, bbox_inches='tight')
plt.clf() # Clear all data from matplotlib so it does not persist across requests.
return path
示例9: visualize_transform
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import clf [as 别名]
def visualize_transform(
potential_or_samples, prior_sample, prior_density, transform=None, inverse_transform=None, samples=True, npts=100,
memory=100, device="cpu"
):
"""Produces visualization for the model density and samples from the model."""
plt.clf()
ax = plt.subplot(1, 3, 1, aspect="equal")
if samples:
plt_samples(potential_or_samples, ax, npts=npts)
else:
plt_potential_func(potential_or_samples, ax, npts=npts)
ax = plt.subplot(1, 3, 2, aspect="equal")
if inverse_transform is None:
plt_flow(prior_density, transform, ax, npts=npts, device=device)
else:
plt_flow_density(prior_density, inverse_transform, ax, npts=npts, memory=memory, device=device)
ax = plt.subplot(1, 3, 3, aspect="equal")
if transform is not None:
plt_flow_samples(prior_sample, transform, ax, npts=npts, memory=memory, device=device)
示例10: plot_loss
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import clf [as 别名]
def plot_loss(train_losses, dev_losses, steps, save_path):
"""Save history of training & dev loss as figure.
Args:
train_losses (list): train losses
dev_losses (list): dev losses
steps (list): steps
"""
# Save as csv file
loss_graph = np.column_stack((steps, train_losses, dev_losses))
if os.path.isfile(os.path.join(save_path, "ler.csv")):
os.remove(os.path.join(save_path, "ler.csv"))
np.savetxt(os.path.join(save_path, "loss.csv"), loss_graph, delimiter=",")
# TODO: error check for inf loss
# Plot & save as png file
plt.clf()
plt.plot(steps, train_losses, blue, label="Train")
plt.plot(steps, dev_losses, orange, label="Dev")
plt.xlabel('step', fontsize=12)
plt.ylabel('loss', fontsize=12)
plt.legend(loc="upper right", fontsize=12)
if os.path.isfile(os.path.join(save_path, "loss.png")):
os.remove(os.path.join(save_path, "loss.png"))
plt.savefig(os.path.join(save_path, "loss.png"), dvi=500)
示例11: update_plot
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import clf [as 别名]
def update_plot(self, i):
"""
This is our animation function.
For line graphs, redraw the whole thing.
"""
plt.clf()
(data_points, varieties) = self.data_func()
self.draw_graph(data_points, varieties)
self.show()
示例12: render
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import clf [as 别名]
def render(self):
# create a grid
states = [self.state/self.scale]
indices = np.array([int(self.preprocess(s)) for s in states])
a = np.zeros(self.grid_size)
for i in indices:
a[i] += 1
max_freq = np.max(a)
a/=float(max_freq) # normalize
a = np.reshape(a, (self.scale, self.scale))
ax = sns.heatmap(a)
plt.draw()
plt.pause(0.001)
plt.clf()
示例13: graph_ROC
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import clf [as 别名]
def graph_ROC(max_ACC, TP, FP, name="STD"):
aTP = np.vstack(TP)
n = len(TP)
mean_TP = np.mean(aTP, axis=0)
stderr_TP = np.std(aTP, axis=0) / (n ** 0.5)
var_TP = np.var(aTP, axis=0)
max_TP = mean_TP + 3 * stderr_TP
min_TP = mean_TP - 3 * stderr_TP
# sTP = sum(TP) / len(TP)
sFP = FP[0]
print len(sFP), len(mean_TP), len(TP[0])
smax_ACC = np.mean(max_ACC)
plt.cla()
plt.clf()
plt.close()
plt.plot(sFP, mean_TP)
plt.fill_between(sFP, min_TP, max_TP, color='black', alpha=0.2)
plt.xlim((0,0.1))
plt.ylim((0,1))
plt.title('ROC Curve (accuracy=%.3f)' % smax_ACC)
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.savefig(r"../scratch/"+name+"_ROC_curve.pdf", bbox_inches='tight')
# Write the data to the file
f = file(r"../scratch/"+name+"_ROC_curve.csv", "w")
f.write("FalsePositive,TruePositive,std_err, var, n\n")
for fp, tp, err, var in zip(sFP, mean_TP, stderr_TP, var_TP):
f.write("%s, %s, %s, %s, %s\n" % (fp, tp, err, var, n))
f.close()
示例14: ROC
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import clf [as 别名]
def ROC(scores, labels, names, name="STD"):
max_ACC, TP, FP = ROC_data(scores, labels, names, name)
graph_ROC([max_ACC], [TP], [FP], name)
#P = len(labels[labels==1])
#N = len(labels[labels==0])
## Save raw results in a file:
#fr = file(r"../scratch/"+name+"_results.txt","w")
#for s, l, n in sorted(zip(scores,labels, names), key=lambda x: np.mean(x[0])):
# fr.write("%.4f\t%s\t%s\n" % (np.mean(s), int(l), n))
#fr.close()
## Make an ROC curve
# acc_max = "%.2f" % max(ACC)
#plt.cla()
#plt.clf()
#plt.close()
#plt.plot(FP, TP)
#plt.xlim((0,0.1))
#plt.ylim((0,1))
#plt.title('ROC Curve (accuracy=%.2f)' % max_ACC)
#plt.xlabel('False Positive Rate')
#plt.ylabel('True Positive Rate')
#plt.savefig(r"../scratch/"+name+"_ROC_curve.png", bbox_inches='tight')
#f = file(r"../scratch/"+name+"_ROC_curve.csv", "w")
#f.write("FalsePositive,TruePositive,Accuracy\n")
#for fp, tp, acc in zip(FP,TP, ACC):
# f.write("%s,%s,%s\n" % (fp, tp, acc))
#f.close()
## Read the csv files
示例15: visualizedistances
# 需要导入模块: from matplotlib import pyplot [as 别名]
# 或者: from matplotlib.pyplot import clf [as 别名]
def visualizedistances(data, figname=None):
D, L, N = data
sorted_indexes = np.argsort(L[:,0])
D2 = D[sorted_indexes, :]
D2 = D2[:, sorted_indexes]
plt.cla()
plt.clf()
plt.close()
plt.imshow(D2, cmap=plt.cm.gray)
plt.title('Distance matrix')
plt.savefig(figname, bbox_inches='tight')