本文搜集整理了关于python中numpy single方法/函数的使用示例。
Namespace/Package: numpy
Method/Function: single
导入包: numpy
每个示例代码都附有代码来源和完整的源代码,希望对您的程序开发有帮助。
示例1
def get_2state_gaussian_seq(lens,dims=2,means1=[2,2,2,2],means2=[5,5,5,5],vars1=[1,1,1,1],vars2=[1,1,1,1],anom_prob=1.0): seqs = co.matrix(0.0, (dims, lens)) lbls = co.matrix(0, (1,lens)) marker = 0 # generate first state sequence for d in range(dims): seqs[d,:] = co.normal(1,lens)*vars1[d] + means1[d] prob = np.random.uniform() if prob<anom_prob: # add second state blocks while (True): max_block_len = 0.6*lens min_block_len = 0.1*lens block_len = np.int(max_block_len*np.single(co.uniform(1))+3) block_start = np.int(lens*np.single(co.uniform(1))) if (block_len - (block_start+block_len-lens)-3>min_block_len): break block_len = min(block_len,block_len - (block_start+block_len-lens)-3) lbls[block_start:block_start+block_len-1] = 1 marker = 1 for d in range(dims): #print block_len seqs[d,block_start:block_start+block_len-1] = co.normal(1,block_len-1)*vars2[d] + means2[d] return (seqs, lbls, marker)
示例2
def calc_updates(valid_labels, pred_label, label):
num_classes = len(valid_labels)
pred_flags = [set(np.where((pred_label == _).ravel())[0]) for _ in valid_labels]
class_flags = [set(np.where((label == _).ravel())[0]) for _ in valid_labels]
conf = [len(class_flags[j].intersection(pred_flags[k])) for j in xrange(num_classes) for k in xrange(num_classes)]
pixel = [len(class_flags[j]) for j in xrange(num_classes)]
return np.single(conf).reshape((num_classes, num_classes)), np.single(pixel)
示例3
def roc_curve(predicted, actual, cls):
si = np.argsort(-predicted)
tp = np.cumsum(np.single(actual[si]==cls))
fp = np.cumsum(np.single(actual[si]!=cls))
tp = tp/np.sum(actual==cls)
fp = fp/np.sum(actual!=cls)
tp = np.hstack((0.0, tp, 1.0))
fp = np.hstack((0.0, fp, 1.0))
return tp, fp
示例4
def quad_poly_patch_color_basis(patch):
h, w, c = patch.shape[0], patch.shape[1], patch.shape[2]
assert c == 3
basis = np.zeros((h, w, 10), dtype=np.single)
for i in range(h):
for j in range(w):
l, a, b = np.single(patch[i, j, 0]), np.single(patch[i, j, 1]), np.single(patch[i, j, 2])
basis[i, j, :] = [l * l, a * a, b * b, l * a, l * b, a * b, l, a, b, 1]
return basis
示例5
def get_lightness_equalization_curve_control_points(L):
h, w = L.shape[0], L.shape[1]
bins = 100
hist, bin_edges = np.histogram(L, bins, range=(0, 100), density=False)
hist = np.single(hist) / np.single(h * w)
cumsum_hist = np.cumsum(hist)
spline, x = get_cum_hist_BSpline_curve(cumsum_hist, 0.0, 100.0, bins)
# mpplot.plot(x,cumsum_hist)
# mpplot.plot(x, spline(x),'.-')
# mpplot.show()
return spline.get_coeffs()
示例6
def point_wise_add_scalar(A, scalar1=1, scalar2=1, OUT_BUFFER=None, gpu_ind=0): assert isinstance(gpu_ind,int) check_buffer(A) if OUT_BUFFER != None: check_buffer(OUT_BUFFER) OUT_BUFFER[1] = copy.deepcopy(A[1]) else: OUT_BUFFER = copy.deepcopy(A) _ntm_module.point_wise_add_scalar(A[0], np.single(scalar1), np.single(scalar2), OUT_BUFFER[0], gpu_ind)
示例7
def reverse_network_recur(deriv_above, layer_ind, LAYERS, WEIGHTS, OUTPUT, OUTPUT_PREV, PARTIALS, WEIGHT_DERIVS, keep_dims, scalar, abort_layer): # multiply all partials together L = LAYERS[layer_ind] N_ARGS = len(L['in_shape']) deriv_above_created = deriv_above is None if len(LAYERS[layer_ind]['out_shape']) > 1 and deriv_above is None: # skip image dim n_imgs = LAYERS[layer_ind]['out_shape'][0] deriv_above_shape = LAYERS[layer_ind]['out_shape'] + LAYERS[layer_ind]['out_shape'][1:] deriv_above = init_buffer(np.single(np.tile(np.eye(np.prod(LAYERS[layer_ind]['out_shape'][1:]))[np.newaxis], (n_imgs, 1, 1))).reshape(deriv_above_shape)) elif deriv_above is None: deriv_above_shape = LAYERS[layer_ind]['out_shape'] + LAYERS[layer_ind]['out_shape'] deriv_above = init_buffer(np.single(np.eye(np.prod(LAYERS[layer_ind]['out_shape'])).reshape(deriv_above_shape))) for arg in range(N_ARGS): src = L['in_source'][arg] if L['in_source'][arg] != -1: # don't compute gradients for user-supplied entries (Ex. images) # compute derivs args = build_forward_args(L, layer_ind, OUTPUT, OUTPUT_PREV, WEIGHTS) deriv_above_new = L['deriv_F'][arg](args, OUTPUT[layer_ind], deriv_above, additional_args=L['additional_deriv_args'][arg]) # input is a layer: if isinstance(src, int) and src != -1: # memory partials, stop here, add these partials to the correct weight derivs: if L['in_prev'][arg]: P = PARTIALS[src] N_ARGS2 = len(P['in_source']) for arg2 in range(N_ARGS2): p_layer_ind = P['in_source'][arg2] p_arg = P['in_arg'][arg2] p_partial = P['partial'][arg2] # multiply partials batched over the images, then sum the results: deriv_temp = mult_partials(deriv_above_new, p_partial, LAYERS[src]['out_shape'], keep_dims=keep_dims) WEIGHT_DERIVS[p_layer_ind][p_arg] = add_points_inc((WEIGHT_DERIVS[p_layer_ind][p_arg], deriv_temp), scalar=scalar) free_buffer(deriv_temp) # another layer (At this time step, go back to earlier layers) # [do not go back if this is the abort_layer where we stop backpropping] elif src != abort_layer: reverse_network_recur(deriv_above_new, src, LAYERS, WEIGHTS, OUTPUT, OUTPUT_PREV, PARTIALS, WEIGHT_DERIVS, keep_dims, scalar, abort_layer) # input is not a layer, end here else: WEIGHT_DERIVS[layer_ind][arg] = add_points_inc((WEIGHT_DERIVS[layer_ind][arg], deriv_above_new), scalar=scalar) free_buffer(deriv_above_new) if deriv_above_created: free_buffer(deriv_above) return WEIGHT_DERIVS
示例8
def get_central_pixel_grad_vector(batch_img, nb_hs):
nb_sz = 2 * nb_hs + 1
ch, h, w, num_imgs =
batch_img.shape[0], batch_img.shape[1], batch_img.shape[2], batch_img.shape[3]
ct_x, ct_y = w / 2, h / 2
# 2D gradient vector for each RGB (or LAB channel)
right, left = batch_img[:, ct_y, ct_x + 1, :], batch_img[:, ct_y, ct_x - 1, :]
top, bottom = batch_img[:, ct_y + 1, ct_x, :], batch_img[:, ct_y - 1, ct_x, :]
x_grad, y_grad = (right - left) / np.single(2.0), (top - bottom) / np.single(2.0)
return np.concatenate((x_grad, y_grad), axis=0)
示例9
def test_against_known_values(self):
R = fractions.Fraction
assert_equal(R(1075, 512),
R(*np.half(2.1).as_integer_ratio()))
assert_equal(R(-1075, 512),
R(*np.half(-2.1).as_integer_ratio()))
assert_equal(R(4404019, 2097152),
R(*np.single(2.1).as_integer_ratio()))
assert_equal(R(-4404019, 2097152),
R(*np.single(-2.1).as_integer_ratio()))
assert_equal(R(4728779608739021, 2251799813685248),
R(*np.double(2.1).as_integer_ratio()))
assert_equal(R(-4728779608739021, 2251799813685248),
R(*np.double(-2.1).as_integer_ratio()))
示例10
def get_scores(self, sol, idx, y=[]): y = np.array(y) if (y.size==0): y=np.array(self.y[idx]) (foo, T) = y.shape N = self.states F = self.dims scores = matrix(0.0, (1, T)) # this is the score of the complete example anom_score = sol.trans()*self.get_joint_feature_map(idx) # transition matrix A = self.get_transition_matrix(sol) # emission matrix without loss em = self.calc_emission_matrix(sol, idx, augment_loss=False, augment_prior=False); # store scores for each position of the sequence scores[0] = self.start_p[int(y[0,0])] + em[int(y[0,0]),0] for t in range(1,T): scores[t] = A[int(y[0,t-1]),int(y[0,t])] + em[int(y[0,t]),t] # transform for better interpretability if max(abs(scores))>10.0**(-15): scores = exp(-abs(4.0*scores/max(abs(scores)))) else: scores = matrix(0.0, (1,T)) return (float(np.single(anom_score)), scores)
示例11
def get_example_list(num, dims, signal, label, start, min_lens=600, max_lens=800):
(foo, LEN) = label.shape
min_genes = int(float(num)*0.15)
X = []
Y = []
phi = []
marker = []
cnt_genes = 0
cnt = 0
while (cnt<num):
lens = np.int(np.single(co.uniform(1, a=min_lens, b=max_lens)))
if (start+lens)>LEN:
print('Warning! End of genome. Could not add example.')
break
(exm, lbl, phi_i, isGene, end_pos) = get_example(signal, label, dims, start, start+lens)
# accept example, if it has the correct length
if (end_pos-start<=max_lens or (isGene==True and end_pos-start<800)):
X.append(exm)
Y.append(lbl)
phi.append(phi_i)
if isGene:
marker.append(0)
cnt_genes += 1
min_genes -= 1
else:
marker.append(1)
cnt += 1
start = end_pos
print('Number of examples {0}. {1} of them are genic.'.format(len(Y), cnt_genes))
return (X, Y, phi, marker, start)
示例12
def steer(self):
N = self.fixedCL.shape
# Obtain 2D view
SteeringGeneric.update_slices(self)
fixed2D, moving2D = self.get_slices()
fixedV, movingV = self.get_slice_axes()
F = SteeringGeneric.get_frame_matrix(self, fixedV, movingV)
# Perform 2D registration
scale, T2 = self.register_scale2d(fixed2D, moving2D)
print "S = ", scale
S = np.identity(3, np.single) * scale
T = F[:,0] * T2[0] + F[:,1] * T2[1]
C = np.array([N[0]/2, N[1]/2, N[2]/2], np.single)
T += C - np.dot(S,C)
T = np.single(T)
# Subtract identitiy from matrix to match convention for PolyAffineCL
for dim in range(3):
S[dim, dim] -= 1.0
# Return 3D transformation that will be folded into an existing polyaffine
return S, T
示例13
def _get_transformer_image():
scale, mean_, std_ = _get_scalemeanstd()
transformers = []
if scale > 0:
transformers.append(ts.ColorScale(np.single(scale)))
transformers.append(ts.ColorNormalize(mean_, std_))
return transformers
示例14
def add_points_inc(args, OUT_BUFFER=None, scalar=1, scalar0=1, gpu_ind=GPU_IND): t = time.time() A, B = args if OUT_BUFFER != None: check_buffer(OUT_BUFFER) OUT_BUFFER[1] = A[1] else: OUT_BUFFER = A _ntm_module3.add_points(A[0], B[0], np.single(scalar), np.single(scalar0), OUT_BUFFER[0], gpu_ind) if OUT_BUFFER[1] is None: OUT_BUFFER[1] = B[1] t_add[0] = time.time() - t return OUT_BUFFER
示例15
def test_floats_from_string(self, level=rlevel):
"""Ticket #640, floats from string"""
fsingle = np.single('1.234')
fdouble = np.double('1.234')
flongdouble = np.longdouble('1.234')
assert_almost_equal(fsingle, 1.234)
assert_almost_equal(fdouble, 1.234)
assert_almost_equal(flongdouble, 1.234)
示例16
def test_floating(self):
# Ticket #640, floats from string
fsingle = np.single('1.234')
fdouble = np.double('1.234')
flongdouble = np.longdouble('1.234')
assert_almost_equal(fsingle, 1.234)
assert_almost_equal(fdouble, 1.234)
assert_almost_equal(flongdouble, 1.234)
示例17
def get_lightness_detail_weighted_equalization_curve_control_points(L, sigma):
bins = 100
grad_mag = scipy.ndimage.filters.gaussian_gradient_magnitude(L, sigma)
hist, bin_edges = np.histogram(L, bins, range=(0, 100), weights=grad_mag)
hist = np.single(hist) / np.sum(grad_mag)
cumsum_hist = np.cumsum(hist)
spline, x = get_cum_hist_BSpline_curve(cumsum_hist, 0.0, 100.0, bins)
return spline.get_coeffs()
示例18
def test_floating_overflow(self):
""" Strings containing an unrepresentable float overflow """
fhalf = np.half('1e10000')
assert_equal(fhalf, np.inf)
fsingle = np.single('1e10000')
assert_equal(fsingle, np.inf)
fdouble = np.double('1e10000')
assert_equal(fdouble, np.inf)
flongdouble = assert_warns(RuntimeWarning, np.longdouble, '1e10000')
assert_equal(flongdouble, np.inf)
fhalf = np.half('-1e10000')
assert_equal(fhalf, -np.inf)
fsingle = np.single('-1e10000')
assert_equal(fsingle, -np.inf)
fdouble = np.double('-1e10000')
assert_equal(fdouble, -np.inf)
flongdouble = assert_warns(RuntimeWarning, np.longdouble, '-1e10000')
assert_equal(flongdouble, -np.inf)
示例19
def reverse_network_btt_recur(deriv_above, layer_ind, LAYERS, WEIGHTS, OUTPUT, WEIGHT_DERIVS, frame, keep_dims, scalar, abort_layer): # multiply all partials together L = LAYERS[layer_ind] N_ARGS = len(L['in_shape']) deriv_above_created = deriv_above is None if len(LAYERS[layer_ind]['out_shape']) > 1 and deriv_above is None: # skip image dim n_imgs = LAYERS[layer_ind]['out_shape'][0] deriv_above_shape = LAYERS[layer_ind]['out_shape'] + LAYERS[layer_ind]['out_shape'][1:] deriv_above = init_buffer(np.single(np.tile(np.eye(np.prod(LAYERS[layer_ind]['out_shape'][1:]))[np.newaxis], (n_imgs, 1, 1))).reshape(deriv_above_shape)) elif deriv_above is None: deriv_above_shape = LAYERS[layer_ind]['out_shape'] + LAYERS[layer_ind]['out_shape'] deriv_above = init_buffer(np.single(np.eye(np.prod(LAYERS[layer_ind]['out_shape'])).reshape(deriv_above_shape))) for arg in range(N_ARGS): src = L['in_source'][arg] if L['in_source'][arg] != -1: # don't compute gradients for user-supplied entries (Ex. images) # compute derivs args = build_forward_args(L, layer_ind, OUTPUT[frame], OUTPUT[frame-1], WEIGHTS) deriv_above_new = L['deriv_F'][arg](args, OUTPUT[frame][layer_ind], deriv_above, additional_args=L['additional_deriv_args'][arg]) # input is a layer: if isinstance(src, int) and src != -1: # memory partials--keep going back through the network...take step back in time... if L['in_prev'][arg]: if frame > 1: reverse_network_btt_recur(deriv_above_new, src, LAYERS, WEIGHTS, OUTPUT, WEIGHT_DERIVS, frame-1, keep_dims, scalar, abort_layer) # another layer (At this time step, go back to earlier layers) # [do not go back if this is the abort_layer where we stop backpropping] elif src != abort_layer: reverse_network_btt_recur(deriv_above_new, src, LAYERS, WEIGHTS, OUTPUT, WEIGHT_DERIVS, frame, keep_dims, scalar, abort_layer) # input is not a layer, end here else: WEIGHT_DERIVS[layer_ind][arg] = add_points_inc((WEIGHT_DERIVS[layer_ind][arg], deriv_above_new), scalar=scalar) free_buffer(deriv_above_new) if deriv_above_created: free_buffer(deriv_above) return WEIGHT_DERIVS
示例20
def leibnitz(k, n):
sum = 0.0
rev_sum = 0.0
single = numpy.single(0.0)
# 0 bis k
for i in range(0,k):
sum = sum + mround(pow(-1,i) / (2.0*i+1),n)
r = range(0,k)
list.reverse(r)
# umgekerte Reihenfolge
for i in r:
rev_sum = rev_sum + mround(pow(-1,i) / (2.0*i+1),n)
# single precision
for i in range(0,k):
single = single + numpy.single(pow(-1,i) / (2.0*i+1))
return (sum, rev_sum, single)
示例21
def argmax(self, sol, idx, add_loss=False, opt_type='linear'):
nd = self.feats
d = 0 # start of dimension in sol
val = -10.**10.
cls = -1 # best class
for c in range(self.num_classes):
foo = sol[d:d+nd].T.dot(self.X[:, idx])
# the argmax of the above function
# is equal to the argmax of the quadratic function
# foo = + 2*foo - normPsi
# since ||Psi(x_i,z)|| = ||phi(x_i)|| = y forall z
d += nd
if np.single(foo) > np.single(val):
val = foo
cls = c
if opt_type == 'quadratic':
normPsi = self.X[:, idx].T.dot(self.X[:, idx])
val = 2.*val - normPsi
psi_idx = self.get_joint_feature_map(idx, cls)
return val, cls, psi_idx
示例22
def point_wise_div_sqrt(args, OUT_BUFFER=None, clip=10, gpu_ind=GPU_IND): A, B = args if OUT_BUFFER != None: check_buffer(OUT_BUFFER) OUT_BUFFER[1] = A[1] else: OUT_BUFFER = A _ntm_module3.point_wise_div_sqrt(A[0], B[0], OUT_BUFFER[0], np.single(clip), gpu_ind) OUT_BUFFER[1] = B[1] return OUT_BUFFER
示例23
def spontaneus_amplitudes(alpha, beta1, beta2, epsilon):
"""
Spontaneous amplitude of fully expanded canonical model
Args:
alpha (float): :math:`\alpha` parameter of the canonical model
beta1 (float): :math:`\beta_1` parameter of the canonical model
beta2 (float): :math:`\beta_2` parameter of the canonical model
epsilon (float): :math:`\varepsilon` parameter of the canonical model
Returns:
:class:`numpy.ndarray`: Spontaneous amplitudes for the oscillator
"""
if beta2 == 0 and epsilon !=0:
epsilon = 0
eps = np.spacing(np.single(1))
# Find r* numerically
r = np.roots([float(epsilon*(beta2-beta1)),
0.0,
float(beta1-epsilon*alpha),
0.0,
float(alpha),
0.0])
# only unique real values
r = np.real(np.unique(r[np.abs(np.imag(r)) < eps]))
r = r[r >=0] # no negative amplitude
if beta2 > 0:
r = r[r < 1.0/np.sqrt(epsilon)] # r* below the asymptote only
def slope(r):
return alpha + 3*beta1*r**2 +
(5*epsilon*beta2*r**4-3*epsilon**2*beta2*r**6) /
((1-epsilon*r**2)**2)
# Take only stable r*
ind1 = slope(r) < 0
ind2a = slope(r) == 0
ind2b = slope(r-eps) < 0
ind2c = slope(r+eps) < 0
ind2 = np.logical_and(ind2a, np.logical_and(ind2b, ind2c))
r = r[np.logical_or(ind1, ind2)]
return sorted(r, reverse=True)
示例24
def get_local_context_color(img_ab, px, py, local_context_color_paras, res=None):
h, w, ch = img_ab.shape[0], img_ab.shape[1], img_ab.shape[2]
assert ch == 2
hf_sz, hist_bin_num =
local_context_color_paras['half_size'], local_context_color_paras['hist_bin_num']
xmin = px - hf_sz if (px - hf_sz) >= 0 else 0
xmax = px + hf_sz + 1 if (px + hf_sz + 1) < w else w
ymin = py - hf_sz if (py - hf_sz) >= 0 else 0
ymax = py + hf_sz + 1 if (py + hf_sz + 1) < h else h
region = img_ab[ymin:ymax, xmin:xmax, :]
h2, w2 = ymax - ymin, xmax - xmin
region = region.reshape((h2 * w2, 2))
hist_a, bin_edges_a = np.histogram(region[:, 0], hist_bin_num, range=(-128, 128))
hist_b, bin_edges_b = np.histogram(region[:, 1], hist_bin_num, range=(-128, 128))
hist_a = np.single(hist_a) / np.single(h2 * w2)
hist_b = np.single(hist_b) / np.single(h2 * w2)
# print 'hist,hist_sum',hist,np.sum(hist)
if res == None:
return np.concatenate((hist_a, hist_b))
else:
res[:hist_bin_num] = hist_a
res[hist_bin_num:(2 * hist_bin_num)] = hist_b
示例25
def argmax(self, sol, idx, add_loss=False):
nd = self.feats
mc = self.num_classes
d = 0 # start of dimension in sol
val = -10**10
cls = -1 # best choice so far
psi_idx = matrix(0.0, (nd*mc,1))
for c in range(self.num_classes):
psi = matrix(0.0, (nd*mc,1))
psi[nd*c:nd*(c+1)] = self.X[:,idx]
foo = 2.0 * sol.trans()*psi - psi.trans()*psi
# the argmax of the above function
# is equal to the argmax of the quadratic function
# foo = + 2*foo - normPsi
# since ||Psi(x_i,z)|| = ||phi(x_i)|| = y forall z
if (np.single(foo)>np.single(val)):
val = -sol.trans()*sol + foo
cls = c
psi_idx = matrix(sol, (nd*mc,1))
psi_idx[nd*c:nd*(c+1)] = self.X[:,idx]
return (val, cls, psi_idx)
示例26
def conv_block(filters, imgs, stride=1, max_el=3360688123):
t_start = time.time()
filters = np.single(filters); imgs = np.single(imgs)
assert filters.shape[1] == filters.shape[2]
assert imgs.shape[1] == imgs.shape[2]
assert imgs.shape[0] == filters.shape[0]
x_loc = 0
y_loc = 0
n_filters = filters.shape[3]
n_imgs = imgs.shape[3]
img_sz = imgs.shape[1]
filter_sz = filters.shape[1]
in_channels = filters.shape[0]
output_sz = len(range(0, img_sz - filter_sz + 1, stride))
filter_temp = filters.reshape((in_channels*filter_sz**2,n_filters)).T.reshape((n_filters,in_channels*filter_sz*filter_sz,1,1,1))
patches = np.zeros((1, in_channels*filter_sz*filter_sz,output_sz, output_sz, n_imgs),dtype='single')
for x in range(output_sz):
y_loc = 0
for y in range(output_sz):
patches[0,:,x,y] = imgs[:,x_loc:x_loc+filter_sz, y_loc:y_loc+filter_sz].reshape((1,in_channels*filter_sz*filter_sz,n_imgs))
y_loc += stride
x_loc += stride
total_el = (n_filters*in_channels*filter_sz*filter_sz*output_sz*output_sz*n_imgs)
n_groups = np.int(np.ceil(np.single(total_el) / max_el))
imgs_per_group = np.int(np.floor(128.0/n_groups))
#print n_groups
#print imgs_per_group
output = np.zeros((n_filters,output_sz,output_sz,n_imgs),dtype='single')
for group in range(n_groups):
p_t = patches[:,:,:,:,group*imgs_per_group:(group+1)*imgs_per_group]
output[:,:,:,group*imgs_per_group:(group+1)*imgs_per_group] = ne.evaluate('filter_temp*p_t').sum(1)
print time.time() - t_start
return output
示例27
def temp_parse(temp):
ntemp = []
errCount = 0
for val in temp:
if val.strip().upper() == "NAN":
cval = "0"
errCount += 1
else:
cval = val
try:
cval = single(cval)
except:
cval = -1
errCount += 1
ntemp += [cval]
return (ntemp, errCount)
示例28
def ImportData(output, cols, filterList=[], synList=[]):
""" Filter list is for adding lambda based filters, synList is for synthetic columns """
print "Importing Next Step..."
# ncols=lacpa_adddb(None,cols,header,'',False) # formatted and scaled
# cols=ncols
print "Filtering List"
keepPoints = numpy.array([True] * len(cols.values()[0])) # only
for (cFiltCol, cFiltFunc) in filterList:
keepPoints &= map(cFiltFunc, cols[cFiltCol])
print "Keeping - " + str((sum(keepPoints), len(keepPoints)))
keepPoints = [cValue for (cValue, isKept) in enumerate(keepPoints) if isKept]
for cKey in cols.keys():
cols[cKey] = numpy.array(cols[cKey])[keepPoints]
print " Adding columns"
for (cName, cData) in cols.items():
output.AddColumn(initCol(cName, cData, None))
print " Adding Triplets"
allTrips = getTriplets(cols.keys())
print allTrips
for (cName, cCols) in allTrips:
output.AddColumn(initCol3(cName, cols[cCols[0]], cols[cCols[1]], cols[cCols[2]], None))
print " Adding Tensors"
cols["NULL"] = 0 * single(cols.values()[0])
allTens = getTensors(cols.keys())
print allTens
for (cName, cCols) in allTens:
output.AddColumn(
initColTens(
cName,
cols[cCols[0]],
cols[cCols[1]],
cols[cCols[2]],
cols[cCols[3]],
cols[cCols[4]],
cols[cCols[5]],
cols[cCols[6]],
cols[cCols[7]],
cols[cCols[8]],
None,
)
)
print " Adding synthetic columns"
for (cName, cFunc) in synList:
output.AddColumn(initCol(cName, cFunc(cols), None))
return output
示例29
def __init__(self, weight_learning_rate=0.2, bias_learning_rate=0.2, weight_momentum=0.5, bias_momentum=0.5,
weight_decay=0.0, bias_decay=0.0):
self.weight_learning_rate = theano.shared(np.single(weight_learning_rate), 'lW')
self.bias_learning_rate = theano.shared(np.single(bias_learning_rate), 'lb')
self.weight_momentum = theano.shared(np.single(weight_momentum), 'mW')
self.bias_momentum = theano.shared(np.single(bias_momentum), 'mb')
self.weight_decay = theano.shared(np.single(weight_decay), 'rW')
self.bias_decay = theano.shared(np.single(bias_decay), 'rb')
示例30
def point_wise_mult_bcast2(A, B, scalar=1, OUT_BUFFER=None, gpu_ind=0): assert isinstance(gpu_ind,int) check_buffer(A) check_buffer(B) assert len(A[1]) > 2 assert len(B[1]) == 2 assert A[1][0] == B[1][0] assert A[1][1] == B[1][1] if OUT_BUFFER != None: check_buffer(OUT_BUFFER) OUT_BUFFER[1] = copy.deepcopy(A[1]) else: OUT_BUFFER = copy.deepcopy(A) _ntm_module.point_wise_mult_bcast2(A[0], A[1], B[0], np.single(scalar), OUT_BUFFER[0], gpu_ind)