本文整理汇总了Python中RandomArray类的典型用法代码示例。如果您正苦于以下问题:Python RandomArray类的具体用法?Python RandomArray怎么用?Python RandomArray使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了RandomArray类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: randomArray
def randomArray(shape, seed=None, range=(0, 1), type=Float):
"""Utility to generate a Numeric array full of pseudorandom numbers in the given range.
This will attempt to use the RandomArray module, but fall back on using the standard
random module in a loop.
"""
global globalSeed
if not seed:
if not globalSeed:
globalSeed = int(time.time())
seed = globalSeed
# Keep our global seed mixed up enough that many requests for
# random arrays consecutively still gives random-looking output.
globalSeed = (globalSeed + random.randint(1, 0xFFFFF)) & 0x7FFFFFF
try:
import RandomArray
RandomArray.seed(seed + 1, seed + 1)
return (RandomArray.random(shape) * (range[1] - range[0]) + range[0]).astype(type)
except ImportError:
random.seed(seed)
a = zeros(multiply.reduce(shape), Float)
for i in xrange(a.shape[0]):
a[i] = random.random() * (range[1] - range[0]) + range[0]
return reshape(a, shape).astype(type)
示例2: random_tree
def random_tree(labels):
"""
Given a list of labels, create a list of leaf nodes, and then one
by one pop them off, randomly grafting them on to the growing tree.
Return the root node.
"""
assert len(labels) > 2
import RandomArray; RandomArray.seed()
leaves = []
for label in labels:
leaves.append(Fnode(istip=1, label=label))
leaf_indices = list(RandomArray.permutation(len(leaves)))
joined = [leaves[leaf_indices.pop()]]
remaining = leaf_indices
while remaining:
i = RandomArray.randint(0, len(joined)-1)
c1 = joined[i]
if c1.back:
n = c1.bisect()
else:
n = InternalNode()
n.add_child(c1)
c = leaves[remaining.pop()]
n.add_child(c)
joined.append(c)
joined.append(n)
for node in joined:
if not node.back:
node.isroot = 1
return node
示例3: main
def main():
""" A simple example. Note that the Tkinter lines are there only
because this code will be run standalone. On the interpreter,
simply invoking surf and view would do the job."""
import Tkinter
r = Tkinter.Tk()
r.withdraw()
def f(x, y):
return Numeric.sin(x*y)/(x*y)
x = Numeric.arange(-7., 7.05, 0.1)
y = Numeric.arange(-5., 5.05, 0.05)
v = surf(x, y, f)
import RandomArray
z = RandomArray.random((50, 25))
v1 = view(z)
v2 = view(z, warp=1)
z_large = RandomArray.random((1024, 512))
v3 = viewi(z_large)
# A hack for stopping Python when all windows are closed.
v.master = r
v1.master = r
v2.master = r
#v3.master = r
r.mainloop()
示例4: setUp
def setUp(self):
self.number = 50
X = RandomArray.random(self.number)
Y = RandomArray.random(self.number)
Z = RandomArray.random(self.number)
co = Numeric.array([X, Y, Z])
self.points = []
for i in range(len(co[0])):
self.points.append(tuple(co[:,i].tolist()))
示例5: RunMovie
def RunMovie(self,event = None):
import RandomArray
start = clock()
shift = RandomArray.randint(0,0,(2,))
NumFrames = 50
for i in range(NumFrames):
points = self.LEs.Points
shift = RandomArray.randint(-5,5,(2,))
points += shift
self.LEs.SetPoints(points)
self.Canvas.Draw()
print "running the movie took %f seconds to disply %i frames"%((clock() - start),NumFrames)
示例6: compare
def compare(m, Nobs, Ncodes, Nfeatures):
obs = RandomArray.normal(0., 1., (Nobs, Nfeatures))
codes = RandomArray.normal(0., 1., (Ncodes, Nfeatures))
import scipy.cluster.vq
scipy.cluster.vq
print 'vq with %d observation, %d features and %d codes for %d iterations' % \
(Nobs,Nfeatures,Ncodes,m)
t1 = time.time()
for i in range(m):
code, dist = scipy.cluster.vq.py_vq(obs, codes)
t2 = time.time()
py = (t2 - t1)
print ' speed in python:', (t2 - t1) / m
print code[:2], dist[:2]
t1 = time.time()
for i in range(m):
code, dist = scipy.cluster.vq.vq(obs, codes)
t2 = time.time()
print ' speed in standard c:', (t2 - t1) / m
print code[:2], dist[:2]
print ' speed up: %3.2f' % (py / (t2 - t1))
# load into cache
b = vq(obs, codes)
t1 = time.time()
for i in range(m):
code, dist = vq(obs, codes)
t2 = time.time()
print ' speed inline/blitz:', (t2 - t1) / m
print code[:2], dist[:2]
print ' speed up: %3.2f' % (py / (t2 - t1))
# load into cache
b = vq2(obs, codes)
t1 = time.time()
for i in range(m):
code, dist = vq2(obs, codes)
t2 = time.time()
print ' speed inline/blitz2:', (t2 - t1) / m
print code[:2], dist[:2]
print ' speed up: %3.2f' % (py / (t2 - t1))
# load into cache
b = vq3(obs, codes)
t1 = time.time()
for i in range(m):
code, dist = vq3(obs, codes)
t2 = time.time()
print ' speed using C arrays:', (t2 - t1) / m
print code[:2], dist[:2]
print ' speed up: %3.2f' % (py / (t2 - t1))
示例7: test_sparse_vs_dense
def test_sparse_vs_dense(self):
RandomArray.seed(0) # For reproducability
for s, l in (100, 100000), (10000, 100000), (100000, 100000):
small = Numeric.sort(RandomArray.randint(0, 100000, (s,)))
large = Numeric.sort(RandomArray.randint(0, 100000, (l,)))
sparse1 = soomfunc.sparse_intersect(small, large)
sparse2 = soomfunc.sparse_intersect(large, small)
dense1 = soomfunc.dense_intersect(small, large)
dense2 = soomfunc.dense_intersect(large, small)
self.assertEqual(sparse1, sparse2)
self.assertEqual(dense1, dense2)
self.assertEqual(sparse1, dense1)
示例8: _synth
def _synth(self, freq, msdur, vol, risefall):
t = arange(0, msdur / 1000.0, 1.0 / _Beeper._dafreq)
s = zeros((t.shape[0], 2))
# use trapezoidal envelope with risefall (below) time
if msdur < 40:
risefall = msdur / 2.0
env = -abs((t - (t[-1] / 2)) / (risefall/1000.0))
env = env - min(env)
env = where(less(env, 1.0), env, 1.0)
bits = _Beeper._bits
if bits < 0:
bits = -bits
signed = 1
else:
signed = 0
fullrange = power(2, bits-1)
if freq is None:
y = (env * vol * fullrange * \
RandomArray.random(t.shape)).astype(Int16)
else:
y = (env * vol * fullrange * \
sin(2.0 * pi * t * freq)).astype(Int16)
if _Beeper._chans == 2:
y = transpose(array([y,y]))
s = pygame.sndarray.make_sound(y)
return s
示例9: __init__
def __init__(self, rows, cols, size):
self.rows = rows
self.cols = cols
self.vectorLen = size
self.weight = RandomArray.random((rows, cols, size))
self.input = []
self.loadOrder = []
self.step = 0
self.maxStep = 1000.0
示例10: sampled_ds
def sampled_ds(parent_dataset, sample, name=None, filter_label=None, **kwargs):
parent_len = len(parent_dataset)
samp_len = int(parent_len * sample)
record_ids = Numeric.sort(RandomArray.randint(0, parent_len, samp_len))
if name is None:
name = 'samp%02d_%s' % (sample * 100, parent_dataset.name)
if filter_label is None:
filter_label = '%.3g%% sample' % (sample * 100)
return FilteredDataset(parent_dataset, record_ids, name=name,
filter_label=filter_label, **kwargs)
示例11: statistics
def statistics():
pd = stats.norm(loc=1, scale=0.5) # normal distribution N(1,0.5)
n=10000
r = pd.rvs(n) # random variates
import RandomArray
r = RandomArray.normal(1, 0.1, n)
s = stats.stats
print pd.stats()
print 'mean=%g stdev=%g skewness=%g kurtosis=%g' % \
(s.mean(r), s.variation(r), s.skew(r), s.kurtosis(r))
bin_counts, bin_min, min_width, noutside = s.histogram(r, numbins=50)
示例12: __init__
def __init__(self, *args):
apply(QWidget.__init__, (self,) + args)
# make a QwtPlot widget
self.plot = QwtPlot('A PyQwt and MinPack Demonstration', self)
# initialize the noisy data
scatter = 0.05
x = arrayrange(-5.0, 5.0, 0.1)
y = RandomArray.uniform(1.0-scatter, 1.0+scatter, shape(x)) * \
function([1.0, 1.0, -2.0, 2.0], x)
# fit from a reasonable initial guess
guess = asarray([0.5, 1.5, -1.0, 3.0])
yGuess = function(guess, x)
solution = leastsq(function, guess, args=(x, y))
yFit = function(solution[0], x)
print solution
# insert a few curves
c1 = self.plot.insertCurve('data')
c2 = self.plot.insertCurve('guess')
c3 = self.plot.insertCurve('fit')
# set curve styles
self.plot.setCurvePen(c1, QPen(Qt.black))
self.plot.setCurvePen(c2, QPen(Qt.red))
self.plot.setCurvePen(c3, QPen(Qt.green))
# copy the data
self.plot.setCurveData(c1, x, y)
self.plot.setCurveData(c2, x, yGuess)
self.plot.setCurveData(c3, x, yFit)
# set axis titles
self.plot.setAxisTitle(QwtPlot.xBottom, 'x -->')
self.plot.setAxisTitle(QwtPlot.yLeft, 'y -->')
self.plot.enableLegend(1)
self.plot.replot()
示例13: xrange
sampleRate = 44100.
c = 300. # meters per second
spectralRange = sampleRate / 2
import numpy
import math
import RandomArray
import stats
T=r/c
spectrum = numpy.zeros( nBins-1, numpy.complex)
for x in RandomArray.normal(0,standardMicrophoneDeviation,(nSpeakers,)) :
t1root = 1+x
t2root = 1-x
print t1root, t2root
spectrum += numpy.array([
complex(1, t1root*w*T) * math.e**complex(math.cos(w*T*t1root), math.sin(w*T*t1root)) /x / w / w / T / T -
complex(1, t2root*w*T) * math.e**complex(math.cos(w*T*t2root), math.sin(w*T*t2root)) /x / w / w / T / T
for w in [ math.pi*2*normfreq*spectralRange/nBins
for normfreq in xrange(1,nBins) ] ])
import Gnuplot
gp=Gnuplot.Gnuplot(persist=1)
gp('set data style lines')
gp.plot(abs(spectrum), [bin.real for bin in spectrum], [bin.imag for bin in spectrum], numpy.zeros(nBins))
gp.hardcopy(filename="IncoherenceSimulation.png",terminal="png")
示例14: allclose
assert allclose(computeResiduals(As, None, lmbd, Q), zeros(kconv), 0.0, tol)
assert allclose(lmbd, lmbd_exact, tol*tol, 0.0)
print 'OK'
#-------------------------------------------------------------------------------
# Test 2: K = None
print 'Test 2',
lmbd_exact = zeros(ncv, 'd')
for k in xrange(ncv):
lmbd_exact[k] = A[k,k]/M[k,k]
X0 = RandomArray.random((n,ncv))
kconv, lmbd, Q, it, it_inner = jdsym.jdsym(As, Ms, None, ncv, 0.0, tol, 150, itsolvers.qmrs,
jmin=5, jmax=10, eps_tr=1e-4, clvl=1)
assert ncv == kconv
assert allclose(computeResiduals(As, Ms, lmbd, Q), zeros(kconv), 0.0, normM*tol)
assert allclose(lmbd, lmbd_exact, normM*tol*tol, 0.0)
print 'OK'
#-------------------------------------------------------------------------------
# Test 3: general case
print 'Test 3',
示例15: trainPattern
print "Error =", error
def trainPattern(self, pattern):
# will depend on self.step
x, y, d = self.winner(pattern)
error += self.updateMap(pattern, x, y)
print "Winner is weight at (", x, y, ") (diff was", d, ") error = ", \
error
def test(self):
import numpy.oldnumeric as Numeric
self.loadOrder = range(len(self.input))
histogram = Numeric.zeros((self.cols, self.rows), 'i')
for p in self.loadOrder:
x, y, d = self.winner(self.input[p])
# print "Input[%d] =" % p, self.input[p],"(%d, %d)" % (x, y)
histogram[x][y] += 1
for r in range(self.rows):
for c in range(self.cols):
print "%5d" % histogram[c][r],
print ""
print ""
if __name__ == '__main__':
import numpy.oldnumeric as Numeric
s = SOM(5, 7, 5) # rows, cols; length of high-dimensional input
s.setInputs( RandomArray.random((100, 5)))
s.maxStep = 100
s.train()
s.test()