def plot_trajectory(name):
STEPS = 600
DELTA = 1 if name != 'linear' else 0.1
trajectory = create_trajectory(name, STEPS)
x = [trajectory.get_position_at(i * DELTA).x for i in range(STEPS)]
y = [trajectory.get_position_at(i * DELTA).y for i in range(STEPS)]
trajectory_fig, trajectory_plot = plt.subplots(1, 1)
trajectory_plot.plot(x, y, label='trajectory', lw=3)
trajectory_plot.set_title(name.title() + ' Trajectory', fontsize=20)
trajectory_plot.set_xlabel(r'$x{\rm[m]}$', fontsize=18)
trajectory_plot.set_ylabel(r'$y{\rm[m]}$', fontsize=18)
trajectory_plot.legend(loc=0)
trajectory_plot.grid()
plt.show()
python类show()的实例源码
def compare_images(path = '.'):
S_limit = 10.
file_list = glob.glob(os.path.join(path, 'Abu*'))
file_list_master = glob.glob(os.path.join(path, 'MasterAbu*'))
file_list.sort()
file_list_master.sort()
S=[]
print("Identifying images with rmq > "+'%3.1f'%S_limit)
ierr_count = 0
for i in range(len(file_list)):
this_S,fimg1,fimg2 = compare_entropy(file_list[i],file_list_master[i])
if this_S > S_limit:
warnings.warn(file_list[i]+" and "+file_list_master[i]+" differ by "+'%6.3f'%this_S)
ierr_count += 1
S.append(this_S)
if ierr_count > 0:
print("Error: at least one image differs by more than S_limit")
sys.exit(1)
#print ("S: ",S)
#plb.plot(S,'o')
#plb.xlabel("image number")
#plb.ylabel("modified log KL-divergence to previous image")
#plb.show()
def postaud(x, fmax, fbtype=None):
if fbtype is None:
fbtype = 'bark'
nbands = x.shape[0]
nframes = x.shape[1]
nfpts = nbands
if fbtype == 'bark':
bancfhz = bark2freq(np.linspace(0, freq2bark(fmax), nfpts))
fsq = bancfhz * bancfhz
ftmp = fsq + 1.6e5
eql = ((fsq/ftmp)**2) * ((fsq + 1.44e6)/(fsq + 9.61e6))
'''
plt.figure()
plt.plot(eql)
plt.show()
'''
eql = eql.reshape(np.size(eql), 1)
z = np.repeat(eql, nframes, axis=1) * x
z = z ** (1./3.)
y = np.vstack((z[1, :], z[1:nbands-1, :], z[nbands-2, :]))
return y
def plot_volcano(logFC,p_val,sample_name,saveName,logFC_thresh):
fig=pl.figure()
## To plot and save
pl.scatter(logFC[(p_val>0.05)|(abs(logFC)<logFC_thresh)],-np.log10(p_val[(p_val>0.05)|(abs(logFC)<logFC_thresh)]),color='blue',alpha=0.5);
pl.scatter(logFC[(p_val<0.05)&(abs(logFC)>logFC_thresh)],-np.log10(p_val[(p_val<0.05)&(abs(logFC)>logFC_thresh)]),color='red');
pl.hlines(-np.log10(0.05),min(logFC),max(logFC))
pl.vlines(-logFC_thresh,min(-np.log10(p_val)),max(-np.log10(p_val)))
pl.vlines(logFC_thresh,min(-np.log10(p_val)),max(-np.log10(p_val)))
pl.xlim(-3,3)
pl.xlabel('Log Fold Change')
pl.ylabel('-log10(p-value)')
pl.savefig(saveName)
pl.close(fig)
# def plot_histograms(df_peaks,pntr_list):
#
# for pntr in pntr_list:
# colName =pntr[2]+'_Intragenic_position'
# pl.hist(df_peaks[colName])
# pl.xlabel(colName)
# pl.ylabel()
# pl.show()
def plot(l, x1, x2, y, e):
# Plot
time_range = numpy.arange(0, l)
pl.figure(1)
pl.subplot(221)
pl.plot(time_range, x1)
pl.title("Input signal")
pl.subplot(222)
pl.plot(time_range, x2, c="r")
pl.plot(time_range, y, c="b")
pl.title("Reference signal")
pl.subplot(223)
pl.plot(time_range, e, c="r")
pl.title("Noise")
pl.xlabel("time")
pl.show()
def make_fft_graph(fft, corre):
fft_np = numpy.array(fft).swapaxes(0, 1).swapaxes(1, 2)
channel_N, freq_N, sample_N = fft_np.shape
if (channel_N > 6): # We don't have space for more than 6 channels
return
fig, axes = plt.subplots(2, 3)
fig.subplots_adjust(hspace=0.3, wspace=0.05)
for ax, mat, i in zip(axes.flat, fft_np, range(1, channel_N + 1)):
fft_abs = numpy.abs(mat)
fft_less_row = fft_abs[0::20]
n = freq_N / 20
fft_sqr = numpy.repeat(fft_less_row, int(n / sample_N)).reshape([n, n])
ax.matshow(fft_sqr, cmap='viridis')
plt.xlabel('time')
plt.ylabel('freq')
ax.set_title('Channel {0}'.format(i))
plt.show()
print("Plotted.")
def run_regression_1D_aep_two_layers():
np.random.seed(42)
print "create dataset ..."
Xtrain, ytrain, Xtest, ytest = create_dataset()
alpha = 1 # other alpha is not valid here
M = 20
model = aep.SDGPR(Xtrain, ytrain, M, hidden_sizes=[2])
model.optimise(method='L-BFGS-B', alpha=1, maxiter=5000, disp=False)
my, vy = model.predict_y(Xtest)
my = np.reshape(my, ytest.shape)
vy = np.reshape(vy, ytest.shape)
rmse = np.sqrt(np.mean((my - ytest)**2))
ll = np.mean(-0.5 * np.log(2 * np.pi * vy) - 0.5 * (ytest - my)**2 / vy)
nlml, _ = model.objective_function(model.get_hypers(), Xtrain.shape[0], alpha)
print 'alpha=%.3f, train ml=%3f, test rmse=%.3f, ll=%.3f' % (alpha, nlml, rmse, ll)
# plot(model, Xtrain, ytrain)
# plt.show()
# should produce something like this
# alpha=1.000, train ml=-51.385404, test rmse=0.168, ll=0.311
def run_regression_1D_aep_two_layers_stoc():
np.random.seed(42)
print "create dataset ..."
Xtrain, ytrain, Xtest, ytest = create_dataset()
alpha = 1 # other alpha is not valid here
M = 20
model = aep.SDGPR(Xtrain, ytrain, M, hidden_sizes=[2])
model.optimise(method='adam', alpha=1, maxiter=5000, disp=False)
my, vy = model.predict_y(Xtest)
my = np.reshape(my, ytest.shape)
vy = np.reshape(vy, ytest.shape)
rmse = np.sqrt(np.mean((my - ytest)**2))
ll = np.mean(-0.5 * np.log(2 * np.pi * vy) - 0.5 * (ytest - my)**2 / vy)
nlml, _ = model.objective_function(model.get_hypers(), Xtrain.shape[0], alpha)
print 'alpha=%.3f, train ml=%3f, test rmse=%.3f, ll=%.3f' % (alpha, nlml, rmse, ll)
# plot(model, Xtrain, ytrain)
# plt.show()
# should produce something like this
# alpha=1.000, train ml=-69.444086, test rmse=0.170, ll=0.318
def plot(param, show = 1):
"""Returns the plot of spectrum as a pyplot object or plot it on the screen
Keyword arguments:
param -- Output spectrum file
show -- Optional, plot the spectrum on the screen. Enabled by default.
"""
s = sed.SED()
s.grmonty(param)
plt = pylab.plot(s.lognu, s.ll)
if show == 1:
pylab.show()
else:
return plt
def plot_confusion_matrix(cm, label_list, title='Confusion matrix', cmap=None):
from matplotlib import pylab
cm = np.asarray(cm, dtype=np.float32)
for i, row in enumerate(cm):
cm[i] = cm[i] / np.sum(cm[i])
#import matplotlib.pyplot as plt
#plt.ion()
pylab.clf()
pylab.matshow(cm, fignum=False, cmap='Blues', vmin=0, vmax=1.0)
ax = pylab.axes()
ax.set_xticks(range(len(label_list)))
ax.set_xticklabels(label_list, rotation='vertical')
ax.xaxis.set_ticks_position('bottom')
ax.set_yticks(range(len(label_list)))
ax.set_yticklabels(label_list)
pylab.title(title)
pylab.colorbar()
pylab.grid(False)
pylab.xlabel('Predicted class')
pylab.ylabel('True class')
pylab.grid(False)
pylab.savefig('test.jpg')
pylab.show()
def plotRes(pre, real, test_x,l):
s = set(pre)
col = ['r','b','g','y','m']
fig = plt.figure()
ax = fig.add_subplot(111)
for i in range(0, len(s)):
index1 = pre == i
index2 = real == i
x1 = test_x[index1, :]
x2 = test_x[index2, :]
ax.scatter(x1[:,0],x1[:,1],color=col[i],marker='v',linewidths=0.5)
ax.scatter(x2[:,0],x2[:,1],color=col[i],marker='.',linewidths=12)
plt.title('learning rating='+str(l))
plt.legend(('c1:predict','c1:true',\
'c2:predict','c2:true',
'c3:predict','c3:true',
'c4:predict','c4:true',
'c5:predict','c5:true'), shadow = True, loc = (0.01, 0.4))
plt.show()
def __init__(self, data, **kwargs):
# Settings
self.show_ticks = kwargs.get("show_ticks", False)
self.show_values = kwargs.get("show_values", False)
self.show = kwargs.get("show", False)
self.labels = kwargs.get("labels", None)
# Setup plot
self.rows, self.cols = data.shape
self.fig = plt.figure()
self.plt_ax = self.fig.add_subplot(111)
self.cov_ax = self.plt_ax.matshow(np.array(data))
# Covariance matrix labels
self.label_values = self._add_data_labels(data)
self._add_axis_labels(data)
# Color bar
self.color_bar = self.fig.colorbar(self.cov_ax)
# Show plot
if self.show:
plt.show(block=False)
def test_plot_error_ellipse(self):
# Generate random data
x = np.random.normal(0, 1, 300)
s = np.array([2.0, 2.0])
y1 = np.random.normal(s[0] * x)
y2 = np.random.normal(s[1] * x)
data = np.array([y1, y2])
# Calculate covariance and plot error ellipse
cov = np.cov(data)
plot_error_ellipse([0.0, 0.0], cov)
debug = False
if debug:
plt.scatter(data[0, :], data[1, :])
plt.xlim([-8, 8])
plt.ylim([-8, 8])
plt.show()
plt.clf()
def test_augment_state(self):
self.msckf.augment_state()
N = self.msckf.N()
self.assertTrue(self.msckf.P_cam is not None)
self.assertTrue(self.msckf.P_imu_cam is not None)
self.assertEqual(self.msckf.P_cam.shape, (N * 6, N * 6))
self.assertEqual(self.msckf.P_imu_cam.shape, (15, N * 6))
self.assertEqual(self.msckf.N(), 2)
self.assertTrue(np.array_equal(self.msckf.cam_states[0].q_CG,
self.msckf.ext_q_CI))
self.assertEqual(self.msckf.counter_frame_id, 2)
# Plot matrix
# debug = True
debug = False
if debug:
ax = plt.subplot(111)
ax.matshow(self.msckf.P())
plt.show()
def test_F(self):
w_hat = np.array([1.0, 2.0, 3.0])
q_hat = np.array([0.0, 0.0, 0.0, 1.0])
a_hat = np.array([1.0, 2.0, 3.0])
w_G = np.array([0.1, 0.1, 0.1])
F = self.imu_state.F(w_hat, q_hat, a_hat, w_G)
# -- First row --
self.assertTrue(np_equal(F[0:3, 0:3], -skew(w_hat)))
self.assertTrue(np_equal(F[0:3, 3:6], -np.ones((3, 3))))
# -- Third Row --
self.assertTrue(np_equal(F[6:9, 0:3], dot(-C(q_hat).T, skew(a_hat))))
self.assertTrue(np_equal(F[6:9, 6:9], -2.0 * skew(w_G)))
self.assertTrue(np_equal(F[6:9, 9:12], -C(q_hat).T))
self.assertTrue(np_equal(F[6:9, 12:15], -skewsq(w_G)))
# -- Fifth Row --
self.assertTrue(np_equal(F[12:15, 6:9], np.ones((3, 3))))
# Plot matrix
if self.debug:
ax = plt.subplot(111)
ax.matshow(F)
plt.show()
def test_G(self):
q_hat = np.array([0.0, 0.0, 0.0, 1.0]).reshape((4, 1))
G = self.imu_state.G(q_hat)
# -- First row --
self.assertTrue(np_equal(G[0:3, 0:3], -np.ones((3, 3))))
# -- Second row --
self.assertTrue(np_equal(G[3:6, 3:6], np.ones((3, 3))))
# -- Third row --
self.assertTrue(np_equal(G[6:9, 6:9], -C(q_hat).T))
# -- Fourth row --
self.assertTrue(np_equal(G[9:12, 9:12], np.ones((3, 3))))
# Plot matrix
if self.debug:
ax = plt.subplot(111)
ax.matshow(G)
plt.show()
def test_J(self):
# Setup
cam_q_CI = np.array([0.0, 0.0, 0.0, 1.0])
cam_p_IC = np.array([1.0, 1.0, 1.0])
q_hat_IG = np.array([0.0, 0.0, 0.0, 1.0])
N = 1
J = self.imu_state.J(cam_q_CI, cam_p_IC, q_hat_IG, N)
# Assert
C_CI = C(cam_q_CI)
C_IG = C(q_hat_IG)
# -- First row --
self.assertTrue(np_equal(J[0:3, 0:3], C_CI))
# -- Second row --
self.assertTrue(np_equal(J[3:6, 0:3], skew(dot(C_IG.T, cam_p_IC))))
# -- Third row --
self.assertTrue(np_equal(J[3:6, 12:15], I(3)))
# Plot matrix
if self.debug:
ax = plt.subplot(111)
ax.matshow(J)
plt.show()
def test_project(self):
# Load points
points_file = join(test.TEST_DATA_PATH, "house/house.p3d")
points = np.loadtxt(points_file).T
# Setup camera
K = np.eye(3)
R = np.eye(3)
t = np.array([0, 0, 0])
camera = PinholeCameraModel(320, 240, K)
x = camera.project(points, R, t)
# Assert
self.assertEqual(x.shape, (3, points.shape[1]))
self.assertTrue(np.all(x[2, :] == 1.0))
# Plot projection
debug = False
# debug = True
if debug:
plt.figure()
plt.plot(x[0], x[1], 'k. ')
plt.show()
def plot(self, track, track_cam_states, estimates):
plt.figure()
# Feature
feature = T_global_camera * track.ground_truth
plt.plot(feature[0], feature[1],
marker="o", color="red", label="feature")
# Camera states
for cam_state in track_cam_states:
pos = T_global_camera * cam_state.p_G
plt.plot(pos[0], pos[1],
marker="o", color="blue", label="camera")
# Estimates
for i in range(len(estimates)):
cam_state = track_cam_states[i]
cam_pos = T_global_camera * cam_state.p_G
estimate = (T_global_camera * estimates[i]) + cam_pos
plt.plot(estimate[0], estimate[1],
marker="o", color="green")
plt.legend(loc=0)
plt.show()
def summary(self):
"""
This function is used to summary the result.
If you want calculate some other indicator, you can add them here.
:return:
"""
if self._analysis is not None:
self._analysis(self.asset_dict)
# for x in self.asset_dict:
# self.get_benchmark()
# asset_return = (self.asset_dict[x] - self._base_fund) / self._base_fund
# asset_return = asset_return.add_prefix(str(x) + "_")
# print asset_return
# result = pd.merge(asset_return, self._benchmark_data,
# left_index=True, right_index=True, how="inner")
# max_return = self.get_max_return(x, begin=self._begin_date, end=self._end_date)
# print max_return
# # print result
# # if self._analysis is not None:
# # self._analysis(result)
# # result.plot()
# # plt.show()
def x_corr(a,b,center_time_s=1000.0,window_len_s=50.0,plot=True):
center_index = int(center_time_s/a.dt)
window_index = int(window_len_s/(a.dt))
print "center_index is", center_index
print "window_index is", window_index
t1 = a.trace_x[(center_index - window_index) : (center_index + window_index)]
t2 = b.trace_x[(center_index - window_index) : (center_index + window_index)]
print t1
time_window = np.linspace((-window_len_s/2.0), (window_len_s/2), len(t1))
#print time_window
#plt.plot(time_window, t1)
#plt.plot(time_window, t2)
#plt.show()
x_corr_time = correlate(t1, t2)
delay = (np.argmax(x_corr_time) - (len(x_corr_time)/2) ) * a.dt
#print "the delay is ", delay
return delay
def plotLine(self, x_vals, y_vals, x_label, y_label, title, filename=None):
plt.clf()
plt.xlabel(x_label)
plt.xlim(((min(x_vals) - 0.5), (max(x_vals) + 0.5)))
plt.ylabel(y_label)
plt.ylim(((min(y_vals) - 0.5), (max(y_vals) + 0.5)))
plt.title(title)
plt.plot(x_vals, y_vals, c='k', lw=2)
#plt.plot(x_vals, len(x_vals) * y_vals[0], c='r', lw=2)
if filename == None:
plt.show()
else:
plt.savefig(self.outputPath + filename)
utils.py 文件源码
项目:Building-Machine-Learning-Systems-With-Python-Second-Edition
作者: PacktPublishing
项目源码
文件源码
阅读 19
收藏 0
点赞 0
评论 0
def plot_confusion_matrix(cm, genre_list, name, title):
pylab.clf()
pylab.matshow(cm, fignum=False, cmap='Blues', vmin=0, vmax=1.0)
ax = pylab.axes()
ax.set_xticks(range(len(genre_list)))
ax.set_xticklabels(genre_list)
ax.xaxis.set_ticks_position("bottom")
ax.set_yticks(range(len(genre_list)))
ax.set_yticklabels(genre_list)
pylab.title(title)
pylab.colorbar()
pylab.grid(False)
pylab.show()
pylab.xlabel('Predicted class')
pylab.ylabel('True class')
pylab.grid(False)
pylab.savefig(
os.path.join(CHART_DIR, "confusion_matrix_%s.png" % name), bbox_inches="tight")
def plotKChart(self, misClassDict, saveFigPath):
kList = []
misRateList = []
for k, misClassNum in misClassDict.iteritems():
kList.append(k)
misRateList.append(1.0 - 1.0/k*misClassNum)
fig = plt.figure(saveFigPath)
plt.plot(kList, misRateList, 'r--')
plt.title(saveFigPath)
plt.xlabel('k Num.')
plt.ylabel('Misclassified Rate')
plt.legend(saveFigPath)
plt.grid(True)
plt.savefig(saveFigPath)
plt.show()
################################### PART3 TEST ########################################
# ??
def backtest(config_file, day_trade):
cfg = config.Config(config_file)
cfg.day_trade = day_trade
dfs = load_data(config_file)
trender = strategies[cfg.strategy](**cfg.strategy_parameters)
res = []
for df in dfs:
res.append(trender.backtest(data_frame=df))
final_panel = pd.Panel({os.path.basename(p['path']): df for p, df in
zip(cfg.data_path, res)})
profit_series = final_panel.sum(axis=0)['total_profit'].cumsum()
final_panel.to_excel(cfg.output_file)
if cfg.show:
profit_series.plot()
plt.xlabel('Time')
plt.ylabel('Profit')
plt.legend('Profit')
plt.show()
def get_captcha_image(filename):
screenshot = driver.get_screenshot_as_png()
screenshot = Image.open(BytesIO(screenshot))
# screenshot.show()
captcha_el = driver.find_element_by_class_name("gt_box")
location = captcha_el.location
size = captcha_el.size
left = location['x']
top = location['y']
right = location['x'] + size['width']
bottom = location['y'] + size['height']
box = (left, top, right, bottom)
print(box)
if box[0] == 0:
raise(Exception('======='))
captcha_image = screenshot.crop(box)
captcha_image.save(filename) # "%s.png" % uuid.uuid4().hex
print(u'????')
def show_samples(y, ndim, nb=10, cmap=''):
if ndim == 4:
for i in range(nb**2):
plt.subplot(nb, nb, i+1)
plt.imshow(y[i], cmap=cmap, interpolation='none')
plt.axis('off')
else:
x = y[0]
y = y[1]
plt.figure(0)
for i in range(10):
plt.subplot(2, 5, i+1)
plt.imshow(x[i], cmap=cmap, interpolation='none')
plt.axis('off')
plt.figure(1)
for i in range(10):
plt.subplot(2, 5, i+1)
plt.imshow(y[i], cmap=cmap, interpolation='none')
plt.axis('off')
plt.show()
def fit_data():
data=np.loadtxt('data.dat')
print(data)
params = dict()
params["c"] = {"min" : -np.inf,"max" : np.inf}
result = qudi_fitting.make_lorentzian_fit(axis=data[:,0], data=data[:,3], add_parameters=params)
print(result.fit_report())
plt.plot(data[:,0],-data[:,3]+2,"b-o",label="data mean")
# plt.plot(data[:,0],data[:,1],label="data")
# plt.plot(data[:,0],data[:,2],label="data")
plt.plot(data[:,0],-result.best_fit+2,"r-",linewidth=2.,label="fit")
# plt.plot(data[:,0],result.init_fit,label="init")
plt.xlabel("time (ns)")
plt.ylabel("polarization transfer (arb. u.)")
plt.legend(loc=1)
# plt.savefig("pol20_24repetition_pol.pdf")
# plt.savefig("pol20_24repetition_pol.png")
plt.show()
savedata=[[data[ii,0],-data[ii,3]+2,-result.best_fit[ii]+2] for ii in range(len(data[:,0]))]
np.savetxt("pol_data_fit.csv",savedata)
# print(result.params)
print(result.params)
def plot_roc(y_test, y_pred, label=''):
"""Compute ROC curve and ROC area"""
fpr, tpr, _ = roc_curve(y_test, y_pred)
roc_auc = auc(fpr, tpr)
# Plot of a ROC curve for a specific class
plt.figure()
plt.plot(fpr, tpr, label='ROC curve (area = %0.2f)' % roc_auc)
plt.plot([0, 1], [0, 1], 'k--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic' + label)
plt.legend(loc="lower right")
plt.show()
def plot_confusion_matrix(cm, plot_title, filename, genres=None):
if not genres:
genres = GENRES
pylab.clf()
pylab.matshow(cm, fignum=False, cmap='Blues', vmin=0, vmax=100.0)
axes = pylab.axes()
axes.set_xticks(range(len(genres)))
axes.set_xticklabels(genres, rotation=45)
axes.set_yticks(range(len(genres)))
axes.set_yticklabels(genres)
axes.xaxis.set_ticks_position("bottom")
pylab.title(plot_title, fontsize=14)
pylab.colorbar()
pylab.xlabel('Predicted class', fontsize=12)
pylab.ylabel('Correct class', fontsize=12)
pylab.grid(False)
#pylab.show()
pylab.savefig(os.path.join(PLOTS_DIR, "cm_%s.eps" % filename), bbox_inches="tight")