def demo(): cc=[ uniform(-0.2,0.2,(3,3)), uniform(2.0,2.0,(3,1)), ] a=pyAnn([2,10,10,2],default=.2,rand=1) print a trainset=[ ([.5,0.0],[0.5,0.0]), ([0.0,0.0],[0.0,0.0]), ([0.0,.5],[0.5,0.5]), ([.5,.5],[0.0,0.5]), ] turns=10000 errth=0 for i in xrange(turns): err=0.0 for t in trainset: a.feed_forward(t[0]) err += a.bp(t[1],fN=0.3,r=0.000) if err<errth: print "in turn: ", i break if i%100==1: print "error: ", err print a for ts in trainset: print ts[0],a.feed_forward(ts[0])
def demo(): cc = [ uniform(-0.2, 0.2, (3, 3)), uniform(2.0, 2.0, (3, 1)), ] a = pyAnn([2, 10, 10, 2], default=.2, rand=1) print a trainset = [ ([.5, 0.0], [0.5, 0.0]), ([0.0, 0.0], [0.0, 0.0]), ([0.0, .5], [0.5, 0.5]), ([.5, .5], [0.0, 0.5]), ] turns = 10000 errth = 0 for i in xrange(turns): err = 0.0 for t in trainset: a.feed_forward(t[0]) err += a.bp(t[1], fN=0.3, r=0.000) if err < errth: print "in turn: ", i break if i % 100 == 1: print "error: ", err print a for ts in trainset: print ts[0], a.feed_forward(ts[0])
def randomPointInSphere(r): """Returns a vector drawn from a uniform distribution within a sphere of radius |r|.""" rsq = r * r while 1: x = N.array([uniform(-r, r), uniform(-r, r), uniform(-r, r)]) if N.dot(x, x) < rsq: break return Vector(x)
def randomPointInBox(a, b=None, c=None): """Returns a vector drawn from a uniform distribution within a rectangular box with edge lengths |a|, |b|, |c|. If |b| and/or |c| are omitted, they are taken to be equal to |a|.""" if b is None: b = a if c is None: c = a x = uniform(-0.5 * a, 0.5 * a) y = uniform(-0.5 * b, 0.5 * b) z = uniform(-0.5 * c, 0.5 * c) return Vector(x, y, z)
def randomPointInSphere(r): """ :param r: the radius of a sphere :type r: float :returns: a vector drawn from a uniform distribution within a sphere of radius r. :rtype: Scientific.Geometry.Vector """ rsq = r*r while 1: x = N.array([uniform(-r, r), uniform(-r, r), uniform(-r, r)]) if N.dot(x, x) < rsq: break return Vector(x)
def randomPointInSphere(r): """ :param r: the radius of a sphere :type r: float :returns: a vector drawn from a uniform distribution within a sphere of radius r. :rtype: Scientific.Geometry.Vector """ rsq = r * r while 1: x = N.array([uniform(-r, r), uniform(-r, r), uniform(-r, r)]) if N.dot(x, x) < rsq: break return Vector(x)
def __bp(self, targets, sig=dsigmoid, fN=0.5, r=0.1): _t = targets ### calculate the delta of output layer _delta = map(lambda x, y: (x - y) * dsigmoid(y), _t, self.neurons[-1]) ###print "neurons", self.neurons, "+++" _sq_error = 0.0 for ei in range(self.layers[-1]): _sq_error += 0.5 * (targets[ei] - self.neurons[-1][ei])**2 for n in range(self.nl - 1, 0, -1): # calculate the strength change _rs = r * uniform(-1.0, 1.0, (self.layers[n - 1], self.layers[n])) * _sq_error _change = dot(transpose([self.neurons[n - 1]]), [_delta]) + _rs ### calculate the delta of hidden layers #### first we calculate the error of hidden layers _error_h = dot(_delta, transpose(self.strengthmatrixes[n - 1])) #### then we have the delta ####_delta = dot( _diagn2, _error_h) _delta = map(lambda x, y: x * dsigmoid(y), _error_h, self.neurons[n - 1]) self.strengthmatrixes[n - 1] = self.strengthmatrixes[n - 1] + fN * _change return _sq_error pass
def __bp(self, targets,sig=dsigmoid, fN=0.5,r=0.1): _t=targets ### calculate the delta of output layer _delta = map(lambda x,y: (x-y)*dsigmoid(y), _t, self.neurons[-1]) ###print "neurons", self.neurons, "+++" _sq_error = 0.0 for ei in range(self.layers[-1]): _sq_error += 0.5*(targets[ei]-self.neurons[-1][ei])**2 for n in range(self.nl-1,0,-1): # calculate the strength change _rs = r*uniform(-1.0,1.0,(self.layers[n-1],self.layers[n]))*_sq_error _change = dot(transpose([self.neurons[n-1]]) ,[_delta] )+_rs ### calculate the delta of hidden layers #### first we calculate the error of hidden layers _error_h = dot(_delta, transpose(self.strengthmatrixes[n-1])) #### then we have the delta ####_delta = dot( _diagn2, _error_h) _delta = map(lambda x,y: x*dsigmoid(y), _error_h, self.neurons[n-1]) self.strengthmatrixes[n-1] = self.strengthmatrixes[n-1] + fN*_change return _sq_error pass
def randomPointInBox(a, b=None, c=None): """ :param a: the edge length of a box along the x axis :type a: float :param b: the edge length of a box along the y axis (default: a) :type b: float :param c: the edge length of a box along the z axis (default: a) :type c: float :returns: a vector drawn from a uniform distribution within a rectangular box with edge lengths a, b, c. :rtype: Scientific.Geometry.Vector """ if b is None: b = a if c is None: c = a x = uniform(-0.5 * a, 0.5 * a) y = uniform(-0.5 * b, 0.5 * b) z = uniform(-0.5 * c, 0.5 * c) return Vector(x, y, z)
def randomPointInBox(a, b = None, c = None): """ :param a: the edge length of a box along the x axis :type a: float :param b: the edge length of a box along the y axis (default: a) :type b: float :param c: the edge length of a box along the z axis (default: a) :type c: float :returns: a vector drawn from a uniform distribution within a rectangular box with edge lengths a, b, c. :rtype: Scientific.Geometry.Vector """ if b is None: b = a if c is None: c = a x = uniform(-0.5*a, 0.5*a) y = uniform(-0.5*b, 0.5*b) z = uniform(-0.5*c, 0.5*c) return Vector(x, y, z)
def randomRotation(max_angle=N.pi): """ :param max_angle: the upper limit for the rotation angle :type max_angle: float :returns: a random rotation with a uniform axis distribution and angles drawn from a uniform distribution between -max_angle and max_angle. :rtype: Scientific.Geometry.Transformations.Rotation """ return Rotation(randomDirection(), uniform(-max_angle, max_angle))
def randomRotation(max_angle = N.pi): """ :param max_angle: the upper limit for the rotation angle :type max_angle: float :returns: a random rotation with a uniform axis distribution and angles drawn from a uniform distribution between -max_angle and max_angle. :rtype: Scientific.Geometry.Transformations.Rotation """ return Rotation(randomDirection(), uniform(-max_angle, max_angle))
def test_check_receptors(self): """ The Python and C versions of the receptor site hit test should return the same result """ from RandomArray import uniform, seed from TAP_ext import check_receptors from time import time area = 200 num_LEs = 100 num_times = 10 num_sites = 4 sites = [ array([(20, 65), (40, 35), (70, 25), (75, 45), (55, 50), (45, 75), (20, 65)], Float) ] * num_sites # build site bounding boxes BBs = [] for site in sites: max_x = site[0, 0] min_x = site[0, 0] max_y = site[0, 1] min_y = site[0, 1] max_x = max(max_x, max(site[:, 0])) min_x = min(min_x, min(site[:, 0])) max_y = max(max_y, max(site[:, 1])) min_y = min(min_y, min(site[:, 1])) BBs.append(array((max_x, min_x, max_y, min_y), Float)) LEs = uniform(0, area, (num_times, num_LEs, 2)) Hit_Table1 = zeros((num_LEs, num_sites), Int) start = time() hit_test(LEs, sites, BBs, Hit_Table1, 0) print "Python version took %.3f seconds" % (time() - start) Hit_Table2 = zeros((num_LEs, num_sites), Int) start = time() check_receptors.hit_test(LEs, sites, BBs, Hit_Table2, 0) print "c version took %.3f seconds" % (time() - start) assert alltrue( equal(Hit_Table1, Hit_Table2)), "Python and C version gave different results"
def resize_using_defaults(a,newsize,default=1.0,rand=0): """ resize a matrix to 'newsize', and fill all extra cells with 'default' """ oldshape=shape(a) dif=array(newsize)-array(oldshape) if dif[0] <= 0 : tmpa=a[:newsize[0]] else: if rand==0: _add_a=ones((dif[0],oldshape[1]))*default else: _add_a=uniform(-1.0,1.0,(dif[0],oldshape[1]))*default tmpa=concatenate((a,_add_a)) if dif[1] <= 0 : tmpb=array(tmpa)[:,:newsize[1]] else: if rand==0: _add_b=ones((newsize[0],dif[1]))*default else: _add_b=uniform(-1.0,1.0,(newsize[0],dif[1]))*default tmpb=concatenate((tmpa,_add_b),1) return tmpb
def resize_using_defaults(a, newsize, default=1.0, rand=0): """ resize a matrix to 'newsize', and fill all extra cells with 'default' """ oldshape = shape(a) dif = array(newsize) - array(oldshape) if dif[0] <= 0: tmpa = a[:newsize[0]] else: if rand == 0: _add_a = ones((dif[0], oldshape[1])) * default else: _add_a = uniform(-1.0, 1.0, (dif[0], oldshape[1])) * default tmpa = concatenate((a, _add_a)) if dif[1] <= 0: tmpb = array(tmpa)[:, :newsize[1]] else: if rand == 0: _add_b = ones((newsize[0], dif[1])) * default else: _add_b = uniform(-1.0, 1.0, (newsize[0], dif[1])) * default tmpb = concatenate((tmpa, _add_b), 1) return tmpb
def test_check_receptors(self): """ The Python and C versions of the receptor site hit test should return the same result """ from RandomArray import uniform, seed from TAP_ext import check_receptors from time import time area = 200 num_LEs = 100 num_times = 10 num_sites = 4 sites = [array([(20,65),(40,35),(70,25),(75,45),(55,50),(45,75),(20,65)],Float)]*num_sites # build site bounding boxes BBs = [] for site in sites: max_x = site[0,0] min_x = site[0,0] max_y = site[0,1] min_y = site[0,1] max_x = max(max_x, max(site[:,0])) min_x = min(min_x, min(site[:,0])) max_y = max(max_y, max(site[:,1])) min_y = min(min_y, min(site[:,1])) BBs.append(array((max_x,min_x,max_y,min_y),Float)) LEs = uniform(0,area,(num_times,num_LEs,2)) Hit_Table1 = zeros((num_LEs, num_sites),Int) start = time() hit_test(LEs,sites,BBs,Hit_Table1,0) print "Python version took %.3f seconds"%(time()-start) Hit_Table2 = zeros((num_LEs, num_sites),Int) start = time() check_receptors.hit_test(LEs,sites,BBs,Hit_Table2,0) print "c version took %.3f seconds"%(time()-start) assert alltrue(equal(Hit_Table1,Hit_Table2)), "Python and C version gave different results"
def makenoise(mod_depth,mod_image,side): from RandomArray import uniform if len(mod_image) == 0: # no image supplied # returns uniform white noise [0-1] as 3-d array noise = uniform(0, mod_depth, shape=(side,side)) tmp = zeros((side,side,3), Float) tmp[:,:,0] = noise[:] tmp[:,:,1] = noise[:] tmp[:,:,2] = noise[:] noise = tmp; else: # image file supplied # returns an image scaled to [0-1] as 3-d array tmp = Sprite(fname=mod_image) tmp = tmp.subimage(0, 0, side, side, center=1) noise = mod_depth * (tmp.astype(Float) - 128.0) / 128.0 return noise
def makenoise(mod_depth, mod_image, side): from RandomArray import uniform if len(mod_image) == 0: # no image supplied # returns uniform white noise [0-1] as 3-d array noise = uniform(0, mod_depth, shape=(side, side)) tmp = zeros((side, side, 3), Float) tmp[:, :, 0] = noise[:] tmp[:, :, 1] = noise[:] tmp[:, :, 2] = noise[:] noise = tmp else: # image file supplied # returns an image scaled to [0-1] as 3-d array tmp = Sprite(fname=mod_image) tmp = tmp.subimage(0, 0, side, side, center=1) noise = mod_depth * (tmp.astype(Float) - 128.0) / 128.0 return noise
def simple_rdp(s, dir=None, vel=None, fraction=0.25, fgcolor=(255,255,255), bgcolor=(128,128,128), rseed=None): if rseed: old_seed = get_seed() seed(rseed[0], rseed[1]) if dir is None: for n in range(3): if n == 0: m = uniform(0.0, 1.0, shape=(s.w, s.h)) mc = where(greater(m, fraction), bgcolor[n], fgcolor[n]) s.array[:,:,n] = mc[::].astype(UnsignedInt8) else: dx = -int(round(vel * math.cos(math.pi * dir / 180.0))) dy = int(round(vel * math.sin(math.pi * dir / 180.0))) a = s.array[:,:,:] a = concatenate((a[dx:,:,:],a[:dx,:,:]), axis=0) a = concatenate((a[:,dy:,:],a[:,:dy,:]), axis=1) s.array[:,:,:] = a[::] if rseed: seed(old_seed[0], old_seed[1])
def __load_strength(self, strengths, default=1.0,rand=0): """ strength: matrix of strengths between each layer, default: the default stength """ import random self.strengthmatrixes=[] loadlen=len(strengths) for i in range(0, loadlen): fill=default self.strengthmatrixes.append( resize_using_defaults(strengths[i], (self.layers[i],self.layers[i+1]),fill,rand) ) if loadlen < self.nl: for i in range(loadlen,self.nl-1): fill=default if rand!=0: self.strengthmatrixes.append( uniform(-1.0,1.0,(self.layers[i],self.layers[i+1]))*fill ) else: self.strengthmatrixes.append( ones((self.layers[i],self.layers[i+1]))*fill )
def __load_strength(self, strengths, default=1.0, rand=0): """ strength: matrix of strengths between each layer, default: the default stength """ import random self.strengthmatrixes = [] loadlen = len(strengths) for i in range(0, loadlen): fill = default self.strengthmatrixes.append( resize_using_defaults(strengths[i], (self.layers[i], self.layers[i + 1]), fill, rand)) if loadlen < self.nl: for i in range(loadlen, self.nl - 1): fill = default if rand != 0: self.strengthmatrixes.append( uniform(-1.0, 1.0, (self.layers[i], self.layers[i + 1])) * fill) else: self.strengthmatrixes.append( ones((self.layers[i], self.layers[i + 1])) * fill)
def randomRotation(max_angle=N.pi): """Returns a Rotation object describing a random rotation with a uniform axis distribution and angles drawn from a uniform distribution between -|max_angle| and |max_angle|.""" return Rotation(randomDirection(), uniform(-max_angle, max_angle))