def plot_by_training_samples(I_XT_array, I_TY_array, axes, epochsInds, f, index_i, index_j, size_ind, font_size, y_ticks, x_ticks, colorbar_axis, title_str, axis_font, bar_font, save_name, samples_labels):
"""Print the final epoch of all the diffrenet training samples size """
max_index = size_ind if size_ind!=-1 else I_XT_array.shape[2]-1
cmap = plt.get_cmap('gnuplot')
colors = [cmap(i) for i in np.linspace(0, 1, max_index+1)]
#Print the final epoch
nums_epoch= -1
#Go over all the samples size and plot them with the right color
for index_in_range in range(0, max_index):
XT, TY = [], []
for layer_index in range(0, I_XT_array.shape[4]):
XT.append(np.mean(I_XT_array[:, -1, index_in_range, nums_epoch, layer_index], axis=0))
TY.append(np.mean(I_TY_array[:, -1, index_in_range,nums_epoch, layer_index], axis=0))
axes[index_i, index_j].plot(XT, TY, marker='o', linestyle='-', markersize=12, markeredgewidth=0.2, linewidth=0.5,
color=colors[index_in_range])
utils.adjustAxes(axes[index_i, index_j], axis_font=axis_font, title_str=title_str, x_ticks=x_ticks, y_ticks=y_ticks,
x_lim=None, y_lim=None,
set_xlabel=index_i == axes.shape[0] - 1, set_ylabel=index_j == 0, x_label='$I(X;T)$',
y_label='$I(T;Y)$', set_xlim=True,
set_ylim=True, set_ticks=True, label_size=font_size)
#Create color bar and save it
if index_i == axes.shape[0] - 1 and index_j == axes.shape[1] - 1:
utils.create_color_bar(f, cmap, colorbar_axis, bar_font, epochsInds, title='Training Data')
f.savefig(save_name + '.jpg', dpi=150, format='jpg')
python类colors()的实例源码
def update_line_each_neuron(num, print_loss, Ix, axes, Iy, train_data, accuracy_test, epochs_bins, loss_train_data, loss_test_data, colors, epochsInds,
font_size = 18, axis_font = 16, x_lim = [0,12.2], y_lim=[0, 1.08],x_ticks = [], y_ticks = []):
"""Update the figure of the infomration plane for the movie"""
#Print the line between the points
axes[0].clear()
if len(axes)>1:
axes[1].clear()
#Print the points
for layer_num in range(Ix.shape[2]):
for net_ind in range(Ix.shape[0]):
axes[0].scatter(Ix[net_ind,num, layer_num], Iy[net_ind,num, layer_num], color = colors[layer_num], s = 35,edgecolors = 'black',alpha = 0.85)
title_str = 'Information Plane - Epoch number - ' + str(epochsInds[num])
utils.adjustAxes(axes[0], axis_font, title_str, x_ticks, y_ticks, x_lim, y_lim, set_xlabel=True, set_ylabel=True,
x_label='$I(X;T)$', y_label='$I(T;Y)$')
#Print the loss function and the error
if len(axes)>1:
axes[1].plot(epochsInds[:num], 1 - np.mean(accuracy_test[:, :num], axis=0), color='g')
if print_loss:
axes[1].plot(epochsInds[:num], np.mean(loss_test_data[:, :num], axis=0), color='y')
nereast_val = np.searchsorted(epochs_bins, epochsInds[num], side='right')
axes[1].set_xlim([0,epochs_bins[nereast_val]])
axes[1].legend(('Accuracy', 'Loss Function'), loc='best')
def plot_hist(str_name, save_name='dist'):
data_array = utils.get_data(str_name)
params = np.squeeze(np.array(data_array['information']))
ind_array = data_array['params']['epochsInds']
DKL_YgX_YgT = utils.extract_array(params, 'DKL_YgX_YgT')
p_ts = utils.extract_array(params, 'pts')
H_Xgt = utils.extract_array(params, 'H_Xgt')
f, (axes) = plt.subplots(3, 1)
#axes = [axes]
f.subplots_adjust(left=0.14, bottom=0.1, right=.928, top=0.94, wspace=0.13, hspace=0.55)
colors = LAYERS_COLORS
line_ani = animation.FuncAnimation(f, update_bars_num_of_ts, len(p_ts), repeat=False,
interval=1, blit=False, fargs=[p_ts,H_Xgt,DKL_YgX_YgT, axes,ind_array])
Writer = animation.writers['ffmpeg']
writer = Writer(fps=50)
#Save the movie
line_ani.save(save_name+'_movie.mp4',writer=writer,dpi=250)
plt.show()
def plot_RF(rf, sample_shape):
norm = matplotlib.colors.Normalize()
norm.autoscale(rf)
rf = np.resize(rf, np.prod(sample_shape)).reshape(sample_shape)
norm_zero = min(max(norm(0.0), 0.0+1e-6), 1.0-1e-6)
cdict = {
'red' : ((0., 0., 0.), (norm_zero, 0.5, 0.5), (1., 1., 1.)),
'green': ((0., 0., 0.), (norm_zero, 0.5, 0.5), (1., 1., 1.)),
'blue' : ((0., 0., 0.), (norm_zero, 0.5, 0.5), (1., 1., 1.))
}
#generate the colormap with 1024 interpolated values
my_cmap = matplotlib.colors.LinearSegmentedColormap('my_colormap', cdict, 1024)
plt.imshow(rf, interpolation='nearest', origin='upper', cmap=my_cmap)
ax = plt.gca()
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
def get_stock_signal_data():
fname = os.path.join(os.getcwd(), 'data', 'stock_data', '_IF000.csv')
price_data = csv2frame(fname)
from matplotlib.colors import colorConverter
info = load_tradeinfo("_djtrend2_IF000")
entry_x = []
entry_y = info['entry_price'].tolist()
exit_x = []
exit_y = info['exit_price'].tolist()
colors = []
for t in info.index:
entry_x.append(price_data.index.searchsorted(t))
for t in info['exit_datetime'].values:
exit_x.append(price_data.index.searchsorted(t))
for i in range(len(info)):
tr = info.ix[i]
if tr['islong']:
c = 'r' if tr['exit_price']>tr['entry_price'] else 'w'
else:
c = 'r' if tr['exit_price']<tr['entry_price'] else 'w'
r,g,b = colorConverter.to_rgb(c)
colors.append((r,g,b,1))
return price_data, entry_x, entry_y, exit_x, exit_y, colors
def _cmap_discretize(cmap, N):
"""Return a discrete colormap from the continuous colormap cmap.
cmap: colormap instance, eg. cm.jet.
N: number of colors.
Example
x = resize(arange(100), (5,100))
djet = cmap_discretize(cm.jet, 5)
imshow(x, cmap=djet)
"""
if type(cmap) == str:
cmap = plt.get_cmap(cmap)
colors_i = np.concatenate((np.linspace(0, 1., N), (0.,0.,0.,0.)))
colors_rgba = cmap(colors_i)
indices = np.linspace(0, 1., N+1)
cdict = {}
for ki, key in enumerate(('red','green','blue')):
cdict[key] = [(indices[i], colors_rgba[i-1,ki], colors_rgba[i,ki])
for i in range(N+1)]
# Return colormap object.
return mcolors.LinearSegmentedColormap(cmap.name + "_%d"%N, cdict, 1024)
plotting.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 28
收藏 0
点赞 0
评论 0
def _apply_style_colors(self, colors, kwds, col_num, label):
"""
Manage style and color based on column number and its label.
Returns tuple of appropriate style and kwds which "color" may be added.
"""
style = None
if self.style is not None:
if isinstance(self.style, list):
try:
style = self.style[col_num]
except IndexError:
pass
elif isinstance(self.style, dict):
style = self.style.get(label, style)
else:
style = self.style
has_color = 'color' in kwds or self.colormap is not None
nocolor_style = style is None or re.match('[a-z]+', style) is None
if (has_color or self.subplots) and nocolor_style:
kwds['color'] = colors[col_num % len(colors)]
return style, kwds
plotting.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 36
收藏 0
点赞 0
评论 0
def _make_plot(self):
colors = self._get_colors()
stacking_id = self._get_stacking_id()
for i, (label, y) in enumerate(self._iter_data()):
ax = self._get_ax(i)
kwds = self.kwds.copy()
label = com.pprint_thing(label)
kwds['label'] = label
style, kwds = self._apply_style_colors(colors, kwds, i, label)
if style is not None:
kwds['style'] = style
kwds = self._make_plot_keywords(kwds, y)
artists = self._plot(ax, y, column_num=i,
stacking_id=stacking_id, **kwds)
self._add_legend_handle(artists[0], label, index=i)
plotting.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 29
收藏 0
点赞 0
评论 0
def maybe_color_bp(self, bp):
if isinstance(self.color, dict):
boxes = self.color.get('boxes', self._boxes_c)
whiskers = self.color.get('whiskers', self._whiskers_c)
medians = self.color.get('medians', self._medians_c)
caps = self.color.get('caps', self._caps_c)
else:
# Other types are forwarded to matplotlib
# If None, use default colors
boxes = self.color or self._boxes_c
whiskers = self.color or self._whiskers_c
medians = self.color or self._medians_c
caps = self.color or self._caps_c
from matplotlib.artist import setp
setp(bp['boxes'], color=boxes, alpha=1)
setp(bp['whiskers'], color=whiskers, alpha=1)
setp(bp['medians'], color=medians, alpha=1)
setp(bp['caps'], color=caps, alpha=1)
node_profile_analyzer_time_and_veh_legs.py 文件源码
项目:gtfspy
作者: CxAalto
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def _get_fill_and_line_colors(self, min_n, max_n):
colors = self._get_colors_for_boardings(min_n, max_n)
n_boardings_range = range(min_n, max_n + 1)
nboardings_to_color = {n: colors[i] for i, n in enumerate(n_boardings_range)}
n_boardings_to_line_color = {}
n_boardings_to_fill_color = {}
#
rgbs = [color_tuple[:3] for color_tuple in nboardings_to_color.values()]
hsvs = matplotlib.colors.rgb_to_hsv(rgbs)
max_saturation = max([hsv[1] for hsv in hsvs])
line_saturation_multiplier = 1 / max_saturation
for n, color_tuple in nboardings_to_color.items():
c = NodeProfileAnalyzerTimeAndVehLegs._multiply_color_saturation(color_tuple, line_saturation_multiplier)
c = NodeProfileAnalyzerTimeAndVehLegs._multiply_color_brightness(c, 1)
n_boardings_to_line_color[n] = c
c = NodeProfileAnalyzerTimeAndVehLegs._multiply_color_brightness(color_tuple, 1.2)
c = NodeProfileAnalyzerTimeAndVehLegs._multiply_color_saturation(c, 0.8)
n_boardings_to_fill_color[n] = c
return n_boardings_to_fill_color, n_boardings_to_line_color
def __init__(self, vmax=None, clip=False):
"""
If *vmax* is not given, it is initialized from the maximum absolute
value of the first input processed. That is, *__call__(A)* calls
*autoscale_None(A)*.
If *clip* is *True* and the given value falls outside the range,
the returned value will be 0 or 1, whichever is closer.
Works with scalars or arrays, including masked arrays. If
*clip* is *True*, masked values are set to 1; otherwise they
remain masked. Clipping silently defeats the purpose of setting
the over, under, and masked colors in the colormap, so it is
likely to lead to surprises; therefore the default is
*clip* = *False*.
"""
self.vmax = vmax
self.clip = clip
def dismph_colormap():
'''Make a custom colormap like the one used in dismph. The list was
created from dismphN.mat in geodmod which is a 64 segmented colormap
using the following:
from scipy.io import loadmat
cmap = loadmat('dismphN.mat',struct_as_record=True)['dismphN']
from matplotlib.colors import rgb2hex
list=[]
for i in cmap: list.append(rgb2hex(i))
'''
list = ['#f579cd', '#f67fc6', '#f686bf', '#f68cb9', '#f692b3', '#f698ad',
'#f69ea7', '#f6a5a1', '#f6ab9a', '#f6b194', '#f6b78e', '#f6bd88',
'#f6c482', '#f6ca7b', '#f6d075', '#f6d66f', '#f6dc69', '#f6e363',
'#efe765', '#e5eb6b', '#dbf071', '#d0f477', '#c8f67d', '#c2f684',
'#bbf68a', '#b5f690', '#aff696', '#a9f69c', '#a3f6a3', '#9cf6a9',
'#96f6af', '#90f6b5', '#8af6bb', '#84f6c2', '#7df6c8', '#77f6ce',
'#71f6d4', '#6bf6da', '#65f6e0', '#5ef6e7', '#58f0ed', '#52e8f3',
'#4cdbf9', '#7bccf6', '#82c4f6', '#88bdf6', '#8eb7f6', '#94b1f6',
'#9aabf6', '#a1a5f6', '#a79ef6', '#ad98f6', '#b392f6', '#b98cf6',
'#bf86f6', '#c67ff6', '#cc79f6', '#d273f6', '#d86df6', '#de67f6',
'#e561f6', '#e967ec', '#ed6de2', '#f173d7']
dismphCM = matplotlib.colors.LinearSegmentedColormap.from_list('mycm', list)
dismphCM.set_bad('w', 0.0)
return dismphCM
def get_cmap(N):
color_norm = colors.Normalize(vmin=0, vmax=N-1)
scalar_map = cmx.ScalarMappable(norm=color_norm, cmap='hsv')
def map_index_to_rgb_color(index):
return scalar_map.to_rgba(index)
return map_index_to_rgb_color
def plotImage(self, I, ax=None, showIt=False, grid=False, clim=None):
if self.dim == 3: raise Exception('Use plot slice?')
import matplotlib.pyplot as plt
import matplotlib
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.colors as colors
import matplotlib.cm as cmx
if ax is None: ax = plt.subplot(111)
jet = cm = plt.get_cmap('jet')
cNorm = colors.Normalize(
vmin=I.min() if clim is None else clim[0],
vmax=I.max() if clim is None else clim[1])
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)
ax.set_xlim((self.x0[0], self.h[0].sum()))
ax.set_ylim((self.x0[1], self.h[1].sum()))
for ii, node in enumerate(self._sortedCells):
x0, sz = self._cellN(node), self._cellH(node)
ax.add_patch(plt.Rectangle((x0[0], x0[1]), sz[0], sz[1], facecolor=scalarMap.to_rgba(I[ii]), edgecolor='k' if grid else 'none'))
# if text: ax.text(self.center[0],self.center[1],self.num)
scalarMap._A = [] # http://stackoverflow.com/questions/8342549/matplotlib-add-colorbar-to-a-sequence-of-line-plots
ax.set_xlabel('x')
ax.set_ylabel('y')
if showIt: plt.show()
return [scalarMap]
def plotImage(
self, I, ax=None, showIt=False, grid=False, clim=None
):
if self.dim == 3:
raise NotImplementedError('This is not yet done!')
import matplotlib.pyplot as plt
import matplotlib
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.colors as colors
import matplotlib.cm as cmx
if ax is None:
ax = plt.subplot(111)
jet = cm = plt.get_cmap('jet')
cNorm = colors.Normalize(
vmin=I.min() if clim is None else clim[0],
vmax=I.max() if clim is None else clim[1])
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)
# ax.set_xlim((self.x0[0], self.h[0].sum()))
# ax.set_ylim((self.x0[1], self.h[1].sum()))
Nx = self.r(self.gridN[:, 0], 'N', 'N', 'M')
Ny = self.r(self.gridN[:, 1], 'N', 'N', 'M')
cell = self.r(I, 'CC', 'CC', 'M')
for ii in range(self.nCx):
for jj in range(self.nCy):
I = [ii, ii+1, ii+1, ii]
J = [jj, jj, jj+1, jj+1]
ax.add_patch(plt.Polygon(np.c_[Nx[I, J], Ny[I, J]], facecolor=scalarMap.to_rgba(cell[ii, jj]), edgecolor='k' if grid else 'none'))
scalarMap._A = [] # http://stackoverflow.com/questions/8342549/matplotlib-add-colorbar-to-a-sequence-of-line-plots
ax.set_xlabel('x')
ax.set_ylabel('y')
if showIt:
plt.show()
return [scalarMap]
def compute_venn2_colors(set_colors):
'''
Given two base colors, computes combinations of colors corresponding to all regions of the venn diagram.
returns a list of 3 elements, providing colors for regions (10, 01, 11).
>>> compute_venn2_colors(('r', 'g'))
(array([ 1., 0., 0.]), array([ 0. , 0.5, 0. ]), array([ 0.7 , 0.35, 0. ]))
'''
ccv = ColorConverter()
base_colors = [np.array(ccv.to_rgb(c)) for c in set_colors]
return (base_colors[0], base_colors[1], mix_colors(base_colors[0], base_colors[1]))
def update_line_specipic_points(nums, data, axes, to_do, font_size, axis_font):
"""Update the lines in the axes for snapshot of the whole process"""
colors =LAYERS_COLORS
x_ticks = [0, 2, 4, 6, 8, 10]
#Go over all the snapshot
for i in range(len(nums)):
num = nums[i]
#Plot the right layer
for layer_num in range(data.shape[3]):
axes[i].scatter(data[0, :, num, layer_num], data[1, :, num, layer_num], color = colors[layer_num], s = 105,edgecolors = 'black',alpha = 0.85)
utils.adjustAxes(axes[i], axis_font=axis_font, title_str='', x_ticks=x_ticks, y_ticks=[], x_lim=None,
y_lim=None,
set_xlabel=to_do[i][0], set_ylabel=to_do[i][1], x_label='$I(X;T)$', y_label='$I(T;Y)$',
set_xlim=True, set_ylim=True,
set_ticks=True, label_size=font_size)
def update_line(num, print_loss, data, axes, epochsInds, test_error, test_data, epochs_bins, loss_train_data, loss_test_data, colors,
font_size = 18, axis_font=16, x_lim = [0,12.2], y_lim=[0, 1.08], x_ticks = [], y_ticks = []):
"""Update the figure of the infomration plane for the movie"""
#Print the line between the points
cmap = ListedColormap(LAYERS_COLORS)
segs = []
for i in range(0, data.shape[1]):
x = data[0, i, num, :]
y = data[1, i, num, :]
points = np.array([x, y]).T.reshape(-1, 1, 2)
segs.append(np.concatenate([points[:-1], points[1:]], axis=1))
segs = np.array(segs).reshape(-1, 2, 2)
axes[0].clear()
if len(axes)>1:
axes[1].clear()
lc = LineCollection(segs, cmap=cmap, linestyles='solid',linewidths = 0.3, alpha = 0.6)
lc.set_array(np.arange(0,5))
#Print the points
for layer_num in range(data.shape[3]):
axes[0].scatter(data[0, :, num, layer_num], data[1, :, num, layer_num], color = colors[layer_num], s = 35,edgecolors = 'black',alpha = 0.85)
axes[1].plot(epochsInds[:num], 1 - np.mean(test_error[:, :num], axis=0), color ='r')
title_str = 'Information Plane - Epoch number - ' + str(epochsInds[num])
utils.adjustAxes(axes[0], axis_font, title_str, x_ticks, y_ticks, x_lim, y_lim, set_xlabel=True, set_ylabel=True,
x_label='$I(X;T)$', y_label='$I(T;Y)$')
title_str = 'Precision as function of the epochs'
utils.adjustAxes(axes[1], axis_font, title_str, x_ticks, y_ticks, x_lim, y_lim, set_xlabel=True, set_ylabel=True,
x_label='# Epochs', y_label='Precision')
def plot_animation_each_neuron(name_s, save_name, print_loss=False):
"""Plot the movie for all the networks in the information plane"""
# If we want to print the loss function also
#The bins that we extened the x axis of the accuracy each time
epochs_bins = [0, 500, 1500, 3000, 6000, 10000, 20000]
data_array = utils.get_data(name_s[0][0])
data = np.squeeze(data_array['information'])
f, (axes) = plt.subplots(1, 1)
axes = [axes]
f.subplots_adjust(left=0.14, bottom=0.1, right=.928, top=0.94, wspace=0.13, hspace=0.55)
colors = LAYERS_COLORS
#new/old version
Ix = np.squeeze(data[0,:, :, :])
Iy = np.squeeze(data[1,:, :, :])
#Interploation of the samplings (because we don't cauclaute the infomration in each epoch)
#interp_data_x = interp1d(epochsInds, Ix, axis=1)
#interp_data_y = interp1d(epochsInds, Iy, axis=1)
#new_x = np.arange(0,epochsInds[-1])
#new_data = np.array([interp_data_x(new_x), interp_data_y(new_x)])
""""
train_data = interp1d(epochsInds, np.squeeze(train_data), axis=1)(new_x)
test_data = interp1d(epochsInds, np.squeeze(test_data), axis=1)(new_x)
if print_loss:
loss_train_data = interp1d(epochsInds, np.squeeze(loss_train_data), axis=1)(new_x)
loss_test_data=interp1d(epochsInds, np.squeeze(loss_test_data), axis=1)(new_x)
"""
line_ani = animation.FuncAnimation(f, update_line_each_neuron, Ix.shape[1], repeat=False,
interval=1, blit=False, fargs=(print_loss, Ix, axes,Iy,train_data,test_data,epochs_bins, loss_train_data,loss_test_data, colors,epochsInds))
Writer = animation.writers['ffmpeg']
writer = Writer(fps=100)
#Save the movie
line_ani.save(save_name+'_movie.mp4',writer=writer,dpi=250)
plt.show()
def rgb_to_hsv(rgb_list):
rgb_normalized = [1.0*rgb_list[0]/255, 1.0*rgb_list[1]/255, 1.0*rgb_list[2]/255]
hsv_normalized = matplotlib.colors.rgb_to_hsv([[rgb_normalized]])[0][0]
return hsv_normalized
def compute_color_histograms(cloud, using_hsv=False):
numBins = 64
# Compute histograms for the clusters
point_colors_list = []
# Step through each point in the point cloud
for point in pc2.read_points(cloud, skip_nans=True):
rgb_list = float_to_rgb(point[3])
if using_hsv:
point_colors_list.append(rgb_to_hsv(rgb_list) * 255)
else:
point_colors_list.append(rgb_list)
# Populate lists with color values
channel_1_vals = []
channel_2_vals = []
channel_3_vals = []
for color in point_colors_list:
channel_1_vals.append(color[0])
channel_2_vals.append(color[1])
channel_3_vals.append(color[2])
# Compute histograms for the colors in the point cloud
channel1_hist = np.histogram(channel_1_vals, bins=numBins, range=(0, 256))
channel2_hist = np.histogram(channel_2_vals, bins=numBins, range=(0, 256))
channel3_hist = np.histogram(channel_3_vals, bins=numBins, range=(0, 256))
# Concatenate and normalize the histograms
hist_features = np.concatenate((channel1_hist[0],channel2_hist[0], channel3_hist[0])).astype(np.float64)
normed_features = hist_features / np.sum(hist_features)
return normed_features
principal_component_analysis.py 文件源码
项目:ML-From-Scratch
作者: eriklindernoren
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def main():
# Demo of how to reduce the dimensionality of the data to two dimension
# and plot the results.
# Load the dataset
data = datasets.load_digits()
X = data.data
y = data.target
# Project the data onto the 2 primary principal components
X_trans = PCA().transform(X, 2)
x1 = X_trans[:, 0]
x2 = X_trans[:, 1]
cmap = plt.get_cmap('viridis')
colors = [cmap(i) for i in np.linspace(0, 1, len(np.unique(y)))]
class_distr = []
# Plot the different class distributions
for i, l in enumerate(np.unique(y)):
_x1 = x1[y == l]
_x2 = x2[y == l]
_y = y[y == l]
class_distr.append(plt.scatter(_x1, _x2, color=colors[i]))
# Add a legend
plt.legend(class_distr, y, loc=1)
# Axis labels
plt.suptitle("PCA Dimensionality Reduction")
plt.title("Digit Dataset")
plt.xlabel('Principal Component 1')
plt.ylabel('Principal Component 2')
plt.show()
def plot_in_2d(self, X, y=None, title=None, accuracy=None, legend_labels=None):
X_transformed = self._transform(X, dim=2)
x1 = X_transformed[:, 0]
x2 = X_transformed[:, 1]
class_distr = []
y = np.array(y).astype(int)
colors = [self.cmap(i) for i in np.linspace(0, 1, len(np.unique(y)))]
# Plot the different class distributions
for i, l in enumerate(np.unique(y)):
_x1 = x1[y == l]
_x2 = x2[y == l]
_y = y[y == l]
class_distr.append(plt.scatter(_x1, _x2, color=colors[i]))
# Plot legend
if not legend_labels is None:
plt.legend(class_distr, legend_labels, loc=1)
# Plot title
if title:
if accuracy:
perc = 100 * accuracy
plt.suptitle(title)
plt.title("Accuracy: %.1f%%" % perc, fontsize=10)
else:
plt.title(title)
# Axis labels
plt.xlabel('Principal Component 1')
plt.ylabel('Principal Component 2')
plt.show()
# Plot the dataset X and the corresponding labels y in 3D using PCA.
def bar3d(h2, ax, **kwargs):
"""Plot of 2D histograms as 3D boxes.
Parameters
----------
h2 : Histogram2D
Returns
-------
plt.Axes
"""
density = kwargs.pop("density", False)
data = get_data(h2, cumulative=False, flatten=True, density=density)
# transformed = transform_data(data, kwargs)
if "cmap" in kwargs:
cmap = _get_cmap(kwargs)
_, cmap_data = _get_cmap_data(data, kwargs)
colors = cmap(cmap_data)
else:
colors = kwargs.pop("color", "blue")
xpos, ypos = (arr.flatten() for arr in h2.get_bin_centers())
zpos = np.zeros_like(ypos)
dx, dy = (arr.flatten() for arr in h2.get_bin_widths())
_add_labels(ax, h2, kwargs)
ax.bar3d(xpos, ypos, zpos, dx, dy, data, color=colors, **kwargs)
ax.set_zlabel("density" if density else "frequency")
return ax
def polar_map(hist, ax, show_zero=True, **kwargs):
"""Polar map of polar histograms.
Similar to map, but supports less parameters.
Returns
-------
plt.Axes
"""
data = get_data(hist, cumulative=False, flatten=True,
density=kwargs.pop("density", False))
# transformed = transform_data(data, kwargs)
cmap = _get_cmap(kwargs)
norm, cmap_data = _get_cmap_data(data, kwargs)
colors = cmap(cmap_data)
rpos, phipos = (arr.flatten() for arr in hist.get_bin_left_edges())
dr, dphi = (arr.flatten() for arr in hist.get_bin_widths())
rmax, _ = (arr.flatten() for arr in hist.get_bin_right_edges())
bar_args = {}
if "zorder" in kwargs:
bar_args["zorder"] = kwargs.pop("zorder")
alphas = _get_alpha_data(cmap_data, kwargs)
if np.isscalar(alphas):
alphas = np.ones_like(data) * alphas
for i in range(len(rpos)):
if data[i] > 0 or show_zero:
bin_color = colors[i]
# TODO: align = "edge"
bars = ax.bar(phipos[i], dr[i], width=dphi[i], bottom=rpos[i], color=bin_color,
edgecolor=kwargs.get("grid_color", cmap(0.5)), lw=kwargs.get("lw", 0.5),
alpha=alphas[i], **bar_args)
ax.set_rmax(rmax.max())
return ax
def _get_cmap_data(data, kwargs):
"""Get normalized values to be used with a colormap.
Parameters
----------
data : array_like
cmap_min : Optional[float] or "min"
By default 0. If "min", minimum value of the data.
cmap_max : Optional[float]
By default, maximum value of the data
cmap_normalize : str or colors.Normalize
Returns
-------
normalizer : colors.Normalize
normalized_data : array_like
"""
norm = kwargs.pop("cmap_normalize", None)
if norm == "log":
cmap_max = kwargs.pop("cmap_max", data.max())
cmap_min = kwargs.pop("cmap_min", data[data > 0].min())
norm = colors.LogNorm(cmap_min, cmap_max)
elif not norm:
cmap_max = kwargs.pop("cmap_max", data.max())
cmap_min = kwargs.pop("cmap_min", 0)
if cmap_min == "min":
cmap_min = data.min()
norm = colors.Normalize(cmap_min, cmap_max, clip=True)
return norm, norm(data)
def _add_colorbar(ax, cmap, cmap_data, norm):
"""Show a colorbar right of the plot.
Parameters
----------
ax : plt.Axes
cmap : colors.Colormap
cmap_data : array_like
norm : colors.Normalize
"""
fig = ax.get_figure()
mappable = cm.ScalarMappable(cmap=cmap, norm=norm)
mappable.set_array(cmap_data) # TODO: Or what???
fig.colorbar(mappable, ax=ax)
def __init__(self, line_width=0.002, alpha = 1.0, color='black'):
from matplotlib.colors import ColorConverter
conv = ColorConverter()
PlotCallback.__init__(self)
self.line_width = line_width
self.alpha = alpha
self.color = (np.array(conv.to_rgb(color)) * 255).astype("uint8")
def get_cmap(N):
'''Returns a function that maps each index in 0, 1, ... N-1 to a distinct RGB color.'''
color_norm = colors.Normalize(vmin=0, vmax=N-1)
scalar_map = cmx.ScalarMappable(norm=color_norm, cmap='hsv')
def map_index_to_rgb_color(index):
return scalar_map.to_rgba(index)
return map_index_to_rgb_color
def scatter_classes(x, classes, ax=None):
"""Scatter the data points coloring by the classes."""
if ax is None:
_fig, ax = plt.subplots()
ax = plt.gca() if ax is None else ax
cmap = matplotlib.cm.jet
norm = matplotlib.colors.Normalize(
vmin=np.min(classes), vmax=np.max(classes))
mapper = matplotlib.cm.ScalarMappable(cmap=cmap, norm=norm)
colors = mapper.to_rgba(classes)
ax.scatter(x[:,0], x[:,1], color=colors)
return ax