python np linspace_Python numpy.linspace() 使用实例

本文详细介绍了Python中numpy.linspace函数的用法,包括如何创建等差数列,以及在不同场景下的应用,如参数优化、数据可视化、数值计算等。通过多个示例展示了linspace在机器学习、数据处理和图像处理中的实际操作。
摘要由CSDN通过智能技术生成

Example 1

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

Example 2

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()

Example 3

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()

Example 4

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)

Example 5

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)

Example 6

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

# ---------------------------------------------------------------------

Example 7

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

Example 8

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)

Example 9

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)

Example 10

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 ini

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值