本文整理汇总了Python中numpy.alen函数的典型用法代码示例。如果您正苦于以下问题:Python alen函数的具体用法?Python alen怎么用?Python alen使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了alen函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_data
def get_data(self, orig):
data = self.serializer.clipboard_data
data_len = np.alen(data)
orig_len = np.alen(orig)
if data_len > orig_len > 1:
data_len = orig_len
return data[0:data_len]
示例2: eccentricity
def eccentricity(data, exponent=1., metricpar={}, callback=None):
if data.ndim==1:
assert metricpar=={}, 'No optional parameter is allowed for a dissimilarity matrix.'
ds = squareform(data, force='tomatrix')
if exponent in (np.inf, 'Inf', 'inf'):
return ds.max(axis=0)
elif exponent==1.:
ds = np.power(ds, exponent)
return ds.sum(axis=0)/float(np.alen(ds))
else:
ds = np.power(ds, exponent)
return np.power(ds.sum(axis=0)/float(np.alen(ds)), 1./exponent)
else:
progress = progressreporter(callback)
N = np.alen(data)
ecc = np.empty(N)
if exponent in (np.inf, 'Inf', 'inf'):
for i in range(N):
ecc[i] = cdist(data[(i,),:], data, **metricpar).max()
progress((i+1)*100//N)
elif exponent==1.:
for i in range(N):
ecc[i] = cdist(data[(i,),:], data, **metricpar).sum()/float(N)
progress((i+1)*100//N)
else:
for i in range(N):
dsum = np.power(cdist(data[(i,),:], data, **metricpar),
exponent).sum()
ecc[i] = np.power(dsum/float(N), 1./exponent)
progress((i+1)*100//N)
return ecc
示例3: candlestick_trades
def candlestick_trades(samplet, lookback, t, px, sz):
#requires = ["CONTIGUOUS", "ALIGNED"]
lib = _load_candlestick_lib()
lib.c_candlestick.restype = None
lib.c_candlestick.argtypes = [np.ctypeslib.c_intp,
np.ctypeslib.ndpointer(float,
flags="aligned, contiguous"),
ctypes.c_double,
np.ctypeslib.c_intp,
np.ctypeslib.ndpointer(float, ndim=1,
flags="aligned, contiguous"),
np.ctypeslib.ndpointer(float, ndim=1,
flags="aligned, contiguous"),
np.ctypeslib.ndpointer(float, ndim=1,
flags="aligned, contiguous"),
np.ctypeslib.ndpointer(float, ndim=1,
flags="aligned, contiguous,"
"writeable")]
# samplet = np.require(samplet, float, requires)
# c = np.empty_like(a)
samplelen = np.alen(samplet)
datalen = np.alen(t)
res = np.empty(6*samplelen)
lib.c_candlestick(samplelen, samplet, lookback, datalen, t, px, sz, res)
return res
示例4: _do_problem
def _do_problem(self, problem, integrator, old_api=True, **integrator_params):
jac = None
if hasattr(problem, 'jac'):
jac = problem.jac
res = problem.res
ig = dae(integrator, res, jacfn=jac, old_api=old_api)
ig.set_options(old_api=old_api, **integrator_params)
z = empty((1+len(problem.stop_t),alen(problem.z0)), float)
zprime = empty((1+len(problem.stop_t),alen(problem.z0)), float)
ist = ig.init_step(0., problem.z0, problem.zprime0, z[0], zprime[0])
i=1
for time in problem.stop_t:
soln = ig.step(time, z[i], zprime[i])
if old_api:
flag, rt = soln
else:
flag = soln.flag
rt = soln.values.t
i += 1
if integrator == 'ida':
assert flag==0, (problem.info(), flag)
else:
assert flag > 0, (problem.info(), flag)
assert problem.verify(array(z), array(zprime), [0.]+problem.stop_t), \
(problem.info(),)
示例5: competence
def competence(stochastic):
"""
The competence function for TWalk.
"""
if stochastic.dtype in float_dtypes and np.alen(stochastic.value) > 4:
if np.alen(stochastic.value) >=10:
return 2
return 1
return 0
示例6: tableSum
def tableSum(self):
"""docstring for tableSum"""
self.fsum = 0
for i in xrange(numpy.alen(self.newx)):
for j in xrange(numpy.alen(self._angles)):
self.fsum += self.newx[i]*1.15*self._angles[j]*math.fabs(self.interpedgrid[i,j])
return self.fsum
示例7: create_binary
def create_binary(filename, num, outfile, options):
"""Create patterned binary data with the first 7 characters of the filename
interleaved with a byte ramp, e.g. A128 \x00A128 \x01A128 \x02 etc.
"""
root, _ = outfile.split(".")
prefix = ("%s " % root)[0:8]
a = np.fromstring(prefix, dtype=np.uint8)
b = np.tile(a, (num / np.alen(a)) + 1)[0:num]
b[7::8] = np.arange(np.alen(b) / 8, dtype=np.uint8)
with open(filename, "wb") as fh:
fh.write(b.tostring())
示例8: add_xexboot_header
def add_xexboot_header(bytes, bootcode=None, title="DEMO", author="an atari user"):
sec_size = 128
xex_size = len(bytes)
num_sectors = (xex_size + sec_size - 1) / sec_size
padded_size = num_sectors * sec_size
if xex_size < padded_size:
bytes = np.append(bytes, np.zeros([padded_size - xex_size], dtype=np.uint8))
paragraphs = padded_size / 16
if bootcode is None:
bootcode = np.fromstring(xexboot_header, dtype=np.uint8)
else:
# don't insert title or author in user supplied bootcode; would have to
# assume that the user supplied everything desired in their own code!
title = ""
author = ""
bootsize = np.alen(bootcode)
v = bootcode[9:11].view(dtype="<u2")
v[0] = xex_size
bootsectors = np.zeros([384], dtype=np.uint8)
bootsectors[0:bootsize] = bootcode
insert_string(bootsectors, 268, title, 0b11000000)
insert_string(bootsectors, 308, author, 0b01000000)
image = np.append(bootsectors, bytes)
return image
示例9: classify
def classify(data, trueclass, traindata, final_set,a):
X=np.vstack(data[traindata[:,1],:])
#np.savetxt("parkinsons/foo.csv",x, fmt='%0.5f',delimiter=",")
b=[]
b.append(traindata[:,1])
C = np.searchsorted(a, b)
D = np.delete(np.arange(np.alen(a)), C)
D= np.array(D)
D=D.reshape(D.size,-1)
true_labels = np.ravel(np.vstack(trueclass[D[:,0],0]))
test_data = np.vstack(data[D[:,0],:])
#print test_data.shape
#np.savetxt("parkinsons/foo.csv",test_data, fmt='%0.6s')
y=np.ravel(np.vstack(traindata[:,0]))
clf=svm.SVC(kernel='linear')
clf.fit(X,y)
labels=clf.predict(test_data) #predicting true labels for the remaining rows
predicted_labels = labels.reshape(labels.size,-1)
np.savetxt("parkinsons/foo%d.csv"%final_set, np.concatenate((test_data, predicted_labels,np.vstack(trueclass[D[:,0],0])), axis=1),fmt='%0.5f',delimiter=",")
print true_labels
print labels
misclassify_rate = 1-accuracy_score(true_labels,labels)
print "Misclassification rate = %f" %misclassify_rate
return misclassify_rate
示例10: distance_to_measure
def distance_to_measure(data, k, metricpar={}, callback=None):
r'''.. math::
\mathit{distance\_to\_measure}(x) = \sqrt{\frac 1k\sum^k_{j=1}d(x,\nu_j(x))^2},
where :math:`\nu_1(x),\ldots,\nu_k(x)` are the :math:`k` nearest neighbors of :math:`x` in the data set. Again, the first nearest neighbor is :math:`x` itself with distance 0.
Reference: [R4]_.
'''
if data.ndim==1:
assert metricpar=={}, ('No optional parameter is allowed for a '
'dissimilarity matrix.')
# dm data
ds = squareform(data, force='tomatrix')
N = np.alen(ds)
r = np.empty(N)
for i in range(N):
s = np.sort(ds[i,:])
assert s[0]==0.
d = s[1:k]
r[i] = np.sqrt((d*d).sum()/float(k))
return r
else:
# vector data
if metricpar=={} or metricpar['metric']=='euclidean':
from scipy.spatial import cKDTree
T = cKDTree(data)
d, j = T.query(data, k+1)
d = d[:,1:k]
return np.sqrt((d*d).sum(axis=1)/k)
else:
print(kwargs)
raise ValueError('Not implemented')
示例11: kNN_distance
def kNN_distance(data, k, metricpar={}, callback=None):
r'''The distance to the :math:`k`-th nearest neighbor as an (inverse) measure of density.
Note how the number of nearest neighbors is understood: :math:`k=1`, the first neighbor, makes no sense for a filter function since the first nearest neighbor of a data point is always the point itself, and hence this filter function is constantly zero. The parameter :math:`k=2` measures the distance from :math:`x_i` to the nearest data point other than :math:`x_i` itself.
'''
if data.ndim==1:
assert metricpar=={}, ('No optional parameter is allowed for a '
'dissimilarity matrix.')
# dm data
ds = squareform(data, force='tomatrix')
N = np.alen(ds)
r = np.empty(N)
for i in range(N):
s = np.sort(ds[i,:])
assert s[0]==0.
r[i] = s[k]
return r
else:
# vector data
if metricpar=={} or metricpar['metric']=='euclidean':
from scipy.spatial import cKDTree
T = cKDTree(data)
d, j = T.query(data, k+1)
return d[:,k]
else:
print(metricpar)
raise ValueError('Not implemented')
示例12: availability
def availability(self):
availability={}
for key in self.magnet_sets:
availability[key]=range(np.alen(self.magnet_sets[key]))
return availability
示例13: testLBP
def testLBP (format, formatMask, path, output) :
dataset = pd.read_csv(path)
idxCls = dataset['idx']
# cnts = dataset['Cnt']
fnList = dataset['path']
# out = open(output, 'w')
lbps = list(map(lambda x: local_binary_pattern(cv2.bitwise_and(imread(format.format(x)),imread(formatMask.format(x))), lbpP, lbpR, lbpMethod), fnList))
histograms = list(map(lambda x: np.histogram(x, bins=range(int(np.max(lbps)) + 1))[0], lbps))
distances = prw.pairwise_distances(histograms, metric='l1')
np.fill_diagonal(distances, math.inf)
guessedClasses = np.apply_along_axis(lambda x: np.argmin(x), 1, distances)
scores = np.apply_along_axis(lambda x: np.min(x), 1, distances)
correct = list(map(lambda i: idxCls[guessedClasses[i]] == idxCls[i], range(0, np.alen(idxCls))))
# out.write(str(np.average(correct)))
# fpr, tpr, thresholds = roc_curve(correct, scores, pos_label=1)
# pyplot.plot(tpr, fpr)
# pyplot.show()
with open(output + 'lbp_distances.csv', 'w', newline='') as fp:
a = csv.writer(fp, delimiter=',')
a.writerows(distances)
with open(output + 'lbp_guessedClasses.csv', 'w', newline='') as fp:
a = csv.writer(fp, delimiter=',')
a.writerow(guessedClasses)
with open(output + 'lbp_correct.csv', 'w', newline='') as fp:
a = csv.writer(fp, delimiter=',')
a.writerow(correct)
with open(output + 'lbp_real.csv', 'w', newline='') as fp:
a = csv.writer(fp, delimiter=',')
a.writerow(idxCls)
示例14: fit_model
def fit_model(self):
if self.similarity_matrix is None:
self._init_similarity_matrix()
self.means = []
for i in xrange(self.dataset.n_items):
i_ = self.item_user_matrix[i][self.item_user_matrix[i] > 0]
self.means.append(np.mean(i_) if not np.alen(i_) == 0 else 0)
示例15: recall_gain
def recall_gain(tp, fn, fp, tn):
"""Calculates Recall Gain from the contingency table
This function calculates Recall Gain from the entries of the contingency
table: number of true positives (TP), false negatives (FN), false positives
(FP), and true negatives (TN). More information on Precision-Recall-Gain
curves and how to cite this work is available at
http://www.cs.bris.ac.uk/~flach/PRGcurves/.
Args:
tp (float) or ([float]): True Positives
fn (float) or ([float]): False Negatives
fp (float) or ([float]): False Positives
tn (float) or ([float]): True Negatives
Returns:
(float) or ([float])
"""
n_pos = tp + fn
n_neg = fp + tn
with np.errstate(divide='ignore', invalid='ignore'):
rg = 1. - (n_pos/n_neg) * (fn/tp)
if np.alen(rg) > 1:
rg[tn + fn == 0] = 1
elif tn + fn == 0:
rg = 1
return rg