def fit(self, trainSamples, trainTargets): self.dataModel = MemeryDataModel(trainSamples, trainTargets) self.mu = np.array(trainTargets).mean() self.bu = np.zeros(self.dataModel.getUsersNum()) self.bi = np.zeros(self.dataModel.getItemsNum()) temp = math.sqrt(self.factors) self.qi = [[(0.1 * random.random() / temp) for j in range(self.factors)] for i in range(self.dataModel.getItemsNum())] self.pu = [[(0.1 * random.random() / temp) for j in range(self.factors)] for i in range(self.dataModel.getUsersNum())] lineData = self.dataModel.getLineData() lengthOfTrain = len(lineData) for step in range(self.iter): rmse_sum = 0.0 hash = np.random.permutation(lengthOfTrain) for j in range(lengthOfTrain): n = hash[j] row = lineData[n] uid = self.dataModel.getUidByUser(row[0]) iid = self.dataModel.getIidByItem(row[1]) rating = row[2] #rating = 1 eui = rating - self.predict_single(uid, iid) rmse_sum += eui**2 self.bu[uid] += self.learningrate*(eui-self.userregular*self.bu[uid]) self.bi[iid] += self.learningrate*(eui-self.itemregular*self.bi[iid]) temp = self.qi[iid] self.qi[iid] += self.learningrate*(np.dot(eui, self.pu[uid]) - np.dot(self.itemregular, self.qi[iid])) self.pu[uid] += self.learningrate*(np.dot(eui, temp) - np.dot(self.userregular, self.pu[uid])) self.learningrate = self.learningrate * 0.93
def fit(self, trainSamples, trainTargets): self.dataModel = MemeryDataModel(trainSamples, trainTargets) temp = math.sqrt(self.factors) self.item_bias = np.zeros(self.dataModel.getItemsNum()) self.user_factors = np.array([[(0.1 * random.random() / temp) for j in range(self.factors)] for i in range(self.dataModel.getUsersNum())]) self.item_factors = np.array([[(0.1 * random.random() / temp) for j in range(self.factors)] for i in range(self.dataModel.getItemsNum())]) ''' user_file = 'pu' item_file = 'qi' self.user_factors = np.array(pd.read_csv(user_file).values)[:, 1:] self.item_factors = np.array(pd.read_csv(item_file).values)[:, 1:] ''' num_loss_samples = int(100*self.dataModel.getUsersNum()**0.5) #print 'sampling {0} <user,item i,item j> triples...'.format(num_loss_samples) loss_sampler = UniformUserUniformItem(True) self.loss_samples = [t for t in loss_sampler.generate_samples(self.dataModel, num_loss_samples)] old_loss = self.loss() update_sampler = UniformPairWithoutReplacement(True) #print 'initial loss = {0}'.format(self.loss()) for it in xrange(self.iter): #print 'starting iteration {0}'.format(it) for u, i, j in update_sampler.generate_samples(self.dataModel): self.update_factors(u, i, j) if abs(self.loss() - old_loss) < 0.01 or self.loss() - old_loss > 0: #print 'iteration {0}: loss = {1}'.format(it, self.loss()) #print 'converge!!' break else: old_loss = self.loss() self.learning_rate *= 0.9
def makeHorizontalLine(): """ Describe a horizontal line as a vector of start and end points """ x = random.random() x2 = random.random() y = random.random() if x < x2: return np.array([x, y, x2, y]) else: return np.array([x2, y, x, y])
def makeVerticalLine(): """ Describe a vertical line as a vector of start and end points """ x = random.random() y = random.random() y2 = random.random() if y < y2: return np.array([x, y, x, y2]) else: return np.array([x, y2, x, y])
def simulate(self): '''simulate a sample path of the multivariate Hawkes process method: Dassios, A., & Zhao, H. (2013). Exact simulation of Hawkes process with exponentially decaying intensity. Electronic Communications in Probability ''' assert self._nu_set and self._tau_set and self._baseline_rate_set and self._clusters_set, "parameters not set yet" assert self.test_stationarity(), "This is not a stationary process!" currentTime = 0 # data[x] is the time points for cluster x data = [[] for x in range(self._C)] # agent_data[x] is the time points for agent x agent_data = [[] for x in range(self._A)] # the left and right limit of intensities intensities_left = self._baseline_rate.copy() intensities_right = self._baseline_rate.copy() + 1e-10 # event counts event_counts = [0 for x in range(self._A)] print("Simulating...") iter_count = 0 while currentTime <= self._T: iter_count += 1 # get W s = -ones(self._C) for x in range(self._C): u1 = random.random() D = 1 + log(u1) / (intensities_right[x] - self._baseline_rate[x]) / self._tau[x] u2 = random.random() s2 = -1 / self._baseline_rate[x] * log(u2) if D > 0: s1 = -self._tau[x] * log(D) s[x] = min(s1, s2) else: s[x] = s2 assert all(s >= 0) # event to l l = argmin(s) W = s[l] # record jump currentTime = currentTime + W data[l].append(currentTime) event_counts[l] += 1 # randomly select an agent in the cluster to assign to - uniform thinning agents = [i for i, x in enumerate(self._clusters_assign) if x == l] agent = random.choice(agents) agent_data[agent].append(currentTime) # update intensities intensities_left = (intensities_right - self._baseline_rate) * exp( -W / self._tau) + self._baseline_rate intensities_right = intensities_left + self._nu[l, :] print("Simulation done, %d events occurred" % (sum(event_counts))) return data, agent_data
def run(self): print('started letter thread...') self.isstarted=1 start_time=time.time() letters=self.letters switch_frequency=self.switch_frequency switch_probability=self.switch_probability cal_time = time.time()+switch_frequency # prevent from jumping the first later - irritating! # keep on doing this - until the end of the experiment, when I 'quit' the CORE: # beauty fix - start 1 sec after start of the experiment time.sleep(1.0) # somehow control that things don't go too fast (effectively reduces the % change of an oddball occurring lastoddball = 0 # set counter to 0 new_lim = 4 # make sure no oddball happens IMMEDEATELY into the experiment: letter_direction = 1; # oddball = reverse letter direction while True: # if the time bigger than the 'cal' time: if time.time() - cal_time > 0: # effecively, only run this code-block once every letter_time_interval: cal_time = cal_time + switch_frequency # switch the letter - according to the given chance: if random.random() < switch_probability and lastoddball > new_lim: # make a (randomly chosen) ISI where nothing should happen. new_lim = 1+round(random.random()*3+2) # between 3 and 6 = the ISI - at LEAST lastoddball = 0 letter_direction = letter_direction*-1 # letters = shift(letters,-1) self.type = 'oddball' else: lastoddball = lastoddball + 1 self.type = 'normal' letters = shift(letters,letter_direction) # well - to be true - it's ONLY the direction that counts, not the size. Like Vector in Dispicable Me. # set the 'current' letter. self.current_letter = letters[0] # set the flag, too. self.flag = 1 # sleep - for only a short time. time.sleep(0.01) if self.stop: break
def randomized_test(N=3, V=5): # This creates a random model and checks if the exhaustive and viterbi # decoders agree. import random A = {(a, b): random.random() for a in range(V) for b in range(V)} Bs = [[random.random() for k in range(V)] for i in range(N)] print "output_vocab=", range(V) print "A=", A print "Bs=", Bs fromex = exhaustive(A, Bs, range(V)) fromvit = viterbi(A, Bs, range(V)) assert fromex == fromvit print "Worked!"
def drawText(ctx, x, y, string): if not DRAW_TEXT: return offset = random.random() * 0.005 ctx.set_source_rgba(*TEXT) ctx.move_to(x + offset, y + offset) ctx.show_text(str(string))
def annealingoptimize(domain,costf,T=10000.0,cool=0.95,step=1): # 从一个随机解开始 vec=[float(random.randint(domain [0],domain[1]))] while T>0.1: # 随机选择一个维度 i=random.randint(0,len(domain)-1) # 选择一个搜索方向 dir=random.randint(-step,step) # 在搜索方向上生成新解 vecb=vec[:] vecb +=dir elif vecb>domain[1]: vecb=domain[1] ea=costf(vec) eb=costf(vecb) #重新计算系统稳定性-概率p,退火算法核心 p=pow(math.e,(-eb-ea)/T) # 更优解将替换当前解,在系统早期,温度很高,系统很不稳定,非更优解也可能替换当前解,这样做的目的,是避免过快陷入局部最优解,更大范围搜索最优解。 if (eb<ea or random.random()<p): vec=vecb # 减低温度 T=T*cool
def generate_random(self, n_points, s_d, start, invalid_prob=0.): points = [start] curr = start for _ in range(n_points - 1): curr = max(0, curr + random.gauss(0, s_d)) points.append(curr if random.random() > invalid_prob else -1) return points
def run(self): print('started letter thread...') self.isstarted=1 start_time=time.time() letters=self.letters switch_frequency=self.switch_frequency switch_probability=self.switch_probability cal_time = time.time() # keep on doing this - until the end of the experiment, when I 'quit' the CORE: while True: # if the time bigger than the 'cal' time: if time.time() - cal_time > 0: # effecively, only run this code-block once every letter_time_interval: cal_time = cal_time + switch_frequency # switch the letter - according to the given chance: if random.random() < switch_probability: letters = shift(letters,-1) else: letters = shift(letters,1) # set the 'current' letter. self.current_letter = letters[0] # set the flag, too. self.flag = 1 # sleep - for only a short time. time.sleep(0.01) if self.stop: break
def mutation(self,probability): #randomly swap two tuples from sequence r = random.random() if r > probability: idx = range(len(self.perm)) i1, i2 = random.sample(idx, 2) self.perm[i1], self.perm[i2] = self.perm[i2], self.perm[i1]
def estimate_beta(x,y): beta_inital = [random.random() for x_i in x[0]] return minimize_stochastic(squared_error, squared_error_gradient, x,y, beta_inital, 0.001)
def newChild(self): """产生新后的""" parent1 = self.getOne() rate = random.random() # 按概率交叉 if rate < self.croessRate: # 交叉 parent2 = self.getOne() gene = self.cross(parent1, parent2) else: gene = parent1.gene # 按概率突变 rate = random.random() if rate < self.mutationRate: gene = self.mutation(gene) return Life(gene)
def fit(self, trainSamples, trainTargets): self.dataModel = MemeryDataModel(trainSamples, trainTargets) temp = math.sqrt(self.factors) self.item_bias = np.zeros(self.dataModel.getItemsNum()) self.user_factors = np.array([[ (0.1 * random.random() / temp) for j in range(self.factors) ] for i in range(self.dataModel.getUsersNum())]) self.item_factors = np.array([[ (0.1 * random.random() / temp) for j in range(self.factors) ] for i in range(self.dataModel.getItemsNum())]) ''' user_file = 'pu' item_file = 'qi' self.user_factors = np.array(pd.read_csv(user_file).values)[:, 1:] self.item_factors = np.array(pd.read_csv(item_file).values)[:, 1:] ''' num_loss_samples = int(100 * self.dataModel.getUsersNum()**0.5) #print 'sampling {0} <user,item i,item j> triples...'.format(num_loss_samples) loss_sampler = UniformUserUniformItem(True) self.loss_samples = [ t for t in loss_sampler.generate_samples(self.dataModel, num_loss_samples) ] old_loss = self.loss() update_sampler = UniformPairWithoutReplacement(True) #print 'initial loss = {0}'.format(self.loss()) for it in xrange(self.iter): #print 'starting iteration {0}'.format(it) for u, i, j in update_sampler.generate_samples(self.dataModel): self.update_factors(u, i, j) if abs(self.loss() - old_loss) < 0.01 or self.loss() - old_loss > 0: #print 'iteration {0}: loss = {1}'.format(it, self.loss()) #print 'converge!!' break else: old_loss = self.loss() self.learning_rate *= 0.9
def semaphore_func(sema, mutex, running): sema.acquire() mutex.acquire() running.value += 1 print running.value, 'tasks are running' mutex.release() random.seed() time.sleep(random.random()*2) mutex.acquire() running.value -= 1 print '%s has finished' % multiprocessing.current_process() mutex.release() sema.release()
def fit(self, trainSamples, trainTargets): self.dataModel = MemeryDataModel(trainSamples, trainTargets) self.mu = np.array(trainTargets).mean() self.bu = np.zeros(self.dataModel.getUsersNum()) self.bi = np.zeros(self.dataModel.getItemsNum()) temp = math.sqrt(self.factors) self.qi = [[(0.1 * random.random() / temp) for j in range(self.factors)] for i in range(self.dataModel.getItemsNum())] self.pu = [[(0.1 * random.random() / temp) for j in range(self.factors)] for i in range(self.dataModel.getUsersNum())] lineData = self.dataModel.getLineData() lengthOfTrain = len(lineData) for step in range(self.iter): rmse_sum = 0.0 hash = np.random.permutation(lengthOfTrain) for j in range(lengthOfTrain): n = hash[j] row = lineData[n] uid = self.dataModel.getUidByUser(row[0]) iid = self.dataModel.getIidByItem(row[1]) rating = row[2] #rating = 1 eui = rating - self.predict_single(uid, iid) rmse_sum += eui**2 self.bu[uid] += self.learningrate * ( eui - self.userregular * self.bu[uid]) self.bi[iid] += self.learningrate * ( eui - self.itemregular * self.bi[iid]) temp = self.qi[iid] self.qi[iid] += self.learningrate * ( np.dot(eui, self.pu[uid]) - np.dot(self.itemregular, self.qi[iid])) self.pu[uid] += self.learningrate * ( np.dot(eui, temp) - np.dot(self.userregular, self.pu[uid])) self.learningrate = self.learningrate * 0.93
def semaphore_func(running): #sema.acquire() #mutex.acquire() running.value += 1 print running.value, 'tasks are running' #mutex.release() random.seed() time.sleep(random.random()*5) #mutex.acquire() running.value -= 1 print '%s has finished' % multiprocessing.current_process().name #mutex.release() #sema.release() return
def random_out(self, # Discrete_Observations instance s): ''' For simulation, draw a random observation given state s Parameters ---------- s : int Index of state Returns ------- y : int Random observation drawn from distribution conditioned on state s ''' import random return (np.searchsorted(self.cum_y[s],random.random()),)
def run(self): print('started letter thread...') self.isstarted = 1 start_time = time.time() letters = self.letters switch_frequency = self.switch_frequency switch_probability = self.switch_probability cal_time = time.time() # keep on doing this - until the end of the experiment, when I 'quit' the CORE: while True: # if the time bigger than the 'cal' time: if time.time() - cal_time > 0: # effecively, only run this code-block once every letter_time_interval: cal_time = cal_time + switch_frequency # switch the letter - according to the given chance: if random.random() < switch_probability: letters = shift(letters, -1) else: letters = shift(letters, 1) # set the 'current' letter. self.current_letter = letters[0] # set the flag, too. self.flag = 1 if self.pause == 0: self.current_letter = letters[0] self.pause = 1 elif self.pause == 1: self.current_letter = (' ') self.pause = 0 # sleep - for only a short time. time.sleep(0.01) if self.stop: break
def inside(p): x, y = random.random(), random.random() return x*x + y*y < 1
def bunda(name): print "value: ",name random.seed() time.sleep(random.random()*5) print '%s has finished' % multiprocessing.current_process().name return
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen win.flip() # -------Ending Routine "trial"------- for thisComponent in trialComponents: if hasattr(thisComponent, "setAutoDraw"): thisComponent.setAutoDraw(False) # ------Prepare to start Routine "fixation"------- t = 0 fixationClock.reset() # clock frameN = -1 continueRoutine = True # update component parameters for each repeat import random time = random.random() * 0.5 + 3 # keep track of which components have finished fixationComponents = [image_2] for thisComponent in fixationComponents: if hasattr(thisComponent, 'status'): thisComponent.status = NOT_STARTED # -------Start Routine "fixation"------- while continueRoutine: # get current time t = fixationClock.getTime() frameN = frameN + 1 # number of completed frames (so 0 is the first frame) # update/draw components on each frame # *image_2* updates
def simulateNextState(state, action, simulationParameterObj, actionParameterObj, dispertionTable, germinationObj): """ simulate based on the input parameters and state and action :param state (an array of length simulationParameterObj.nbrReaches* simulationParameterObj.habitatSize) :param action (array of length simulationParameterObj.nbrReaches) :param simulationParameterObj (SimulationParameterClass) :param dispertionTable (matrix of size (simulationParameterObj.nbrReaches,simulationParameterObj.nbrReaches)) :param germinationObj (GerminationClass) :return next state """ H = simulationParameterObj.habitatSize Prod_rate = simulationParameterObj.prodRate Death_Rate = simulationParameterObj.deathRate on_off_indicator = simulationParameterObj.exogenousArrivalIndicator reach_arrival_rates = simulationParameterObj.reachArrivalRates reach_arrival_probs = simulationParameterObj.reachArrivalProbs beta = simulationParameterObj.competitionFactor eradication_rate = actionParameterObj.eradicationRate restoration_rate = actionParameterObj.restorationRate nbr_Reaches = simulationParameterObj.nbrReaches Nat_Prod_rate = Prod_rate[0] Tam_Prod_rate = Prod_rate[1] Nat_Death_Rate = Death_Rate[0] Tam_Death_Rate = Death_Rate[1] nbr_samples = 1 result = np.zeros((nbr_samples, len(state))) for sampling_idx in range(nbr_samples): S_ad = np.zeros((len(state), 1)) rnd_v = random.rand(1, len(state)) for i in range(len(state)): beforeDeath = state[i] action_type = action[int(np.floor(i / H))] afterDeath = 0 rnd = rnd_v[0, i] if(action_type == InvasiveUtility.Not): if (beforeDeath == InvasiveUtility.Emp): afterDeath = InvasiveUtility.Emp else:#(beforeDeath!=Emp) if beforeDeath == InvasiveUtility.Tam and rnd <= Tam_Death_Rate: afterDeath = InvasiveUtility.Emp elif beforeDeath == InvasiveUtility.Nat and rnd <= Nat_Death_Rate: afterDeath = InvasiveUtility.Emp else: afterDeath = beforeDeath elif(action_type == InvasiveUtility.Erad): if (beforeDeath == InvasiveUtility.Emp): afterDeath = InvasiveUtility.Emp else:#(beforeDeath!=Emp) if (beforeDeath == InvasiveUtility.Tam): if rnd <= eradication_rate: afterDeath = InvasiveUtility.Emp else: afterDeath = beforeDeath elif (beforeDeath == InvasiveUtility.Nat): if rnd <= Nat_Death_Rate: afterDeath = InvasiveUtility.Emp else: afterDeath = beforeDeath elif(action_type == InvasiveUtility.EradRes): if (beforeDeath == InvasiveUtility.Nat): if rnd <= Nat_Death_Rate: afterDeath = InvasiveUtility.Emp else: afterDeath = InvasiveUtility.Nat elif(beforeDeath == InvasiveUtility.Tam): if rnd <= eradication_rate * (1 - restoration_rate): afterDeath = InvasiveUtility.Emp elif rnd <= eradication_rate: afterDeath = InvasiveUtility.Nat else: afterDeath = InvasiveUtility.Tam elif(beforeDeath == InvasiveUtility.Emp): afterDeath = InvasiveUtility.Emp # if rnd <= (1 - restoration_rate): # afterDeath = Invasive_Utility.Emp # else: # afterDeath = Invasive_Utility.Nat elif(action_type == InvasiveUtility.Res): if (beforeDeath == InvasiveUtility.Emp): if rnd <= (1 - restoration_rate): afterDeath = InvasiveUtility.Emp else: afterDeath = InvasiveUtility.Nat else:#(beforeDeath!=Emp) if beforeDeath == InvasiveUtility.Tam and rnd <= Tam_Death_Rate: afterDeath = InvasiveUtility.Emp elif beforeDeath == InvasiveUtility.Nat and rnd <= Nat_Death_Rate: afterDeath = InvasiveUtility.Emp else: afterDeath = beforeDeath S_ad[i] = afterDeath G_T = Tam_Prod_rate * (S_ad == InvasiveUtility.Tam) G_N = Nat_Prod_rate * (S_ad == InvasiveUtility.Nat) G_T=sum(reshape(G_T,(nbr_Reaches,-1)),1) G_N=sum(reshape(G_N,(nbr_Reaches,-1)),1) Exg_T = 0 Exg_N = 0 if on_off_indicator == SimulationParameterClass.ExogenousArrivalOn: if size(reach_arrival_rates) > 0: Exg = binomial(reach_arrival_rates, reach_arrival_probs) Exg_T = Exg[:, 1] Exg_N = Exg[:, 0] gT_to = np.sum(binomial(repmat(G_T, nbr_Reaches,1).T, dispertionTable), axis=0) gN_to = sum(binomial(repmat(G_N, nbr_Reaches,1).T, dispertionTable), axis=0) arr = array([gT_to + Exg_T, gN_to + Exg_N]) gt_vec = reshape(arr.conj().transpose(), (1, size(arr))) #Germination Process gt_vec[0:2:] = binomial(gt_vec[0:2:], germinationObj.germinationSuccTam) gt_vec[1:2:] = binomial(gt_vec[1:2:], germinationObj.germinationSuccNat) landed = repmat(gt_vec, H, 1) new_S = binomial(landed, 1 / float(H)) final_S = np.zeros((len(state), 1), dtype='int') for i in range(nbr_Reaches): for h in range(H): idx = H * i + h si = S_ad[idx, 0] ghT_land = new_S[h, 2 * i] ghN_land = new_S[h, 2 * i + 1] if (si == InvasiveUtility.Emp): if (ghT_land == 0 and ghN_land == 0): final_S[idx] = InvasiveUtility.Emp else: rnd = random.random() Tam_p = beta * ghT_land / (beta * ghT_land + ghN_land) if rnd <= Tam_p: final_S[idx] = InvasiveUtility.Tam else: final_S[idx] = InvasiveUtility.Nat else: final_S[idx] = si #new_S=final_S final_S = np.squeeze(np.asarray(final_S)) if nbr_samples == 1: return final_S else: result[sampling_idx, :] = final_S#.conj().transpose() return result
exec('{} = thisPracticeLoop[paramName]'.format(paramName)) # ------Prepare to start Routine "trial"------- t = 0 trialClock.reset() # clock frameN = -1 continueRoutine = True routineTimer.add(4.000000) # update component parameters for each repeat fixation.setOpacity(1) go_item.setOpacity(1) go_item.setFillColor(go_color) key_resp = keyboard.Keyboard() #random.random() gibt einen zufälligen Wert zwischen 0.0 und 1.0 aus #50% der Fälle entspricht also >0.5 if (random.random() > 0.5): #entweder mache dies: #setze stim_pos Variable auf (-2,0) stim_pos = (-0.5,0) else: #oder mache das: stim_pos = (0.5,0) # keep track of which components have finished trialComponents = [fixation, go_item, key_resp] for thisComponent in trialComponents: thisComponent.tStart = None thisComponent.tStop = None thisComponent.tStartRefresh = None thisComponent.tStopRefresh = None if hasattr(thisComponent, 'status'): thisComponent.status = NOT_STARTED
patients.append(agent) for indiv in range(isolated_count): agent = Patient(state='isolated') patients.append(agent) for indiv in range(exposed_count): agent = Patient(state='exposed') patients.append(agent) counter = 0 while patients.get_num_infected() > 0 or patients.get_num_isolated() > 0: counter += 1 for susc in range(patients.get_num_susceptible()): if random.random() < beta * (patients.get_num_infected() / \ float(patients.get_num_total())): patients.exposed() # infect patient print('exposed') print(patients.get_num_exposed()) for exposed in range(patients.get_num_exposed()): if random.random() < sickness_rate: patients.infected() # recover patient print('infec') print(patients.get_num_infected()) for infected in range(patients.get_num_infected()): if random.random() < Isolation_rate: patients.isolate() # recover patient print(patients.get_num_isolated()) for isolated_count in range(patients.get_num_isolated()): if random.random() < gamma:
earning = earning + 0.02 e_string = str(earning) else: color = [1, 1, 1] Earning_Trial.append(0) elif cond == 'Pun': if Resp.corr == 0 or Resp.rt > crit: color = [1, 0, 0] Earning_Trial.append(1) earning = earning - 0.02 e_string = str(earning) else: color = [1, 1, 1] Earning_Trial.append(0) elif cond == 'ContRew': x = random.random() if Resp.corr == 0: color = [1, 1, 1] elif x < 0.5: color = [0, 1, 0] else: color = [1, 1, 1] e_string = str('You have earned money.') else: x = random.random() if Resp.corr == 0: color = [1, 0, 0] elif x < 0.5: color = [1, 0, 0] else: