def test_kpls(self):
import numpy as np
import matplotlib.pyplot as plt
from smt.methods import KPLS
xt = np.array([0., 1., 2., 3., 4.])
yt = np.array([0., 1., 1.5, 0.5, 1.0])
sm = KPLS(theta0=[1e-2])
sm.set_training_values(xt, yt)
sm.train()
num = 100
x = np.linspace(0., 4., num)
y = sm.predict_values(x)
plt.plot(xt, yt, 'o')
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.legend(['Training data', 'Prediction'])
plt.show()
python类pyplot()的实例源码
def test_kplsk(self):
import numpy as np
import matplotlib.pyplot as plt
from smt.methods import KPLSK
xt = np.array([0., 1., 2., 3., 4.])
yt = np.array([0., 1., 1.5, 0.5, 1.0])
sm = KPLSK(theta0=[1e-2])
sm.set_training_values(xt, yt)
sm.train()
num = 100
x = np.linspace(0., 4., num)
y = sm.predict_values(x)
yy = sm.predict_derivatives(xt,0)
plt.plot(xt, yt, 'o')
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.legend(['Training data', 'Prediction'])
plt.show()
def test_random(self):
import numpy as np
import matplotlib.pyplot as plt
from smt.sampling import Random
xlimits = np.array([
[0., 4.],
[0., 3.],
])
sampling = Random(xlimits=xlimits)
num = 50
x = sampling(num)
print(x.shape)
plt.plot(x[:, 0], x[:, 1], 'o')
plt.xlabel('x')
plt.ylabel('y')
plt.show()
def test_lhs(self):
import numpy as np
import matplotlib.pyplot as plt
from smt.sampling import LHS
xlimits = np.array([
[0., 4.],
[0., 3.],
])
sampling = LHS(xlimits=xlimits)
num = 50
x = sampling(num)
print(x.shape)
plt.plot(x[:, 0], x[:, 1], 'o')
plt.xlabel('x')
plt.ylabel('y')
plt.show()
def test_full_factorial(self):
import numpy as np
import matplotlib.pyplot as plt
from smt.sampling import FullFactorial
xlimits = np.array([
[0., 4.],
[0., 3.],
])
sampling = FullFactorial(xlimits=xlimits)
num = 50
x = sampling(num)
print(x.shape)
plt.plot(x[:, 0], x[:, 1], 'o')
plt.xlabel('x')
plt.ylabel('y')
plt.show()
PlottingOutliers.py 文件源码
项目:MarksPredictor-AzureMachineLearning
作者: keshav123456
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
def auto_scatter_outlier(df, plot_cols):
import matplotlib.pyplot as plt
outlier = [0,0,1,1] # Vector of outlier indicators
color = ['DarkBlue','DarkBlue','Red','Red'] # vector of color choices for plot
marker = ['x','o','o','x'] # vector of shape choices for plot
for col in plot_cols: # loop over the columns
fig = plt.figure(figsize=(6, 6))
ax = fig.gca()
## Loop over the zip of the four vectors an subset the data and
## create the plot using the aesthetics provided
for o, c, m in zip(outlier, color, marker):
temp = df.ix[(df['outlier'] == o)]
if temp.shape[0] > 0:
temp.plot(kind = 'scatter', x = col, y = 'Marks' ,
ax = ax, color = c, marker = m)
ax.set_title('Scatter plot of marks vs. ' + col)
fig.savefig('scatter_' + col + '.png')
return plot_cols
def ensure_pyplot(self):
"""
Ensures that pyplot has been imported into the embedded IPython shell.
Also, makes sure to set the backend appropriately if not set already.
"""
# We are here if the @figure pseudo decorator was used. Thus, it's
# possible that we could be here even if python_mplbackend were set to
# `None`. That's also strange and perhaps worthy of raising an
# exception, but for now, we just set the backend to 'agg'.
if not self._pyplot_imported:
if 'matplotlib.backends' not in sys.modules:
# Then ipython_matplotlib was set to None but there was a
# call to the @figure decorator (and ipython_execlines did
# not set a backend).
#raise Exception("No backend was set, but @figure was used!")
import matplotlib
matplotlib.use('agg')
# Always import pyplot into embedded shell.
self.process_input_line('import matplotlib.pyplot as plt',
store_history=False)
self._pyplot_imported = True
def activate_matplotlib(backend):
"""Activate the given backend and set interactive to True."""
import matplotlib
matplotlib.interactive(True)
# Matplotlib had a bug where even switch_backend could not force
# the rcParam to update. This needs to be set *before* the module
# magic of switch_backend().
matplotlib.rcParams['backend'] = backend
import matplotlib.pyplot
matplotlib.pyplot.switch_backend(backend)
# This must be imported last in the matplotlib series, after
# backend/interactivity choices have been made
import matplotlib.pyplot as plt
plt.show._needmain = False
# We need to detect at runtime whether show() is called by the user.
# For this, we wrap it into a decorator which adds a 'called' flag.
plt.draw_if_interactive = flag_calls(plt.draw_if_interactive)
def vis_detections(self, im, class_name, gt_boxes, dets):
"""Visual debugging of detections."""
import matplotlib
matplotlib.use('TkAgg') # For Mac OS
import matplotlib.pyplot as plt
import matplotlib.patches as patches
fig, ax = plt.subplots(1)
for i in range(np.minimum(10, dets.shape[0])):
bbox = dets[i,1:]
print(bbox)
ax.imshow(np.squeeze(im), cmap="gray")
self.plot_patch(ax, patches, bbox, gt=False)
plt.title(class_name)
self.plot_patch(ax, patches, gt_boxes[0][:4], gt=True)
# Display Final composite image
plt.show()
def plot_func(cause, effect, seasonal, different, heatmap_func, title):
heatmap = numpy.zeros((len(sigma01_vals), len(sd_proc_vals)))
eps = eps_vals[seasonal]
beta00 = beta00_vals[different]
for i, sigma01 in enumerate(sigma01_vals):
for j, sd_proc in enumerate(sd_proc_vals):
heatmap[i,j] = heatmap_func(cause, effect, eps, beta00, sigma01, sd_proc)
print heatmap
plot_heatmap(heatmap,
'sd_proc', ['{0:.2g}'.format(x) for x in sd_proc_vals],
'sigma01', ['{0:.2g}'.format(y) for y in sigma01_vals],
vmin=0, vmax=1
)
pyplot.title('{}: {} causes {}'.format(title, cause, effect))
def render_systems(params=None):
figure = pyplot.figure()
axes = figure.add_subplot(111, projection='3d')
for currentSystem in database.get_star_log_hashes(from_highest=True):
current_position = util.get_cartesian(currentSystem)
xs = [current_position[0], current_position[0]]
ys = [current_position[1], current_position[1]]
zs = [0, current_position[2]]
axes.plot(xs, ys, zs)
axes.scatter(current_position[0], current_position[1], current_position[2], label=util.get_system_name(currentSystem))
axes.legend()
axes.set_title('Systems')
axes.set_xlabel('X')
axes.set_ylabel('Y')
axes.set_zlabel('Z')
pyplot.show()
def Plot(obj, ys=None, style='', **options):
"""Plots a line.
Args:
obj: sequence of x values, or Series, or anything with Render()
ys: sequence of y values
style: style string passed along to pyplot.plot
options: keyword args passed to pyplot.plot
"""
options = _UnderrideColor(options)
label = getattr(obj, 'label', '_nolegend_')
options = _Underride(options, linewidth=3, alpha=0.8, label=label)
xs = obj
if ys is None:
if hasattr(obj, 'Render'):
xs, ys = obj.Render()
if isinstance(obj, pandas.Series):
ys = obj.values
xs = obj.index
if ys is None:
pyplot.plot(xs, style, **options)
else:
pyplot.plot(xs, ys, style, **options)
def Pcolor(xs, ys, zs, pcolor=True, contour=False, **options):
"""Makes a pseudocolor plot.
xs:
ys:
zs:
pcolor: boolean, whether to make a pseudocolor plot
contour: boolean, whether to make a contour plot
options: keyword args passed to pyplot.pcolor and/or pyplot.contour
"""
_Underride(options, linewidth=3, cmap=matplotlib.cm.Blues)
X, Y = np.meshgrid(xs, ys)
Z = zs
x_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False)
axes = pyplot.gca()
axes.xaxis.set_major_formatter(x_formatter)
if pcolor:
pyplot.pcolormesh(X, Y, Z, **options)
if contour:
cs = pyplot.contour(X, Y, Z, **options)
pyplot.clabel(cs, inline=1, fontsize=10)
def ensure_pyplot(self):
"""
Ensures that pyplot has been imported into the embedded IPython shell.
Also, makes sure to set the backend appropriately if not set already.
"""
# We are here if the @figure pseudo decorator was used. Thus, it's
# possible that we could be here even if python_mplbackend were set to
# `None`. That's also strange and perhaps worthy of raising an
# exception, but for now, we just set the backend to 'agg'.
if not self._pyplot_imported:
if 'matplotlib.backends' not in sys.modules:
# Then ipython_matplotlib was set to None but there was a
# call to the @figure decorator (and ipython_execlines did
# not set a backend).
#raise Exception("No backend was set, but @figure was used!")
import matplotlib
matplotlib.use('agg')
# Always import pyplot into embedded shell.
self.process_input_line('import matplotlib.pyplot as plt',
store_history=False)
self._pyplot_imported = True
def feature_range(maximums, minimums):
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
feature_num = len(maximums)
ax.bar(range(feature_num), maximums - minimums, color='r', align='center')
ax.set_title('feature scale')
plt.xticks(range(feature_num), feature_names)
plt.xlim([-1, feature_num])
fig.set_figheight(6)
fig.set_figwidth(10)
if not os.path.exists('./image'):
os.makedirs('./image')
fig.savefig('image/ranges.png', dpi=48)
plt.close(fig)
def _prepare_trellis(n_cells, max_col):
"""Aux function
"""
import matplotlib.pyplot as plt
if n_cells == 1:
nrow = ncol = 1
elif n_cells <= max_col:
nrow, ncol = 1, n_cells
else:
nrow, ncol = int(math.ceil(n_cells / float(max_col))), max_col
fig, axes = plt.subplots(nrow, ncol, figsize=(7.4, 1.5 * nrow + 1))
axes = [axes] if ncol == nrow == 1 else axes.flatten()
for ax in axes[n_cells:]: # hide unused axes
# XXX: Previously done by ax.set_visible(False), but because of mpl
# bug, we just hide the frame.
from .topomap import _hide_frame
_hide_frame(ax)
return fig, axes
def figure_nobar(*args, **kwargs):
"""Make matplotlib figure with no toolbar"""
from matplotlib import rcParams, pyplot as plt
old_val = rcParams['toolbar']
try:
rcParams['toolbar'] = 'none'
fig = plt.figure(*args, **kwargs)
# remove button press catchers (for toolbar)
cbs = list(fig.canvas.callbacks.callbacks['key_press_event'].keys())
for key in cbs:
fig.canvas.callbacks.disconnect(key)
except Exception as ex:
raise ex
finally:
rcParams['toolbar'] = old_val
return fig
def plot_clicks(self, **kwargs):
"""Plot the x/y positions stored in self.coords.
Parameters
----------
**kwargs : dict
Arguments are passed to imshow in displaying the bg image.
"""
from matplotlib.pyplot import subplots
f, ax = subplots()
ax.imshow(self.imdata, extent=(0, self.xmax, 0, self.ymax), **kwargs)
xlim, ylim = [ax.get_xlim(), ax.get_ylim()]
xcoords, ycoords = zip(*self.coords)
ax.scatter(xcoords, ycoords, c='r')
ann_text = np.arange(len(self.coords)).astype(str)
for txt, coord in zip(ann_text, self.coords):
ax.annotate(txt, coord, fontsize=20, color='r')
ax.set_xlim(xlim)
ax.set_ylim(ylim)
plt_show()
def plot_clustermap(sequences, title, plotpath, size=300, dpi=200):
"""
Plot a clustermap of the given sequences
size -- Downsample to this many sequences
title -- plot title
Return the number of clusters.
"""
logger.info('Clustering %d sequences (downsampled to at most %d)', len(sequences), size)
sequences = downsampled(sequences, size)
df, linkage, clusters = cluster_sequences(sequences)
palette = sns.color_palette([(0.15, 0.15, 0.15)])
palette += sns.color_palette('Spectral', n_colors=max(clusters), desat=0.9)
row_colors = [ palette[cluster_id] for cluster_id in clusters ]
cm = sns.clustermap(df,
row_linkage=linkage,
col_linkage=linkage,
row_colors=row_colors,
linewidths=None,
linecolor='none',
figsize=(210/25.4, 210/25.4),
cmap='Blues',
xticklabels=False,
yticklabels=False
)
if title is not None:
cm.fig.suptitle(title)
cm.savefig(plotpath, dpi=dpi)
# free the memory used by the plot
import matplotlib.pyplot as plt
plt.close('all')
return len(set(clusters))
def _savePlot(self, data, filename):
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.plot(data)
plt.savefig(filename)