def Occlusion_exp(image,occluding_size,occluding_stride,model,preprocess,classes,groundTruth):
img = np.copy(image)
height, width,_= img.shape
output_height = int(math.ceil((height-occluding_size)/occluding_stride+1))
output_width = int(math.ceil((width-occluding_size)/occluding_stride+1))
ocludedImages=[]
for h in range(output_height):
for w in range(output_width):
#occluder region
h_start = h*occluding_stride
w_start = w*occluding_stride
h_end = min(height, h_start + occluding_size)
w_end = min(width, w_start + occluding_size)
input_image = copy.copy(img)
input_image[h_start:h_end,w_start:w_end,:] = 0
ocludedImages.append(preprocess(Image.fromarray(input_image)))
L = np.empty(output_height*output_width)
L.fill(groundTruth)
L = torch.from_numpy(L)
tensor_images = torch.stack([img for img in ocludedImages])
dataset = torch.utils.data.TensorDataset(tensor_images,L)
dataloader = torch.utils.data.DataLoader(dataset,batch_size=5,shuffle=False, num_workers=8)
heatmap=np.empty(0)
model.eval()
for data in dataloader:
images, labels = data
if use_gpu:
images, labels = (images.cuda()), (labels.cuda(async=True))
outputs = model(Variable(images))
m = nn.Softmax()
outputs=m(outputs)
if use_gpu:
outs=outputs.cpu()
heatmap = np.concatenate((heatmap,outs[0:outs.size()[0],groundTruth].data.numpy()))
return heatmap.reshape((output_height, output_width))
python类heatmap()的实例源码
def __init__(self, parent, mlca, width=6, height=6, dpi=100):
figure = Figure(figsize=(width, height), dpi=dpi, tight_layout=True)
axes = figure.add_subplot(111)
super(LCAResultsPlot, self).__init__(figure)
self.setParent(parent)
activity_names = [format_activity_label(next(iter(f.keys()))) for f in mlca.func_units]
# From https://stanford.edu/~mwaskom/software/seaborn/tutorial/color_palettes.html
cmap = sns.cubehelix_palette(8, start=.5, rot=-.75, as_cmap=True)
hm = sns.heatmap(
# mlca.results / np.average(mlca.results, axis=0), # Normalize to get relative results
mlca.results,
annot=True,
linewidths=.05,
cmap=cmap,
xticklabels=["\n".join(x) for x in mlca.methods],
yticklabels=activity_names,
ax=axes,
square=False,
)
hm.tick_params(labelsize=8)
self.setMinimumSize(self.size())
# sns.set_context("notebook")
def plot_correlation_fig(data):
"""
Creates a correlation heat map for all columns in user data.
Parameters
----------
data: Pandas DataFrame
User data file as a Pandas DataFrame
Returns
-------
Matplotlib Figure object.
"""
sns.set(context='talk', style='white')
fig = plt.figure()
sns.heatmap(data.corr(), vmin=-1, vmax=1)
plt.tight_layout()
return fig
def plot_heatmaps(data, mis, column_label, cont, topk=30, prefix=''):
cmap = sns.cubehelix_palette(as_cmap=True, light=.9)
m, nv = mis.shape
for j in range(m):
inds = np.argsort(- mis[j, :])[:topk]
if len(inds) >= 2:
plt.clf()
order = np.argsort(cont[:,j])
subdata = data[:, inds][order].T
subdata -= np.nanmean(subdata, axis=1, keepdims=True)
subdata /= np.nanstd(subdata, axis=1, keepdims=True)
columns = [column_label[i] for i in inds]
sns.heatmap(subdata, vmin=-3, vmax=3, cmap=cmap, yticklabels=columns, xticklabels=False, mask=np.isnan(subdata))
filename = '{}/heatmaps/group_num={}.png'.format(prefix, j)
if not os.path.exists(os.path.dirname(filename)):
os.makedirs(os.path.dirname(filename))
plt.title("Latent factor {}".format(j))
plt.yticks(rotation=0)
plt.savefig(filename, bbox_inches='tight')
plt.close('all')
#plot_rels(data[:, inds], map(lambda q: column_label[q], inds), colors=cont[:, j],
# outfile=prefix + '/relationships/group_num=' + str(j), latent=labels[:, j], alpha=0.1)
def correlation(self, vec_col, method="pearson"):
"""
Compute the correlation matrix for the input dataset of Vectors using the specified method. Method
mapped from pyspark.ml.stat.Correlation.
:param vec_col: The name of the column of vectors for which the correlation coefficient needs to be computed.
This must be a column of the dataset, and it must contain Vector objects.
:param method: String specifying the method to use for computing correlation. Supported: pearson (default),
spearman.
:return: Heatmap plot of the corr matrix using seaborn.
"""
assert isinstance(method, str), "Error, method argument provided must be a string."
assert method == 'pearson' or (
method == 'spearman'), "Error, method only can be 'pearson' or 'sepearman'."
cor = Correlation.corr(self._df, vec_col, method).head()[0].toArray()
return sns.heatmap(cor, mask=np.zeros_like(cor, dtype=np.bool), cmap=sns.diverging_palette(220, 10,
as_cmap=True))
def qindex_heatmap(broker):
try:
info = {"broker": broker, "symbol": "AI50", "period": "1440", \
"system": "AI50", "direction": "longs"}
filename = join(settings.DATA_PATH, 'portfolios', '{}_qndx'.format(broker))
image_filename = filename_constructor(info=info, folder="heatmap")
data = await df_multi_reader(filename=filename)
info["direction"] = 1
returns = await convert_to_perc(data=data.last('108M').LONG_PL, info=info)
if not returns is None:
returns.columns = ['LONG_PL']
if (not isfile(image_filename)) | (datetime.fromtimestamp(getmtime(image_filename)) < \
(datetime.now() - timedelta(days=30))):
await save_qindex_heatmap(data=returns, image_filename=image_filename)
await make_yearly_returns(returns=returns, info=info)
except Exception as err:
print(colored.red("At qindex_heatmap {}".format(err)))
def cor_df(data, cols=None, xticklabels=False, yticklabels=False, close=True):
'''
??: ???????????
???:
data: ?????dataframe??
cols: ?????list??????data????
close: ????????
???:
cormat: ??????dataframe??
heatmap: ????fig??
'''
if cols is None:
cols=list(data.columns)
corrmat = data[cols].corr()
fig = plt.figure()
ax = fig.add_subplot(111)
sns.set(context='paper', font='monospace')
sns.heatmap(corrmat, vmax=0.8, square=True, ax=ax, xticklabels=xticklabels, yticklabels=yticklabels)
ax.set_title('Heatmap of Correlation Matrix')
if close:
plt.close('all')
return corrmat, fig
#Distribution
def heatmap(data,ax,xlabel=None,ylabel=None,xticklabels=None,yticklabels=None,title=None,fontsize=12):
'''
??matplotlib.pyplot.pcolor?????
?????(pc,ax)???pc????matplotlib.pyplot.colorbar??????mappable?
'''
pc=ax.pcolor(data,cmap=plt.cm.Blues)
if xlabel is not None:
ax.set_xlabel(xlabel,fontsize=fontsize)
if ylabel is not None:
ax.set_ylabel(ylabel,fontsize=fontsize)
ax.set_xticks(np.arange(data.shape[1])+0.5,minor=False)
if xticklabels is not None:
ax.set_xticklabels(xticklabels,minor=False,fontsize=fontsize)
ax.set_yticks(np.arange(data.shape[0])+0.5,minor=False)
if yticklabels is not None:
ax.set_yticklabels(yticklabels,minor=False,fontsize=fontsize)
if title is not None:
ax.set_title(title,fontsize=fontsize)
return pc,ax
#????X?Y????
def plotKLdivergenceHeatmap(KL_all, name = None):
print("Plotting KL-divergence heatmap (activity of latent units).")
figure_name = "KL_divergence_heatmap"
if name:
figure_name = name + "/" + figure_name
figure = pyplot.figure()
axis = figure.add_subplot(1, 1, 1)
KL_array = array(KL_all)
print("Dimensions of KL-activations:")
print(KL_array.shape)
seaborn.heatmap(log(KL_array.T), xticklabels = True, yticklabels = False,
cbar = True, center = None, square = True, ax = axis)
axis.set_xlabel("Epoch")
axis.set_ylabel("$log KL(p_i||q_i)$")
data.saveFigure(figure, figure_name, no_spine = False)
def plot_heatmap(
D, xordering=None, yordering=None, xticklabels=None,
yticklabels=None, vmin=None, vmax=None, ax=None):
import seaborn as sns
D = np.copy(D)
if ax is None:
_, ax = plt.subplots()
if xticklabels is None:
xticklabels = np.arange(D.shape[0])
if yticklabels is None:
yticklabels = np.arange(D.shape[1])
if xordering is not None:
xticklabels = xticklabels[xordering]
D = D[:,xordering]
if yordering is not None:
yticklabels = yticklabels[yordering]
D = D[yordering,:]
sns.heatmap(
D, yticklabels=yticklabels, xticklabels=xticklabels,
linewidths=0.2, cmap='BuGn', ax=ax, vmin=vmin, vmax=vmax)
ax.set_xticklabels(xticklabels, rotation=90)
ax.set_yticklabels(yticklabels, rotation=0)
return ax
def correlation(data,title=''):
corr = data.corr(method='spearman')
mask = np.zeros_like(corr)
mask[np.triu_indices_from(mask)] = True
sns.set(style="white")
sns.set_context("notebook", font_scale=2, rc={"lines.linewidth": 0.3})
rcParams['figure.figsize'] = 25, 12
rcParams['font.family'] = 'Verdana'
rcParams['figure.dpi'] = 300
g = sns.heatmap(corr, mask=mask, linewidths=1, cmap="RdYlGn", annot=False)
g.set_xticklabels(data,rotation=25,ha="right");
plt.tick_params(axis='both', which='major', pad=15);
def visualize_housing_data(df):
sns.set(style='whitegrid', context='notebook')
cols = ['LSTAT', 'INDUS', 'NOX', 'RM', 'MEDV']
sns.pairplot(df[cols], size=2.5)
plt.show()
correlation_matrix = np.corrcoef(df[cols].values.T)
sns.set(font_scale=1.5)
heatmap = sns.heatmap(
correlation_matrix,
cbar=True,
annot=True,
square=True,
fmt='.2f',
annot_kws={'size': 15},
yticklabels=cols,
xticklabels=cols,
)
plt.show()
def sns_triangle(matrix, plt_title, only_class=None):
sns.set(style="white")
# Generate a mask for the upper triangle
mask = np.zeros_like(matrix, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
# Set up the matplotlib figure
f, ax = subplots(figsize=(11, 9))
# Generate a custom diverging colormap
cmap = sns.diverging_palette(220, 10, as_cmap=True)
# Draw the heatmap with the mask and correct aspect ratio
sns.heatmap(matrix.as_matrix(), mask=mask, cmap=cmap, vmax=.3,
square=True, xticklabels=5, yticklabels=5,
linewidths=.5, cbar_kws={"shrink": .5}, ax=ax)
title(plt_title)
xlabel('Preprocessed Features')
ylabel('Preprocessed Features')
if only_class is None:
only_class = ''
savefig('images/triangle'+only_class+'.png')
def plotSleepValueHeatmap(intradayStats, sleepValue=1):
sns.set_context("poster")
sns.set_style("darkgrid")
xTicksDiv = 20
#stepSize = int(len(xticks)/xTicksDiv)
stepSize = 60
xticks = [x for x in intradayStats.columns.values]
keptticks = xticks[::stepSize]
xticks = ['' for _ in xticks]
xticks[::stepSize] = keptticks
plt.figure(figsize=(16, 4.2))
g = sns.heatmap(intradayStats.loc[sleepValue].reshape(1,-1))
g.set_xticklabels(xticks, rotation=45)
g.set_yticklabels([])
g.set_ylabel(sleepStats.SLEEP_VALUES[sleepValue])
plt.tight_layout()
sns.plt.show()
def get_confusion(y_test, y_pred):
cm = confusion_matrix(y_test, y_pred)
cm_normalized = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
label_unique = y_test.unique()
# #Graph Confusion Matrix
tick_marks = np.arange(len(label_unique))
# plt.figure(figsize=(8,6))
sns.heatmap(cm_normalized, cmap='Greens',annot=True,linewidths=.5)
# plt.title('confusion matrix')
plt.xlabel('Predicted label')
plt.ylabel('True label')
plt.xticks(tick_marks + 0.5, list(label_unique))
plt.yticks(tick_marks + 0.5,list(reversed(list(label_unique))) , rotation=0)
#
# plt.imshow(cm_normalized, interpolation='nearest', cmap='Greens')
# plt.title('confusion matrix')
# plt.colorbar()
# tick_marks = np.arange(len(label_unique))
# plt.xticks(tick_marks + 0.5, list(reversed(list(label_unique))))
# plt.yticks(tick_marks + 0.5,list(label_unique) , rotation=0)
# plt.tight_layout()
# plt.ylabel('True label')
# plt.xlabel('Predicted label')
def plot_corr_heatmap(corr, labels, heading):
sns.set(style="white")
# Generate a mask for the upper triangle
mask = np.zeros_like(corr, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(8, 8))
# Generate a custom diverging colormap
cmap = sns.diverging_palette(220, 10, as_cmap=True)
# Draw the heatmap with the mask and correct aspect ratio
sns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3,
square=True, xticklabels=labels, yticklabels=labels,
linewidths=.5, ax=ax, cbar_kws={"shrink": .5}, annot=True)
ax.set_title(heading)
plt.show()
def corr_heatmap(df,cols=None,name=None):
sns.set()
if cols is None:
cols = [i for i in df.columns.values if df[i].dtype!='object']
df = df[cols].corr()
print(df.shape)
ds = sns.heatmap(df, annot=False)
plt.show()
if name is not None:
ds.get_figure().savefig(name)
def plotHeatMap(df, psize=(8,8), filename='Heatmap'):
ax = sns.heatmap(df, vmax=.85, square=True, cbar=False, annot=True)
plt.xticks(rotation=40), plt.yticks(rotation=360)
fig = ax.get_figure()
fig.set_size_inches(psize)
fig.savefig(filename)
plt.clf()
def plot_confusion_matrix(fname, conf_mat, target_names,
title='', cmap='Blues', perc=True,figsize=[6,5],cbar=True):
"""Plot Confusion Matrix."""
figsize = deepcopy(figsize)
if cbar == False:
figsize[0] = figsize[0] - 0.6
c_names = []
r_names = []
if len(target_names) != len(conf_mat):
target_names = [str(i) for i in np.arange(len(conf_mat))]
for i, label in enumerate(target_names):
c_names.append(label + '\n(' + str(int(np.sum(conf_mat[:,i]))) + ')')
align = len(str(int(np.sum(conf_mat[i,:])))) + 3 - len(label)
r_names.append('{:{align}}'.format(label, align=align) + '\n(' + str(int(np.sum(conf_mat[i,:]))) + ')')
cm = conf_mat
cm = 100* cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
df = pd.DataFrame(data=np.sqrt(cm), columns=c_names, index=r_names)
if fname != '':plt.figure(figsize=figsize)
g = sns.heatmap(df, annot = cm if perc else conf_mat , fmt=".1f" if perc else ".0f",
linewidths=.5, vmin=0, vmax=np.sqrt(100), cmap=cmap, cbar=cbar,annot_kws={"size": 13})
g.set_title(title)
if cbar:
cbar = g.collections[0].colorbar
cbar.set_ticks(np.sqrt(np.arange(0,100,20)))
cbar.set_ticklabels(np.arange(0,100,20))
g.set_ylabel('True sleep stage',fontdict={'fontsize' : 12, 'fontweight':'bold'})
g.set_xlabel('Predicted sleep stage',fontdict={'fontsize' : 12, 'fontweight':'bold'})
# plt.tight_layout()
if fname!='':
plt.tight_layout()
g.figure.savefig(os.path.join('plots', fname))
def plot_difference_matrix(fname, confmat1, confmat2, target_names,
title='', cmap='Blues', perc=True,figsize=[5,4],cbar=True,
**kwargs):
"""Plot Confusion Matrix."""
figsize = deepcopy(figsize)
if cbar == False:
figsize[0] = figsize[0] - 0.6
cm1 = confmat1
cm2 = confmat2
cm1 = 100 * cm1.astype('float') / cm1.sum(axis=1)[:, np.newaxis]
cm2 = 100 * cm2.astype('float') / cm2.sum(axis=1)[:, np.newaxis]
cm = cm2 - cm1
cm_eye = np.zeros_like(cm)
cm_eye[np.eye(len(cm_eye), dtype=bool)] = cm.diagonal()
df = pd.DataFrame(data=cm_eye, columns=target_names, index=target_names)
plt.figure(figsize=figsize)
g = sns.heatmap(df, annot=cm, fmt=".1f" ,
linewidths=.5, vmin=-10, vmax=10,
cmap='coolwarm_r',annot_kws={"size": 13},cbar=cbar,**kwargs)#sns.diverging_palette(20, 220, as_cmap=True))
g.set_title(title)
g.set_ylabel('True sleep stage',fontdict={'fontsize' : 12, 'fontweight':'bold'})
g.set_xlabel('Predicted sleep stage',fontdict={'fontsize' : 12, 'fontweight':'bold'})
plt.tight_layout()
g.figure.savefig(os.path.join('plots', fname))
def __init__(self, parent, data, labels, width=6, height=6, dpi=100):
figure = Figure(figsize=(width, height), dpi=dpi, tight_layout=True)
axes = figure.add_subplot(111)
super(CorrelationPlot, self).__init__(figure)
self.setParent(parent)
sns.set(style="darkgrid")
corr = data
# cmap = sns.diverging_palette(220, 10, as_cmap=True)
# corrplot(data, names=labels, annot=True, sig_stars=False,
# diag_names=True, cmap=cmap, ax=axes, cbar=True)
df = pd.DataFrame(data=data, columns=labels)
corr = df.corr()
# Generate a mask for the upper triangle
mask = np.zeros_like(corr, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
# Draw the heatmap with the mask and correct aspect ratio
vmax = np.abs(corr.values[~mask]).max()
# vmax = np.abs(corr).max()
sns.heatmap(corr, mask=mask, cmap=plt.cm.PuOr, vmin=-vmax, vmax=vmax,
square=True, linecolor="lightgray", linewidths=1, ax=axes)
for i in range(len(corr)):
axes.text(i + 0.5, i + 0.5, corr.columns[i],
ha="center", va="center", rotation=0)
for j in range(i + 1, len(corr)):
s = "{:.3f}".format(corr.values[i, j])
axes.text(j + 0.5, i + 0.5, s,
ha="center", va="center")
axes.axis("off")
# If uncommented, fills widget
self.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
self.updateGeometry()
self.setMinimumSize(self.size())
def beta_rarefaction(output_dir: str, table: biom.Table, metric: str,
sampling_depth: int, iterations: int=10,
phylogeny: skbio.TreeNode=None,
correlation_method: str='spearman',
color_scheme: str='BrBG') -> None:
if metric in phylogenetic_metrics():
if phylogeny is None:
raise ValueError("A phylogenetic metric (%s) was requested, "
"but a phylogenetic tree was not provided. "
"Phylogeny must be provided when using a "
"phylogenetic diversity metric." % metric)
beta_func = functools.partial(beta_phylogenetic, phylogeny=phylogeny)
else:
beta_func = beta
distance_matrices = _get_multiple_rarefaction(
beta_func, metric, iterations, table, sampling_depth)
sm_df = skbio.stats.distance.pwmantel(
distance_matrices, method=correlation_method, permutations=0,
strict=True)
sm = sm_df[['statistic']] # Drop all other DF columns
sm = sm.unstack(level=0) # Reshape for seaborn
test_statistics = {'spearman': "Spearman's rho", 'pearson': "Pearson's r"}
ax = sns.heatmap(
sm, cmap=color_scheme, vmin=-1.0, vmax=1.0, center=0.0, annot=False,
square=True, xticklabels=False, yticklabels=False,
cbar_kws={'ticks': [1, 0.5, 0, -0.5, -1],
'label': test_statistics[correlation_method]})
ax.set(xlabel='Iteration', ylabel='Iteration',
title='Mantel correlation between iterations')
ax.get_figure().savefig(os.path.join(output_dir, 'heatmap.svg'))
similarity_mtx_fp = os.path.join(output_dir,
'rarefaction-iteration-correlation.tsv')
sm_df.to_csv(similarity_mtx_fp, sep='\t')
index_fp = os.path.join(TEMPLATES, 'beta_rarefaction_assets', 'index.html')
q2templates.render(index_fp, output_dir)
def plot_heatmap(mpm, cm=plt.cm.viridis, xlabel='Sources', ylabel='Sinks',
title='Mixing Proportions (as Fraction)'):
'''Make a basic mixing proportion histogram.'''
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
sns.heatmap(mpm, vmin=0, vmax=1.0, cmap=cm, annot=True, linewidths=.5,
ax=ax)
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
ax.set_title(title)
return fig, ax
def save_heatmap(df, title, tag):
"""Create and save heatmaps."""
sns.plt.figure()
sns.plt.clf()
filename = title+tag+".pdf"
sns.heatmap(df, cmap="YlGn", annot=True, fmt='1.2f')
sns.plt.title(title)
sns.plt.ylabel(r'Number of samples $n$')
sns.plt.xlabel(r'Number of dimensions $d$')
sns.plt.savefig(filename)
print("\t{} saved".format(filename))
def make_heatmaps(collection, tag, idx, cols):
"""Generate heatmaps from dictionaries."""
# Heatmaps containers
acc = list()
bacc = list()
f1 = list()
prec = list()
rcll = list()
for i, n in enumerate(sorted(collection.keys())):
# Empty Rows of the heatmap
n_acc = list()
n_bacc = list()
n_f1 = list()
n_prec = list()
n_rcll = list()
for j, d in enumerate(sorted(collection[n])): # fill columns
n_acc.append(collection[n][d]['acc'])
n_bacc.append(collection[n][d]['bacc'])
n_f1.append(collection[n][d]['f1'])
n_prec.append(collection[n][d]['prec'])
n_rcll.append(collection[n][d]['rcll'])
# Store filled rows
acc.append(n_acc)
bacc.append(n_bacc)
f1.append(n_f1)
prec.append(n_prec)
rcll.append(n_rcll)
# From lists of lists to numpy arrays
acc = pd.DataFrame(data=np.array(acc), index=idx, columns=cols)
bacc = pd.DataFrame(data=np.array(bacc), index=idx, columns=cols)
f1 = pd.DataFrame(data=np.array(f1), index=idx, columns=cols)
prec = pd.DataFrame(data=np.array(prec), index=idx, columns=cols)
rcll = pd.DataFrame(data=np.array(rcll), index=idx, columns=cols)
# Save heatmaps
save_heatmap(acc, 'Accuracy', tag)
save_heatmap(bacc, 'Balanced Accuracy', tag)
save_heatmap(f1, 'F1', tag)
save_heatmap(prec, 'Precision', tag)
save_heatmap(rcll, 'Recall', tag)
def __init__(self, path, games, logger, suffix):
super(SuccessPosition, self).__init__(path, self.__class__.__name__, suffix)
x_bin = 7
y_bin = 7
success_sum = np.zeros((x_bin+1, y_bin+1))
total_sum = np.zeros((x_bin+1, y_bin+1))
for game in games:
bbox = game.object.bbox
picture = game.image
x = int(bbox.x_center / picture.width * x_bin)
y = int(bbox.y_center / picture.height * y_bin)
total_sum[x][y] += 1.0
if game.status == "success":
success_sum[x][y] += 1.0
ratio = 1.0 * success_sum / total_sum
sns.set(style="whitegrid")
# Draw the heatmap with the mask and correct aspect ratio
f = sns.heatmap(ratio, robust=True, linewidths=.5, cbar_kws={"label" : "% Success"}, xticklabels=False, yticklabels=False)
f.set_xlabel("normalized image width", {'size':'14'})
f.set_ylabel("normalized image height", {'size':'14'})
f.legend(loc="upper left", fontsize='x-large')
def monthly_returns(self, fund, ax=None):
if ax is None:
ax = plt.gca()
# Compute the returns on a month-over-month basis.
history = fund.history
monthly_ret = self.__aggregate_returns(history, 'monthly')
monthly_ret = monthly_ret.unstack()
monthly_ret = np.round(monthly_ret, 3)
monthly_ret.rename(
columns={1: 'Jan', 2: 'Feb', 3: 'Mar', 4: 'Apr',
5: 'May', 6: 'Jun', 7: 'Jul', 8: 'Aug',
9: 'Sep', 10: 'Oct', 11: 'Nov', 12: 'Dec'},
inplace=True
)
# Create a heatmap showing the month-over-month returns of the portfolio
# or the fund.
sns.heatmap(
monthly_ret.fillna(0) * 100.0, annot=True, fmt="0.1f",
annot_kws={"size": 12}, alpha=1.0, center=0.0, cbar=False,
cmap=cm.RdYlGn, ax=ax
)
ax.set_title('Monthly Returns (%)', fontweight='bold')
ax.set_ylabel('')
ax.set_yticklabels(ax.get_yticklabels(), rotation=0)
ax.set_xlabel('')
return ax
def show_heat_map(self):
pd.set_option('precision', 2)
plt.figure(figsize=(20, 6))
sns.heatmap(self.data.corr(), square=True)
plt.xticks(rotation=90)
plt.yticks(rotation=360)
plt.suptitle("Correlation Heatmap")
plt.show()
def plot_deviations(self, feature_column):
""" Plots deviations from expected distributions of features within each
predicted class.
:param feature_column: name of the column on which to plot distributions
:type feature_column: str
:returns: heatmap of deviations
:rtype: matplotlib figure
"""
expected_proportions = self.get_distribution_by_class(
feature_column, self.model['labelling'][0], True)
observed_proportions = self.get_distribution_by_class(
feature_column, 'y_pred', True)
observed_values = self.get_distribution_by_class(
feature_column, 'y_pred', False)
proportion_deviation = ((observed_proportions - expected_proportions) /
expected_proportions)
deviation_plot = sns.heatmap(proportion_deviation, cmap = 'RdBu_r',
vmin = -1, vmax = 1,
annot = observed_values, fmt = 'g')
deviation_plot.set(xlabel = feature_column, ylabel = 'predicted class',
yticklabels = reversed(self.labels))
return(deviation_plot)
def save_qindex_heatmap(data, image_filename):
try:
monthly_ret = await aggregate_returns(returns=data, convert_to='monthly')
monthly_ret = monthly_ret.unstack()
monthly_ret = round(monthly_ret, 3)
monthly_ret.rename(
columns={1: 'Jan', 2: 'Feb', 3: 'Mar', 4: 'Apr',
5: 'May', 6: 'Jun', 7: 'Jul', 8: 'Aug',
9: 'Sep', 10: 'Oct', 11: 'Nov', 12: 'Dec'},
inplace=True
)
ax = plt.gca()
sns.heatmap(
monthly_ret.fillna(0), # * 100.0,
annot=True,
fmt="0.1f",
annot_kws={"size": 8},
alpha=1.0,
center=0.0,
cbar=False,
cmap=cm.RdYlGn,
ax=ax)
ax.set_title('A.I. Returns, %', fontweight='bold')
plt.savefig(image_filename)
plt.close()
if settings.SHOW_DEBUG:
print(colored.green("Wrote heatmap image for {}\n".format(image_filename)))
except Exception as err:
print(colored.red("At save_qindex_heatmap {}".format(err)))