def draw_bboxes(vis, bboxes, texts=None, ellipse=False, colored=True):
if not len(bboxes):
return vis
if not colored:
cols = np.tile([240,240,240], [len(bboxes), 1])
else:
N = 20
cwheel = colormap(np.linspace(0, 1, N))
cols = np.vstack([cwheel[idx % N] for idx, _ in enumerate(bboxes)])
texts = [None] * len(bboxes) if texts is None else texts
for col, b, t in zip(cols, bboxes, texts):
if ellipse:
cv2.ellipse(vis, ((b[0]+b[2])/2, (b[1]+b[3])/2), ((b[2]-b[0])/2, (b[3]-b[1])/2), 0, 0, 360,
color=tuple(col), thickness=1)
else:
cv2.rectangle(vis, (b[0], b[1]), (b[2], b[3]), tuple(col), 2)
if t:
annotate_bbox(vis, b, title=t)
return vis
python类linspace()的实例源码
def optimize_training_parameters(self, n):
# data
from_timestamp = self.min_timestamp
to_timestamp = self.min_timestamp + datetime.timedelta(days=365) + datetime.timedelta(hours=1)
train_timestamps, train_values = self.load_monitor_data(from_timestamp, to_timestamp, "1")
train_data = np.array(train_values)[:, 0:5]
# parameters
nu = np.linspace(start=1e-5, stop=1e-2, num=n)
gamma = np.linspace(start=1e-6, stop=1e-3, num=n)
opt_diff = 1.0
opt_nu = None
opt_gamma = None
fw = open("training_param.csv", "w")
fw.write("nu,gamma,diff\n")
for i in range(len(nu)):
for j in range(len(gamma)):
classifier = svm.OneClassSVM(kernel="rbf", nu=nu[i], gamma=gamma[j])
classifier.fit(train_data)
label = classifier.predict(train_data)
p = 1 - float(sum(label == 1.0)) / len(label)
diff = math.fabs(p-nu[i])
if diff < opt_diff:
opt_diff = diff
opt_nu = nu[i]
opt_gamma = gamma[j]
fw.write(",".join([str(nu[i]), str(gamma[j]), str(diff)]) + "\n")
fw.close()
return opt_nu, opt_gamma
def plot_sent_trajectories(sents, decode_plot):
font = {'family' : 'normal',
'size' : 14}
matplotlib.rc('font', **font)
i = 0
l = ["Portuguese","Catalan"]
axes = plt.gca()
#axes.set_xlim([xmin,xmax])
axes.set_ylim([-1,1])
for sent, enc in zip(sents, decode_plot):
if i==2: continue
i += 1
#times = np.arange(len(enc))
times = np.linspace(0,1,len(enc))
plt.plot(times, enc, label=l[i-1])
plt.title("Hidden Node Trajectories")
plt.xlabel('timestep')
plt.ylabel('trajectories')
plt.legend(loc='best')
plt.savefig("final_tests/cr_por_cat_hidden_cell_trajectories", bbox_inches="tight")
plt.close()
def draw_tracks(self, out, colored=False, color_type='unique', min_track_length=4, max_track_length=4):
"""
color_type: {age, unique}
"""
N = 20
# inds = self.confident_tracks(min_length=min_track_length)
# if not len(inds):
# return
# ids, pts = self.latest_ids[inds], self.latest_pts[inds]
# lengths = self.tm_.lengths[inds]
ids, pts, lengths = self.latest_ids, self.latest_pts, self.tm_.lengths
if color_type == 'unique':
cwheel = colormap(np.linspace(0, 1, N))
cols = np.vstack([cwheel[tid % N] for idx, tid in enumerate(ids)])
elif color_type == 'age':
cols = colormap(lengths)
else:
raise ValueError('Color type {:} undefined, use age or unique'.format(color_type))
if not colored:
cols = np.tile([0,240,0], [len(self.tm_.tracks), 1])
for col, pts in izip(cols.astype(np.int64), self.tm_.tracks.itervalues()):
cv2.polylines(out, [np.vstack(pts.items).astype(np.int32)[-max_track_length:]], False,
tuple(col), thickness=1)
tl, br = np.int32(pts.latest_item)-2, np.int32(pts.latest_item)+2
cv2.rectangle(out, (tl[0], tl[1]), (br[0], br[1]), tuple(col), -1)
def plot_interpolation(orderx,ordery):
s = PseudoSpectralDiscretization2D(orderx,XMIN,XMAX,
ordery,YMIN,YMAX)
Xc,Yc = s.get_x2d()
x = np.linspace(XMIN,XMAX,100)
y = np.linspace(YMIN,YMAX,100)
Xf,Yf = np.meshgrid(x,y,indexing='ij')
f_coarse = f(Xc,Yc)
f_interpolator = s.to_continuum(f_coarse)
f_num = f_interpolator(Xf,Yf)
plt.pcolor(Xf,Yf,f_num)
cb = plt.colorbar()
cb.set_label('interpolated function',fontsize=16)
plt.xlabel('x')
plt.ylabel('y')
for postfix in ['.png','.pdf']:
name = 'orthopoly_interpolated_function'+postfix
if USE_FIGS_DIR:
name = 'figs/' + name
plt.savefig(name,
bbox_inches='tight')
plt.clf()
def create_reference_image(size, x0=10., y0=-3., sigma_x=50., sigma_y=30., dtype='float64',
reverse_xaxis=False, correct_axes=True, sizey=None, **kwargs):
"""
Creates a reference image: a gaussian brightness with elliptical
"""
inc_cos = np.cos(0./180.*np.pi)
delta_x = 1.
x = (np.linspace(0., size - 1, size) - size / 2.) * delta_x
if sizey:
y = (np.linspace(0., sizey-1, sizey) - sizey/2.) * delta_x
else:
y = x.copy()
if reverse_xaxis:
xx, yy = np.meshgrid(-x, y/inc_cos)
elif correct_axes:
xx, yy = np.meshgrid(-x, -y/inc_cos)
else:
xx, yy = np.meshgrid(x, y/inc_cos)
image = np.exp(-(xx-x0)**2./sigma_x - (yy-y0)**2./sigma_y)
return image.astype(dtype)
def draw_laser_frustum(pose, zmin=0.0, zmax=10, fov=np.deg2rad(60)):
N = 30
curve = np.vstack([(
RigidTransform.from_rpyxyz(0, 0, rad, 0, 0, 0) * np.array([[zmax, 0, 0]]))
for rad in np.linspace(-fov/2, fov/2, N)])
curve_w = pose * curve
faces, edges = [], []
for cpt1, cpt2 in zip(curve_w[:-1], curve_w[1:]):
faces.extend([pose.translation, cpt1, cpt2])
edges.extend([cpt1, cpt2])
# Connect the last pt in the curve w/ the current pose,
# then connect the the first pt in the curve w/ the curr. pose
edges.extend([edges[-1], pose.translation])
edges.extend([edges[0], pose.translation])
faces = np.vstack(faces)
edges = np.vstack(edges)
return (faces, edges)
def recall_from_IoU(IoU, samples=500):
"""
plot recall_vs_IoU_threshold
"""
if not (isinstance(IoU, list) or IoU.ndim == 1):
raise ValueError('IoU needs to be a list or 1-D')
iou = np.float32(IoU)
# Plot intersection over union
IoU_thresholds = np.linspace(0.0, 1.0, samples)
recall = np.zeros_like(IoU_thresholds)
for idx, IoU_th in enumerate(IoU_thresholds):
tp, relevant = 0, 0
inds, = np.where(iou >= IoU_th)
recall[idx] = len(inds) * 1.0 / len(IoU)
return recall, IoU_thresholds
# =====================================================================
# Generic utility functions for object recognition
# ---------------------------------------------------------------------
def plotTimeMultiHistogram(parseTimes, hashTimes, compileTimes, filename): # times in ms
bins = np.linspace(0, 5000, 50)
data = np.vstack([parseTimes, hashTimes, compileTimes]).T
fig, ax = plt.subplots()
plt.hist(data, bins, alpha=0.7, label=['parsing', 'hashing', 'compiling'], color=[parseColor, hashColor, compileColor])
plt.legend(loc='upper right')
plt.xlabel('time [ms]')
plt.ylabel('#files')
fig.savefig(filename)
fig, ax = plt.subplots()
boxplot_data = [[i/1000 for i in parseTimes], [i/1000 for i in hashTimes], [i/1000 for i in compileTimes]] # times to s
plt.boxplot(boxplot_data, 0, 'rs', 0, [5, 95])
plt.xlabel('time [s]')
plt.yticks([1, 2, 3], ['parsing', 'hashing', 'compiling'])
#lgd = ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) # legend on the right
fig.savefig(filename[:-4] + '_boxplots' + GRAPH_EXTENSION)
def initwithsize(self, curshape, dim):
# DIM-dependent initialization
if self.dim != dim:
if self.zerox:
self.xopt = zeros(dim)
else:
self.xopt = compute_xopt(self.rseed, dim)
if hasattr(self, 'param') and self.param: # not self.param is None
tmp = self.param
else:
tmp = self.condition
self.scales = tmp ** linspace(0, 1, dim)
# DIM- and POPSI-dependent initialisations of DIM*POPSI matrices
if self.lastshape != curshape:
self.dim = dim
self.lastshape = curshape
self.arrxopt = resize(self.xopt, curshape)
def initwithsize(self, curshape, dim):
# DIM-dependent initialisation
if self.dim != dim:
if self.zerox:
self.xopt = zeros(dim)
else:
self.xopt = compute_xopt(self.rseed, dim)
self.scales = (self.condition ** .5) ** linspace(0, 1, dim)
# DIM- and POPSI-dependent initialisations of DIM*POPSI matrices
if self.lastshape != curshape:
self.dim = dim
self.lastshape = curshape
self.arrxopt = resize(self.xopt, curshape)
self.arrscales = resize(self.scales, curshape)
self.arrexpo = resize(self.beta * linspace(0, 1, dim), curshape)
def initwithsize(self, curshape, dim):
# DIM-dependent initialization
if self.dim != dim:
if self.zerox:
self.xopt = zeros(dim)
else:
self.xopt = compute_xopt(self.rseed, dim)
self.xopt[:min(dim, self.maxindex):2] = abs(self.xopt[:min(dim, self.maxindex):2])
self.scales = (self.condition ** .5) ** linspace(0, 1, dim)
# DIM- and POPSI-dependent initialisations of DIM*POPSI matrices
if self.lastshape != curshape:
self.dim = dim
self.lastshape = curshape
self.arrxopt = resize(self.xopt, curshape)
self.arrscales = resize(self.scales, curshape)
def initwithsize(self, curshape, dim):
# DIM-dependent initialization
if self.dim != dim:
if self.zerox:
self.xopt = zeros(dim)
else:
self.xopt = compute_xopt(self.rseed, dim)
self.rotation = compute_rotation(self.rseed + 1e6, dim)
self.scales = (self.condition ** .5) ** linspace(0, 1, dim)
self.linearTF = dot(compute_rotation(self.rseed, dim), diag(self.scales))
# decouple scaling from function definition
self.linearTF = dot(self.linearTF, self.rotation)
# DIM- and POPSI-dependent initialisations of DIM*POPSI matrices
if self.lastshape != curshape:
self.dim = dim
self.lastshape = curshape
self.arrxopt = resize(self.xopt, curshape)
def initwithsize(self, curshape, dim):
# DIM-dependent initialization
if self.dim != dim:
if self.zerox:
self.xopt = zeros(dim)
else:
self.xopt = compute_xopt(self.rseed, dim)
self.rotation = compute_rotation(self.rseed + 1e6, dim)
self.scales = (self.condition ** .5) ** linspace(0, 1, dim)
self.linearTF = dot(compute_rotation(self.rseed, dim), diag(self.scales))
self.linearTF = dot(self.linearTF, self.rotation)
# DIM- and POPSI-dependent initialisations of DIM*POPSI matrices
if self.lastshape != curshape:
self.dim = dim
self.lastshape = curshape
self.arrxopt = resize(self.xopt, curshape)
def initwithsize(self, curshape, dim):
# DIM-dependent initialization
if self.dim != dim:
if self.zerox:
self.xopt = zeros(dim)
else:
self.xopt = compute_xopt(self.rseed, dim)
self.rotation = compute_rotation(self.rseed + 1e6, dim)
self.scales = (self.condition ** .5) ** linspace(0, 1, dim)
self.linearTF = dot(compute_rotation(self.rseed, dim), diag(self.scales))
# decouple scaling from function definition
self.linearTF = dot(self.linearTF, self.rotation)
# DIM- and POPSI-dependent initialisations of DIM*POPSI matrices
if self.lastshape != curshape:
self.dim = dim
self.lastshape = curshape
self.arrxopt = resize(self.xopt, curshape)
self.arrexpo = resize(self.beta * linspace(0, 1, dim), curshape)
def initwithsize(self, curshape, dim):
# DIM-dependent initialization
if self.dim != dim:
if self.zerox:
self.xopt = zeros(dim)
else:
self.xopt = compute_xopt(self.rseed, dim)
self.rotation = compute_rotation(self.rseed + 1e6, dim)
self.scales = (self.condition ** .5) ** linspace(0, 1 , dim)
self.linearTF = dot(compute_rotation(self.rseed, dim), diag(self.scales))
# DIM- and POPSI-dependent initialisations of DIM*POPSI matrices
if self.lastshape != curshape:
self.dim = dim
self.lastshape = curshape
self.arrxopt = resize(self.xopt, curshape)
self.arrexpo = resize(self.beta * linspace(0, 1, dim), curshape)
def initwithsize(self, curshape, dim):
# DIM-dependent initialization
if self.dim != dim:
if self.zerox:
self.xopt = zeros(dim)
else:
self.xopt = 0.5 * sign(unif(dim, self.rseed) - 0.5) * 4.2096874633
self.scales = (self.condition ** .5) ** np.linspace(0, 1, dim)
# DIM- and POPSI-dependent initialisations of DIM*POPSI matrices
if self.lastshape != curshape:
self.dim = dim
self.lastshape = curshape
self.arrxopt = resize(2 * np.abs(self.xopt), curshape)
self.arrscales = resize(self.scales, curshape)
self.arrsigns = resize(sign(self.xopt), curshape)
def initwithsize(self, curshape, dim):
# DIM-dependent initialization
if self.dim != dim:
if self.zerox:
self.xopt = zeros(dim)
else:
self.xopt = compute_xopt(self.rseed, dim)
self.rotation = compute_rotation(self.rseed + 1e6, dim)
self.scales = (self.condition ** .5) ** linspace(0, 1, dim)
self.linearTF = dot(compute_rotation(self.rseed, dim), diag(self.scales))
# decouple scaling from function definition
self.linearTF = dot(self.linearTF, self.rotation)
# DIM- and POPSI-dependent initialisations of DIM*POPSI matrices
if self.lastshape != curshape:
self.dim = dim
self.lastshape = curshape
self.arrxopt = resize(self.xopt, curshape)
def initwithsize(self, curshape, dim):
# DIM-dependent initialization
if self.dim != dim:
if self.zerox:
self.xopt = zeros(dim)
else:
self.xopt = .5 * self._mu1 * sign(gauss(dim, self.rseed))
self.rotation = compute_rotation(self.rseed + 1e6, dim)
self.scales = (self.condition ** .5) ** linspace(0, 1, dim)
self.linearTF = dot(compute_rotation(self.rseed, dim), diag(self.scales))
# decouple scaling from function definition
self.linearTF = dot(self.linearTF, self.rotation)
# DIM- and POPSI-dependent initialisations of DIM*POPSI matrices
if self.lastshape != curshape:
self.dim = dim
self.lastshape = curshape
# self.arrxopt = resize(self.xopt, curshape)
self.arrscales = resize(2. * sign(self.xopt), curshape) # makes up for xopt
def _set_clock_data(self, dim, data, start, end, step, nsteps):
if data is not None:
data_dims = getattr(data, 'dims', None)
if data_dims is not None and data_dims != (dim,):
raise ValueError("expected dimension %r for clock coordinate"
"but found %r" % (dim, data_dims))
return data
args = {'step': step, 'nsteps': nsteps, 'end': end}
provided_args = {k for k, v in args.items() if v is not None}
if provided_args == {'nsteps', 'end', 'step'}:
if end - start == nsteps * step:
provided_args = {'nsteps', 'end'}
if provided_args == {'nsteps', 'end'}:
data = np.linspace(start, end, nsteps + 1)
elif provided_args == {'step', 'nsteps'}:
data = np.arange(start, start + (nsteps + 1) * step, step)
elif provided_args == {'step', 'end'}:
data = np.arange(start, end + step, step)
else:
raise ValueError("Invalid combination of nsteps (%s), step (%s) "
"and end (%s)" % (nsteps, step, end))
return data
def get_interv_table(model,intrv=True):
n_batches=25
table_outputs=[]
d_vals=np.linspace(TINY,0.6,n_batches)
for name in model.cc.node_names:
outputs=[]
for d_val in d_vals:
do_dict={model.cc.node_dict[name].label_logit : d_val*np.ones((model.batch_size,1))}
outputs.append(model.sess.run(model.fake_labels,do_dict))
out=np.vstack(outputs)
table_outputs.append(out)
table=np.stack(table_outputs,axis=2)
np.mean(np.round(table),axis=0)
return table
#dT=pd.DataFrame(index=p_names, data=T, columns=do_names)
#T=np.mean(np.round(table),axis=0)
#table=get_interv_table(model)
def modeFilter(data, window=500, step=None, bins=None):
"""Filter based on histogram-based mode function"""
d1 = data.view(np.ndarray)
vals = []
l2 = int(window/2.)
if step is None:
step = l2
i = 0
while True:
if i > len(data)-step:
break
vals.append(mode(d1[i:i+window], bins))
i += step
chunks = [np.linspace(vals[0], vals[0], l2)]
for i in range(len(vals)-1):
chunks.append(np.linspace(vals[i], vals[i+1], step))
remain = len(data) - step*(len(vals)-1) - l2
chunks.append(np.linspace(vals[-1], vals[-1], remain))
d2 = np.hstack(chunks)
if (hasattr(data, 'implements') and data.implements('MetaArray')):
return MetaArray(d2, info=data.infoCopy())
return d2
def analyseparamsneighbourhood(svdata, params, includejumps, randomstate):
parameterndarray = transformparameterndarray(np.array(params), includejumps)
offsets = np.linspace(-.5, .5, 10)
for dimension in range(params.dimensioncount):
xs, ys = [], []
parametername = params.getdimensionname(dimension)
print('Perturbing %s...' % parametername)
for offset in offsets:
newparameterndarray = np.copy(parameterndarray)
newparameterndarray[dimension] += offset
xs.append(inversetransformparameterndarray(newparameterndarray, includejumps)[dimension])
y = runsvljparticlefilter(svdata, sv.Params(*inversetransformparameterndarray(newparameterndarray, includejumps)), randomstate).stochfilter.loglikelihood
ys.append(y)
fig = plt.figure()
plot = fig.add_subplot(111)
plot.plot(xs, ys)
plot.axvline(x=inversetransformparameterndarray(parameterndarray, includejumps)[dimension], color='red')
plot.set_xlabel(parametername)
plot.set_ylabel('loglikelihood')
plt.show()
def plot2d_simplex(simplex, ind):
fig_dir = "./"
plt.cla()
n = 1000
x1 = np.linspace(-256, 1024, n)
x2 = np.linspace(-256, 1024, n)
X, Y = np.meshgrid(x1, x2)
Z = np.sqrt(X ** 2 + Y ** 2)
plt.contour(X, Y, Z, levels=list(np.arange(0, 1200, 10)))
plt.gca().set_aspect("equal")
plt.xlim((-256, 768))
plt.ylim((-256, 768))
plt.plot([simplex[0].x[0], simplex[1].x[0]],
[simplex[0].x[1], simplex[1].x[1]], color="#000000")
plt.plot([simplex[1].x[0], simplex[2].x[0]],
[simplex[1].x[1], simplex[2].x[1]], color="#000000")
plt.plot([simplex[2].x[0], simplex[0].x[0]],
[simplex[2].x[1], simplex[0].x[1]], color="#000000")
plt.savefig(os.path.join(fig_dir, "{:03d}.png".format(ind)))
def graph(self, ctx, lower_limit : int, upper_limit : int, *, equation : str):
'''WIP'''
filename = "data/temp/graph.png"
try:
equation = self.string_to_equation(equation)
except SyntaxError as e:
await self.bot.embed_reply(":no_entry: Error: {}".format(e))
return
x = numpy.linspace(lower_limit, upper_limit, 250)
try:
y = numexpr.evaluate(equation)
except Exception as e:
await self.bot.reply(py_code_block.format("{}: {}".format(type(e).__name__, e)))
return
try:
matplotlib.pyplot.plot(x, y)
except ValueError as e:
await self.bot.embed_reply(":no_entry: Error: {}".format(e))
return
matplotlib.pyplot.savefig(filename)
matplotlib.pyplot.clf()
await self.bot.send_file(destination = ctx.message.channel, fp = filename, content = ctx.message.author.display_name + ':')
# TODO: Send as embed?
def getAUC(self,test_tasks):
mean_tpr = 0.0
mean_fpr = np.linspace(0, 1, 100)
for t in range(self.n_tasks):
X_t, Y_t = self.extractTaskData(self.train_tasks,t)
X_test_t, Y_test_t = self.extractTaskData(test_tasks, t)
overallKernel = self.constructKernelFunction(t)
self.classifiers[t] = SVC(C=self.C, kernel=overallKernel, probability=True, max_iter=self.max_iter_internal, tol=self.tolerance)
probas_ = self.classifiers[t].fit(X_t, Y_t).predict_proba(X_test_t)
fpr, tpr, thresholds = roc_curve(Y_test_t, probas_[:, 1])
mean_tpr += interp(mean_fpr, fpr, tpr)
mean_tpr[0] = 0.0
mean_tpr /= self.n_tasks
mean_tpr[-1] = 1.0
mean_auc = auc(mean_fpr, mean_tpr)
return mean_auc, mean_fpr, mean_tpr
def x_frame1D(X, plot_limits=None, resolution=None):
"""
Internal helper function for making plots, returns a set of input values to plot as well as lower and upper limits
"""
assert X.shape[1] == 1, \
'x_frame1D is defined for one-dimensional inputs'
if plot_limits is None:
(xmin, xmax) = (X.min(0), X.max(0))
(xmin, xmax) = (xmin - 0.2 * (xmax - xmin), xmax + 0.2 * (xmax
- xmin))
elif len(plot_limits) == 2:
(xmin, xmax) = plot_limits
else:
raise ValueError, 'Bad limits for plotting'
Xnew = np.linspace(xmin, xmax, resolution or 200)[:, None]
return (Xnew, xmin, xmax)
def display_results_figure(results, METRIC):
import pylab as pb
color = iter(pb.cm.rainbow(np.linspace(0, 1, len(results))))
plots = []
for method in results.keys():
x = []
y = []
for train_perc in sorted(results[method].keys()):
x.append(train_perc)
y.append(results[method][train_perc][0])
c = next(color)
(pi, ) = pb.plot(x, y, color=c)
plots.append(pi)
from matplotlib.font_manager import FontProperties
fontP = FontProperties()
fontP.set_size('small')
pb.legend(plots, map(method_name_mapper, results.keys()),
prop=fontP, bbox_to_anchor=(0.6, .65))
pb.xlabel('#Tweets from target rumour for training')
pb.ylabel('Accuracy')
pb.title(METRIC.__name__)
pb.savefig('incrementing_training_size.png')
def draw_hill(x,y):
a = np.linspace(-20,20,100)
print(a)
b = np.linspace(-20,20,100)
x = np.array(x)
y = np.array(y)
allSSE = np.zeros(shape=(len(a),len(b)))
for ai in range(0,len(a)):
for bi in range(0,len(b)):
a0 = a[ai]
b0 = b[bi]
SSE = calc_loss(a=a0,b=b0,x=x,y=y)
allSSE[ai][bi] = SSE
a,b = np.meshgrid(a, b)
return [a,b,allSSE]
def draw_hill(x,y):
a = np.linspace(-20,20,100)
print(a)
b = np.linspace(-20,20,100)
x = np.array(x)
y = np.array(y)
allSSE = np.zeros(shape=(len(a),len(b)))
for ai in range(0,len(a)):
for bi in range(0,len(b)):
a0 = a[ai]
b0 = b[bi]
SSE = calc_loss(a=a0,b=b0,x=x,y=y)
allSSE[ai][bi] = SSE
a,b = np.meshgrid(a, b)
return [a,b,allSSE]
# ????