def plot_averages_by_type(df, figname, fignum, use_en_source=True, pointplot=True, layer0=True):
plt.figure(fignum)
if use_en_source:
df_side = df[(df.source == 'en') & (df.target != 'en')]
else:
df_side = df[(df.source != 'en') & (df.target == 'en')]
if not layer0:
df_side = df_side[df_side.layer != '0']
plotfunc = sns.pointplot if pointplot else sns.boxplot
if pointplot:
plotfunc(x='accuracy', y='relation', hue='layer', data=df_side, join=False)
else:
plotfunc(x='accuracy', y='relation', hue='layer', data=df_side)
plt.xlabel('Accuracy')
plt.ylabel('')
plt.tight_layout()
plt.savefig(figname)
return fignum + 1
python类pointplot()的实例源码
def save_mapping_cmp(is_power_point = False):
dfs = []
for filename in glob.glob("../output/cifar10classifier_resnet32_*.csv"):
target = filename.split("_")[-1].split(".csv")[0]
if target in ["momentum", "bnafteraddition", "fullpreactivation", "noactivation", "relubeforeaddition", "reluonlypreactivation"]:
df = pd.read_csv(filename)
df["train_error"] = 1 - df["train_accuracy"]
df["test_error"] = 1 - df["test_accuracy"]
dfs.append(df)
total_df = pd.concat(dfs)
total_df["name"] = total_df["name"].str.split("_").str.get(-1).str.replace("Momentum", "Nesterov(Original Paper)")
ax = sns.pointplot(x="epoch", y="test_error", hue="name", data=total_df, scale=0.2)
if is_power_point:
ax.legend(loc="lower left", markerscale=9.0, fontsize=20)
else:
ax.legend(markerscale=3.0)
ax.set(ylim=(0, 0.2))
ax.set_xticklabels([i if i % 10 == 0 else "" for i in range(200)])
ax.set(xlabel='epoch', ylabel='error(%)')
ax.get_figure().savefig("../figures/resnet.mapping.png")
sns.plt.close()
def save_solvers_cmp(is_power_point = False):
dfs = []
for filename in glob.glob("../output/cifar10classifier_resnet32_*.csv"):
target = filename.split("_")[-1].split(".csv")[0]
if target in ["adadelta", "adagrad", "adam", "momentum", "rmsprop"]:
df = pd.read_csv(filename)
df["train_error"] = 1 - df["train_accuracy"]
df["test_error"] = 1 - df["test_accuracy"]
dfs.append(df)
total_df = pd.concat(dfs)
total_df["name"] = total_df["name"].str.split("_").str.get(-1).str.replace("Momentum", "Nesterov(Original Paper)")
ax = sns.pointplot(x="epoch", y="test_error", hue="name", data=total_df, scale=0.2)
if is_power_point:
ax.legend(loc="lower left", markerscale=9.0, fontsize=20)
else:
ax.legend(loc="lower left", markerscale=3.0)
ax.set(ylim=(0, 0.2))
ax.set_xticklabels([i if i % 10 == 0 else "" for i in range(200)])
ax.set(xlabel='epoch', ylabel='error(%)')
ax.get_figure().savefig("../figures/resnet.solvers.png")
sns.plt.close()
def save_layers_cmp(is_power_point = False):
total_df = None
for layer in [20, 32, 44, 56, 110]:
df = pd.read_csv("../output/cifar10classifier_resnet%d.csv" % layer)
df["train_error"] = 1 - df["train_accuracy"]
df["test_error"] = 1 - df["test_accuracy"]
df = df[df["epoch"] < 150]
if total_df is None:
total_df = df
else:
total_df = pd.concat([total_df, df])
total_df["name"] = total_df["name"].str.split("_").str.get(-1)
ax = sns.pointplot(x="epoch", y="test_error", hue="name", data=total_df, scale=0.2)
if is_power_point:
ax.legend(loc="lower left", markerscale=9.0, fontsize=20)
else:
ax.legend(markerscale=3.0)
ax.set(ylim=(0, 0.2))
ax.set_xticklabels([i if i % 10 == 0 else "" for i in range(150)])
ax.set(xlabel='epoch', ylabel='error(%)')
ax.get_figure().savefig("../figures/resnet.layers.png")
sns.plt.close()
def plotDailyStatsSleep(stats, columns=None):
"""
Plot daily stats. Fill all data range, and put NaN for days without measures
:param data: data to plot
"""
MEASURE_NAME = 'date'
if not columns:
columns = ['sleep_inefficiency', 'sleep_hours']
dataToPlot = _prepareDailyStats(stats, columns)
f, axes = getAxes(2,1)
xTicksDiv = min(10, len(dataToPlot))
#xticks = [(x-pd.DateOffset(years=1, day=2)).date() for x in stats.date]
xticks = [x.date() for x in dataToPlot.date]
keptticks = xticks[::int(len(xticks)/xTicksDiv)]
xticks = ['' for _ in xticks]
xticks[::int(len(xticks)/xTicksDiv)] = keptticks
for i, c in enumerate(columns):
g =sns.pointplot(x=MEASURE_NAME, y=NAMES[c], data=dataToPlot, ax=axes[i])
g.set_xticklabels([])
g.set_xlabel('')
g.set_xticklabels(xticks, rotation=45)
sns.plt.show()
def plot(self):
""" Graphical summary of pointwise pareto-k importance-sampling indices
Pareto-k tail indices are plotted (on the y axis) for each observation unit (on the x axis)
"""
seaborn.pointplot(
y = self.pointwise.pareto_k,
x = self.pointwise.index,
join = False)
#pyplot.axhline(0.5)
def plot_averages_by_distance(df, figname, fignum, use_en_source=True, num_accs=24, pointplot=True, hue='Distance'):
plt.figure(fignum)
if use_en_source:
df_side = df[(df.source == 'en') & (df.target != 'en')]
layers = np.concatenate([[i]*5 for i in range(5)] * num_accs)
else:
df_side = df[(df.source != 'en') & (df.target == 'en')]
layers = list(range(5))*5*num_accs
accs = get_accs_from_df(df_side, col_pref='dist')
flat_accs = np.concatenate(accs)
dists = np.concatenate([[pretty_dist_names_list[i]]*75 for i in range(8)])
df_plot = pd.DataFrame({'Layer' : layers, 'Accuracy' : flat_accs, 'Distance' : dists })
#print(df_plot)
plotfunc = sns.pointplot if pointplot else sns.boxplot
if hue == 'Distance':
plotfunc(x='Layer', y='Accuracy', data=df_plot, hue='Distance')
else:
plotfunc(x='Distance', y='Accuracy', data=df_plot, hue='Layer')
plt.xticks(range(8), pretty_dist_names_list)
plt.tight_layout()
plt.savefig(figname)
return fignum + 1
cyber_attack_classification.py 文件源码
项目:AppsOfDataAnalysis
作者: nhanloukiala
项目源码
文件源码
阅读 20
收藏 0
点赞 0
评论 0
def line_plot(data ,title = "", x_title ="", y_title="", legend_label="",group_labels=None):
plot_data = DataFrame()
plot_data['x'] = data[:, 1].astype(int)
plot_data['y'] = data[:, 0].astype(float)
plot_data[legend_label] = data[:, 2]
sns.set(style="whitegrid")
g = sns.pointplot(x="x", y="y", hue=legend_label, data=plot_data, hue_order=np.unique(plot_data[legend_label]))
plt.title(title, fontsize=25)
plt.ylabel(y_title, fontsize=12)
plt.xlabel(x_title, fontsize=12)
plt.show()
def line_plot(data ,title = "", x_title ="", y_title="", legend_label="",group_labels=None):
plot_data = DataFrame()
plot_data['x'] = data[:, 1].astype(int)
plot_data['y'] = data[:, 0].astype(float)
plot_data[legend_label] = data[:, 2]
sns.set(style="whitegrid")
g = sns.pointplot(x="x", y="y", hue=legend_label, data=plot_data, hue_order=np.unique(plot_data[legend_label]))
plt.title(title, fontsize=14)
plt.ylabel(y_title, fontsize=12)
plt.xlabel(x_title, fontsize=12)
plt.show()
def plot_points(df, axes):
for exp, ax in zip(["dots", "sticks", "rest"], axes):
exp_df = pd.melt(df.query("exp == @exp"),
"subj", ["within", "between"], "test", "corr")
sns.pointplot(x="test", y="corr", hue="test", data=exp_df,
dodge=.5, join=False, ci=95,
palette=[".15", ".5"], ax=ax)
plt.setp(ax.lines, linewidth=2)
sns.pointplot(x="test", y="corr", hue="subj", data=exp_df,
palette=[".75"], scale=.75, ax=ax)
plt.setp(ax.collections[:], facecolor="w", zorder=20)
ax.legend_ = None
ax.set(ylabel="",
xlabel="",
xticks=[-.1, 1.1],
xticklabels=["Same\ncontext", "Different\ncontext"])
axes[0].set(ylim=(0, .105), ylabel="Timeseries correlation (r)")
axes[1].set(ylim=(0, .0525))
axes[2].set(ylim=(0, .0525))
for ax in axes:
sns.despine(ax=ax, trim=True)
def plot_swarms(df, axes, palette):
for exp, ax in zip(["dots", "sticks"], axes):
exp_df = df.query("experiment == @exp")
ax.axhline(.5, .1, .9, dashes=(5, 2), color=".6")
ax.set(ylim=(.4, .9), yticks=[.4, .5, .6, .7, .8, .9])
sns.pointplot(x="roi", y="acc", data=exp_df,
palette=palette, join=False, ci=None, ax=ax)
points_to_lines(ax, lw=3)
sns.swarmplot(x="roi", y="acc", data=exp_df, size=4,
color=".85", # facecolor="none",
linewidth=1, edgecolor=".4", ax=ax)
ax.set(xlabel="", ylabel="", xticklabels=["IFS", "MFC"])
ax_l, ax_r = axes
ax_l.set(ylabel="Decoding accuracy")
ax_r.set(yticks=[])
ax_l.text(.5, .91, "Experiment 1", ha="center", va="center", size=7.5)
ax_r.text(.5, .91, "Experiment 2", ha="center", va="center", size=7.5)
sns.despine(ax=ax_l, trim=True)
sns.despine(ax=ax_r, left=True, trim=True)
def _plotWeekdayByMonthStats(stats, stat_name):
dataToPlot = _prepareWeekdayByMonthStats(stats)
# Plot
g = sns.pointplot(data=dataToPlot, x="day", y=stat_name, hue="month", order=dayOfWeekOrder)
g.set(xlabel='')
g.set_ylabel(NAMES[stat_name])
return g
#sns.plt.show()