id int64 0 25.6k | text stringlengths 0 4.59k |
|---|---|
18,900 | reasoning under uncertainty pearl' sprinkler example season rained sprinkler grass wet grass shiny shoes wet figure the sprinkler belief network f_ta prob(tamper,[],[ , ]f_fi prob(fire,[],[ , ]f_sm prob(smoke,[fire],[[ , ],[ , ]]f_al prob(alarm,[fire,tamper],[[[ ][ ]][[ ][ ]]]f_lv prob(leaving,[alarm],[[ ][ ]]f_re prob... |
18,901 | f_season prob(season,[],{'summer': 'winter': }f_sprinkler prob(sprinkler,[season],{'summer':{'on': ,'off': }'winter':{'on': ,'off': }}f_rained prob(rained,[season],{'summer':[ , ]'winter'[ , ]}f_wet prob(grass_wet,[sprinkler,rained]{'on'[[ , ],[ , ]]'off':[[ , ],[ , ]]}f_shiny prob(grass_shiny[grass_wet][[ , ][ , ]]f_s... |
18,902 | reasoning under uncertainty bipartite diagnostic network (noisy-orcold flu covid cough fever sneeze figure bipartite diagnostic network {coughfeversneezecoldflucovid}{p_cold_nop_flu_nop_covid_nop_cough_nop_fever_nop_sneeze_no} to see the conditional probability of noisy-or doprint(p_cough_no to_table() example from box... |
18,903 | p_cold_lr prob(cold,[],[ , ]p_flu_lr prob(flu,[],[ , ]p_covid_lr prob(covid,[],[ , ] p_cough_lr logisticregression(cough[cold,flu,covid][- ]p_fever_lr logisticregression(feverflu,covid][- ]p_sneeze_lr logisticregression(sneeze[cold,flu ][- ] bn_lr beliefnetwork("bipartite diagnostic network logistic regression"{coughfe... |
18,904 | reasoning under uncertainty raise notimplementederror("inferencemethod query"abstract method we use bn_ ch as the test casein particular ( truethis needs an error thresholdparticularly for the approximate methodswhere the default threshold is much too accurate probgraphicalmodels py -(continued def testim(selfthreshold... |
18,905 | elseif split_order =nonesplit_order [ for in self gm variables if ( not in obsand !qvarunnorm [self prob_search(dict_union({qvar:val},obs)self gm factorssplit_orderfor val in qvar domainp_obs sum(unnormreturn {val:pr/p_obs for val,pr in zip(qvar domainunnorm)the following is the naive search-based algorithm it is expon... |
18,906 | reasoning under uncertainty def __init__(self,gm=none)self cache {(frozenset()frozenset()): probsearch __init__(self,gm def prob_search(selfcontextfactorssplit_order)""returns the number \sum_{split_order\prod_{factorsgiven assignments in context context is variable:value dictionary factors is set of factors split_orde... |
18,907 | elseassert split_order"split_order should not be empty to get heretotal var split_order[ self display( "rc branching on"varfor val in var domaintotal +self prob_search(dict_union({var:val},context)factorssplit_order[ :]self cache[cetotal self display( "rc branching on"var,"returning"totalreturn total connected_componen... |
18,908 | reasoning under uncertainty factors_to_check |{ for in other_factors if var in variablesother_factors -factors_to_check set difference if other_factorsreturn [(component_factors,[ for in split_order if in component_variables])connected_components(contextother_factors[ for in split_order if not in component_variables]el... |
18,909 | from probgraphicalmodels import bn_no bn_lr coughfeversneezecoldflucovid bn_no probrc(bn_no bn_lr probrc(bn_lr #bn_no query(flu{fever: sneeze: }#bn_lr query(flu{fever: sneeze: }#bn_lr query(cough,{}#bn_lr query(cold,{cough: ,sneeze: ,fever: }#bn_lr query(flu,{cough: ,sneeze: ,fever: }#bn_lr query(covid,{cough: ,sneeze:... |
18,910 | reasoning under uncertainty projfactors self eliminate_var(projfactors,vunnorm factor_times(var,projfactorsp_obs=sum(unnormself display( ,"unnormalized probs:",unnorm,"prob obs:",p_obsreturn {val:pr/p_obs for val,pr in zip(var domainunnorm) factorobserved is factor that is the result of some observations on another fac... |
18,911 | if asst in self valuesreturn self values[asstelsetotal new_asst assignment copy(for val in self var_summed_out domainnew_asst[self var_summed_outval total +math prod(fac get_value(new_asstfor fac in self factorsself values[assttotal return total the method factor times multiples set of factors that are all factors on t... |
18,912 | reasoning under uncertainty if var in fac variablescontains_var append(facelsenot_contains_var append(facif contains_var =[]return factors elsenewfactor factorsum(var,contains_varself display( ,"multiplying:",[str(ffor in contains_var]self display( ,"creating factor:"newfactorself display( newfactor to_table()factor in... |
18,913 | if __name__ ="__main__"inferencemethod testim(ve stochastic simulation sampling from discrete distribution the method sample one generates single sample from (possible unnormalizeddistribution dist is {value weightdictionarywhere weight > this returns value with probability in proportion to its weight probstochsim py -... |
18,914 | reasoning under uncertainty cum dist_items[ ][ cumulative sum index for in randswhile >cumindex + cum +dist_items[index][ result append(dist_items[index][ ]return result exercise what is the time and space complexity the following methods to generate sampleswhere is the length of dist(an calls to sample one (bsample mu... |
18,915 | probstochsim py -(continued class samplinginferencemethod(inferencemethod)"""the abstract class of sampling-based belief network inference methods"" def __init__(self,gm=none)inferencemethod __init__(selfgm def query(self,qvar,obs={},number_samples= ,sample_order=none)raise notimplementederror("samplinginferencemethod ... |
18,916 | reasoning under uncertainty if not rejectedcounts[sample[qvar]+ self display( ,"accepted"tot sum(counts values()as well as the distribution we also include raw counts dist { : /tot if tot> else /len(qvar domainfor ( ,vin counts items()dist["raw_counts"counts return dist likelihood weighting likelihood weighting include... |
18,917 | self display( ,val,end="\ "sample[nvarval counts[sample[qvar]+weight self display( ,weighttot sum(counts values()as well as the distribution we also include the raw counts dist { : /tot for ( ,vin counts items()dist["raw_counts"counts return dist exercise change this algorithm so that it does importance sampling using ... |
18,918 | reasoning under uncertainty particles [{**pnvar:obs[nvar]for in resample(particlesweightsnumber_samples)elsefor part in particlespart[nvarsample_one({ :fac get_value({**partnvar: }for in nvar domain}self display( ,part[nvar],end="\ "counts {val: for val in qvar domainfor part in particlescounts[part[qvar]+ tot sum(coun... |
18,919 | #inferencemethod max_display_level detailed tracing for all inference methods #bn_ chr query( ,{}#bn_ chr query( ,{}#bn_ chr query( ,{ :true}#bn_ chr query( ,{ :true, :false} from probgraphicalmodels import bn_report,alarm,fire,leaving,report,smoke,tamper bn_reportr rejectionsampling(bn_reportanswers queries using reje... |
18,920 | reasoning under uncertainty gibbs sampling the following implements gibbs samplinga form of markov chain monte carlo mcmc probstochsim py -(continued #import random #from probgraphicalmodels import inferencemethod #from probstochsim import sample_onesamplinginferencemethod class gibbssampling(samplinginferencemethod)""... |
18,921 | for fac in var_to_factors[var]markov blanket vardist[val*fac get_value(samplesample[varsample_one(vardistif >burn_incounts[sample[qvar]+= tot sum(counts values()as well as the computed distributionwe also include raw counts dist { : /tot for ( ,vin counts items()dist["raw_counts"counts return dist #from probgraphicalmo... |
18,922 | reasoning under uncertainty it is more appropriate to plot the distribution of predictions over multiple runs the plot stats method plots the prediction of particular variable (or for the partition functionfor number of runs of the same algorithm on the xaxisis the prediction of the algorithm on the -axis is the number... |
18,923 | plot_stats(bn_reportp,tamper,true,{report:true,smoke:true},number_samples= number_runs= plot_stats(bn_reportr,tamper,true,{report:true,smoke:true},number_samples= number_runs= plot_stats(bn_reportl,tamper,true,{report:true,smoke:true},number_samples= number_runs= plot_stats(bn_reportg,tamper,true,{report:true,smoke:tru... |
18,924 | reasoning under uncertainty import random from probstochsim import sample_onesample_multiple class hmm(object)def __init__(selfstatesobsvarspobstransindist)""" hidden markov model states set of states obsvars set of observation variables pobs probability of observationspobs[ ][sis (obs_i=true state=strans transition pr... |
18,925 | or goes to one of the other corners with probability each if it is in the middleit stays in the middle with probability otherwise it moves to one the cornerseach with probability probhmm py -(continued trans specifies the dynamics trans[iis the distribution over states resulting from state trans[ ][jgives ( = =ism= mmc... |
18,926 | reasoning under uncertainty self advance(advance time self observe(obsobserve return self state_dist def observe(selfobs)"""updates state conditioned on observations obs is list of values for each observation variable""for in self hmm obsvarsself state_dist {st:self state_dist[st]*(self hmm pobs[ ][stif obs[ielse ( -se... |
18,927 | hmm state_dist for in range( )hmm advance(hmm state_dist exercise the representation assumes that there are list of boolean observations extend the representation so that the each observation variable can have multiple discrete values you need to choose representation for the modeland change the algorithm localization ... |
18,928 | reasoning under uncertainty hmm_ pos hmm_controlled(local_states{'door'}local_obsact trans[ / for in range( )]to change the ve localization code to allow for controlled hmmsnotice that the action selects which transition probability to us problocalization py -(continued class hmm_local(hmmvefilter)"""ve filter for cont... |
18,929 | self ax set_ylabel("probability"self ax set_xlabel("location"self ax set_title("location probability distribution"self ax set_xticks(self hmm statesvals [self loc_filt state_dist[ifor in self hmm statesself bars self ax bar(self hmm statesvalscolor='black'self ax bar_label(self bars,["{ }format( =vfor in vals]padding p... |
18,930 | reasoning under uncertainty note that it first advances time this is what is required if it is called after previous filtering if that is not what is wanted initiallydo an observe first ""for obs in obsseqself advance(advance time self observe(obsobserve self resample_particles(self display( ,"after observing"str(obs)"... |
18,931 | hmm pf hmmparticlefilter(hmm hmmparticlefilter max_display_level show each step hmm pf filter([{' ': ' ': ' ': }{' ': ' ': ' ': }]hmm pf hmmparticlefilter(hmm hmm pf filter([{' ': ' ': ' ': }{' ': ' ': ' ': }{' ': ' ': ' ': }{' ': ' ': ' ': }{' ': ' ': ' ': }{' ': ' ': ' ': }{' ': ' ': ' ': }{' ': ' ': ' ': }{' ': ' ':... |
18,932 | reasoning under uncertainty """returns observation sequence for the state sequence""obsseq=[for state in stateseqnewobs {obs:sample_one({ : -hmm pobs[obs][state], :hmm pobs[obs][state]}for obs in hmm obsvarsobsseq append(newobsreturn obsseq def create_eg(hmm, )"""create an annotated example for horizon ""seq,obs simula... |
18,933 | an initial distribution over the features "now(time this is belief network with all variables being time variables specification of the dynamics we define the how the variables now (time depend on variables now and the previous time (time )in such way that the graph is acyclic probdbn py -dynamic belief networks from p... |
18,934 | reasoning under uncertainty probdbn py -(continued class factorrename(factor)def __init__(self,fac,renaming)""" renamed factor fac is factor renaming is dictionary of the form {new:oldwhere old and new var variableswhere the variables in fac appear exactly once in the renaming ""factor __init__(self,[ for ( ,oin renami... |
18,935 | self vars_prev [ previous for in vars_nowself transition_factors transition_factors self init_factors init_factors self var_index {var_index[vis the index of variable for , in enumerate(vars_now)self var_index[ ]= here is variable dbnprobdbn py -(continued , variable_pair(" "domain=[false,true] , variable_pair(" "domai... |
18,936 | reasoning under uncertainty unrolling dbns probdbn py -(continued class bnfromdbn(beliefnetwork)"""belief network unrolled from dynamic belief network "" def __init__(self,dbn,horizon)"""dbn is the dynamic belief network being unrolled horizon> is the number of steps (so there will be horizon+ variables for each dbn va... |
18,937 | probdbn py -(continued class dbnvefilter(ve)def __init__(self,dbn)self dbn dbn self current_factors dbn init_factors self current_obs { def observe(selfobs)"""updates the current observations with obs obs is variable:value dictionary where variable is current variable ""assert all(self current_obs[var]==obs[varfor var ... |
18,938 | reasoning under uncertainty probdbn py -(continued #df dbnvefilter(dbn #df observe({ :true})df advance()df observe({ :false}#df query( # ( | , #df advance()df query( #dfa dbnvefilter(dbn_andfa observe({mic : mic : mic : }dfa advance(dfa observe({mic : mic : mic : }dfa query(pos_ causal models causal model can answer "d... |
18,939 | #probrc(bn_sprinkler_soffquery(shoes_wetshould be same as previous case #bn_sprinklerv querydo(seasonobs={sprinkler:"off"}#bn_sprinklerv querydo(seasondo={sprinkler:"off"}probdo py -(continued from probvariables import variable from probfactors import prob from probgraphicalmodels import boolean drug_prone variable("dr... |
18,940 | planning with uncertainty decision networks the decision network code builds on the representation for belief networks of we first allow for factors that define the utility here the utility is function of the variables in vars in utility table the utility is defined in terms of aa list that enumerates the values as in ... |
18,941 | planning with uncertainty decnnetworks py -(continued class decisionvariable(variable)def __init__(selfnamedomainparentsposition=none)variable __init__(selfnamedomainpositionself parents parents self all_vars set(parents{selfa decision network is graphical model where the variables can be random variables or decision v... |
18,942 | umbrella decision network weather forecast utility umbrella figure the umbrella decision network for par in self utility_factor variablesax annotate("utility"par positionxytext=self utility_factor positionarrowprops={'arrowstyle':'<-'},bbox=dict(boxstyle="sawtooth,pad= ha='center'for var in reversed(self topological_so... |
18,943 | planning with uncertainty umbrella decisionvariable("umbrella"["take""leave"]{forecast}position=( , ) p_weather prob(weather[][ ]p_forecast prob(forecast[weather][[ ][ ]]umb_utility utilitytable([weatherumbrella][[ ][ ]]position=( , ) umbrella_dn decisionnetwork("umbrella decision network"{weatherforecastumbrella}{p_we... |
18,944 | fire decision network tamper fire alarm smoke leaving chk_sm report utility see_sm call figure fire decision network f_lv prob(leaving,[alarm],[[ ][ ]]f_re prob(report,[leaving],[[ ][ ]]f_ss prob(see_sm,[chk_sm,smoke],[[[ , ],[ , ]],[[ , ],[ , ]]] ut utilitytable([chk_sm,fire,call],[[[ ,- ],[- ,- ]],[[- ,- ],[- ,- ]]]p... |
18,945 | planning with uncertainty cheat decision watched punish caught cheat_ caught cheat_ grade_ utility grade_ fin_grd figure cheating decision network punish variable("punish"["none","suspension","recorded"]position=( , )grade_ variable("grade_ "gradesposition=( , )grade_ variable("grade_ "gradesposition=( , )fin_grd varia... |
18,946 | ' ':{' ': ' ': ' ' ' ': }' ':{' ': ' ': ' ' ' ': }}' ':{' ':{' ': ' ': ' ' ' ': }' '{' ': ' ': ' ' ' ': }' ':{' ': ' ': ' ' ' ': }' ':{' ': ' ': ' ' ' ': }}' ':{' ':{' ': ' ': ' ' ' ': }' '{' ': ' ': ' ' ' ': }' ':{' ': ' ': ' ' ' ': }' ':{' ': ' ': ' ' ' ': }}' ':{' ':{' ': ' ': ' ' ' ': }' '{' ': ' ': ' ' ' ': }' ':{... |
18,947 | planning with uncertainty -chain utility figure decision network that is chain of decisions ch utilitytable([ ],[ , ]position=( / , ) ch decisionnetwork(" -chain"{ , , , , , , },{p_s ,p_s ,p_s ,p_s ,ch }#rc rc_dn(ch #rc optimize(#rc opt_policy recursive conditioning for decision networks an instance of rc_dn object tak... |
18,948 | gm is graphical model to query "" def __init__(self,gm=none)self gm gm self cache {(frozenset()frozenset()): #self max_display_level def optimize(selfsplit_order=none)"""computes expected utilityand creates optimal decision functionswhere elim_order is list of the non-observed non-query variables in gm ""if split_order... |
18,949 | planning with uncertainty self opt_policy[frozenset(context items())(var,thevalreturn maxres elsetotal for val in var domaintotal +self rc (dict_union({var:val},context)factorssplit_order[ :]self display( "rc branching on"var,"returning"totalreturn total we can combine the optimization for decision networks abovewith t... |
18,950 | elif len(comp :connected_components(contextfactorssplit_order) there are disconnected components self display( ,"splitting into connected components",compreturn(math prod(self rc(context, ,eofor ( ,eoin comp)elseassert split_orderf"split_order empty rc({context},{factors})var split_order[ self display( "rc branching on... |
18,951 | planning with uncertainty variable elimination for decision networks ve dn is variable elimination for decision networks the method optimize is used to optimize all the decisions note that optimize requires legal elimination ordering of the random and decision variablesotherwise it will give an exception ( decision nod... |
18,952 | def __init__(selfdvarfactor)"""dvar is decision variable factor is factor that contains dvar and only parents of dvar ""self dvar dvar self factor factor vars [ for in factor variables if is not dvarfactor __init__(self,varsself values [none]*self size self decision_fun factordf(dvar,vars,[none]*self size def get_value... |
18,953 | planning with uncertainty markov decision processes we will represent markov decision process (mdpdirectlyrather than using the recursive conditioning or variable elimination codeas we did for decision networks mdpproblem py -representations for markov decision processes from utilities import argmaxd import random impo... |
18,954 | def (self, , )" ( , )return 'healthy'{'relax' 'party' }'sick'{'relax' 'party' }}[ ][ def (self, , )"returns dictionary of { : such that ( , )= other probabilities are zero phealthy ('healthysa'healthy'{'relax' 'party' }'sick'{'relax' 'party' }}[ ][areturn {'healthy':phealthy'sick': -phealthythe next example is the tiny... |
18,955 | planning with uncertainty elif == return {( , ): ( , ): ( , + ): elseat ( , return {( , ): ( , ) def (self, , )( ,ys if ='right'return [ ,- ][xelif ='upc'return [- ,- ,- ][yelif ='left'if == return [- - ][yelsereturn elif ='upr'return [[- - ],[- - - ]][ ][yat ( , reward is * + *- = here is the domain of example of pool... |
18,956 | return ( - if else , def (self, , )"""return dictionary of { : if ( , )= other probabilities are zero corners are tricky because different actions result in same state ""if in self fling_statesreturn {( , ) (self x_dim- , ): ( ,self y_dim- ): (self x_dim- ,self y_dim- ): res dict(for ai in self actionss self intended_n... |
18,957 | planning with uncertainty """carries out iterations of value iterationupdating value function self returns -functionvalue functionpolicy ""print("calling vi"assert > ,"you must carry out at least one iteration of vi ="+str( # if is not none else { : for in self statesfor in range( )self { {aself ( , )+self discount*sum... |
18,958 | stepb button(plt axes([ , , , ])"step"stepb on_clicked(self on_stepresetb button(plt axes([ , , , ])"reset"resetb on_clicked(self on_resetself qcheck checkbuttons(plt axes([ , , , ])["show -values","show policy"]self qcheck on_clicked(self show_valsself show_vals(noneplt show( def show_vals(self,event)self ax cla(array... |
18,959 | planning with uncertainty - show -values show policy reset step figure interface for tiny exampleafter number of steps each rectangle represents state in each rectangle are the -values for the state the leftmost number is the for the left actionthe rightmost number is for the right actionthe upper most is for the upr (... |
18,960 | resizing itchecking "show -valuesand "show policy"and clicking "stepa few times exercise computing before may seem like waste of space because we don' need to store in order to compute value function or the policy change the algorithm so that it loops through the states and actions once per iterationand only stores the... |
18,961 | planning with uncertainty - - - - - - - - - - - - - - - - show -values show policy reset step figure interface for grid exampleafter number of steps each rectangle represents state in each rectangle are the -values for the state the leftmost number is the for the left actionthe rightmost number is for the right actiont... |
18,962 | which states have had their -values change the mostand then update the previous onesbut that is not so straightforward to implementbecause you need to find those previous states version june |
18,963 | learning with uncertainty -means the -means learner maintains two lists that suffice as sufficient statistics to classify examplesand to learn the classificationclass counts is list such that class counts[cis the number of examples in the training set with class feature sum is list such that feature sum[ ][cis sum of t... |
18,964 | learning with uncertainty class_counts[cis the number of examples with class= self class_counts [ ]*self num_classes feature_sum[ ][cis the sum of the values of feature for class self feature_sum [[ ]*self num_classes for feat in self dataset input_featuresfor eg in self dataset traincl random randrange(self num_classe... |
18,965 | new_class_counts [ ]*self num_classes feature_sum[ ][cis the sum of the values of feature for class new_feature_sum [[ ]*self num_classes for feat in self dataset input_featuresfor eg in self dataset traincl self class_of_eg(egnew_class_counts[cl+ for (ind,featin enumerate(self dataset input_features)new_feature_sum[in... |
18,966 | learning with uncertainty test_errors [for in range(maxstep)self learn( train_errors appendsum(self distance(self class_of_eg(eg),egfor eg in self dataset train/len(self dataset train)if self dataset testtest_errors appendsum(self distance(self class_of_eg(eg),egfor eg in self dataset test/len(self dataset test)plt plo... |
18,967 | (ainitialize the classes with actual examplesso that the classes will not start empty (do the classes become empty?(bin class predictionwe test whether the code is emptyand make prediction of for an empty class it is possible to make different prediction to "stealan example (but you should make sure that class has cons... |
18,968 | learning with uncertainty learnem py -(continued def em_step(selforig_class_countsorig_feature_counts)"""updates the model ""class_counts [ ]*self num_classes feature_counts [{val:[ ]*self num_classes for val in feat frangefor feat in self dataset input_featuresfor tple in self dataset trainif orig_class_countsa model ... |
18,969 | def learn(self, )"""do steps of em""for in range( )self class_counts,self feature_counts self em_step(self class_counts self feature_countsthe following is for visualizing the classes it prints the dataset ordered by the probability of class learnem py -(continued def show_class(self, )"""sorts the data by the class an... |
18,970 | learning with uncertainty for in range(self num_classes)res +prod(fc[ ][feat(tple)][cfor ( ,featin enumerate(feats))/(cc[ ]**(len(feats)- )if res> return -math log (res/len(self dataset train)elsereturn float("inf"#infinity def plot_error(selfmaxstep= )"""plots the logloss error as function of the number of steps""plt ... |
18,971 | print("class assignment after",num_iter,"iterations:"eml learn(num_iter)eml show_class( plot the error em =em_learner(data, )em plot_error( classes em =em_learner(data, )em plot_error( classes em =em_learner(data, )em plot_error( classes data data_from_file('data/carbool csv'target_index= ,boolean_features=false[ frang... |
18,972 | reinforcement learning representing agents and environments when the learning agent does an action in the environmentit observes (staterewardpair from the environment the state is the world statethis is the fully observable assumption an rl environment implements do(actionmethod that returns (staterewardpair rlproblem ... |
18,973 | reinforcement learning def do(selfaction)"""updates the state based on the agent doing action returns state,reward ""if self state=="healthy"if action=="party"self state "healthyif flip( else "sickreward elseaction=="relaxself state "healthyif flip( else "sickreward elseself state=="sickif action=="party"self state "he... |
18,974 | figure monster game return self statereward def pick_from_dist(dist,values)"" pick_from_dist([ , , ],[' ',' ',' ']should pick 'awith probability etc ""ran random random( = while ran>dist[ ]ran -dist[ii + return values[isimple game this is for the game depicted in figure rlsimpleenv py -simple game import random from ut... |
18,975 | reinforcement learning prize_locs [( , )( , )( , )( , )prize_apears_prob prize_reward monster_locs [( , )( , )( , )( , )( , )monster_appears_prob monster_reward_when_damaged - repair_stations [( , ) actions ["up","down","left","right" def __init__(self)stateself self self damaged false self prize none statistics self n... |
18,976 | elseself +- elif actual_direction ="up"if self ==self ydim- reward +self crashed_reward elseself + elif actual_direction ="down"if self == reward +self crashed_reward elseself +- elseraise runtimeerror("unknown_direction "+str(direction) monsters if (self ,self yin self monster_locs and flip(self monster_appears_prob)i... |
18,977 | reinforcement learning steps_explore= steps_exploit= xscale='linear')""plots the agent ag label is the label for the plot yplot is 'averageor 'totalstep_size is the number of steps between each point plotted steps_explore is the number of steps the agent spends exploring steps_exploit is the number of steps the agent s... |
18,978 | learning to run the -learning demoin folder "aipython"load "rlqtest py"and copy and paste the example queries at the bottom of that file this assumes python rlqlearner py - learning import random from display import displayable from utilities import argmaxeflip class rl_agent(displayable)"""an rl_agent has percepts (sr... |
18,979 | reinforcement learning self discount discount self explore explore self fixed_alpha fixed_alpha self alpha alpha self alpha_fun alpha_fun self qinit qinit self label label self restart(restart is used to make the learner relearn everything this is used by the plotter to create new plots rlqlearner py -(continued def re... |
18,980 | given the stateand the -function ""if flip(self explore)return random choice(self actionselsereturn argmaxe((next_actself get((statenext_act),self qinit)for next_act in self actionsexercise implement soft-max action selection choose temperature that works well for the domain explain how you picked this temperature comp... |
18,981 | reinforcement learning agt q_learner(envt agt do( from rlsimpleenv import simple_game_env senv simple_game_env(sag q_learner(senv, ,explore= ,fixed_alpha=true,alpha= plot_rl(sag ,steps_explore= ,steps_exploit= ,label="alpha="+str(sag alpha)sag q_learner(senv, ,explore= ,fixed_alpha=falseplot_rl(sag ,steps_explore= ,ste... |
18,982 | q_learner __init__(selfenvdiscountexplorefixed_alphaalphaalpha_funqinitlabelself experience_buffer boundedbuffer(max_buffer_sizeself num_updates_per_action num_updates_per_action self burn_in burn_in def do(self,num_steps= )"""do num_steps of interaction with the environment""self display( ," \ta\tr\ts'\tq"alpha self a... |
18,983 | reinforcement learning plot_rl(sag ar,steps_explore= ,steps_exploit= ,label="ar alpha="+str(sag ar alpha)sag ar q_ar_learner(senv, ,explore= ,fixed_alpha=falseplot_rl(sag ar,steps_explore= ,steps_exploit= ,label="ar alpha= / "sag ar q_ar_learner(senv, ,explore= ,fixed_alpha=false,alpha_fun=lambda : /( + )plot_rl(sag ar... |
18,984 | rlmodellearner py -model-based reinforcement learner import random from rlqlearner import rl_agent from display import displayable from utilities import argmaxeflip class model_based_reinforcement_learner(rl_agent)""" model-based reinforcement learner "" def __init__(selfenvdiscountexplore= qinit= updates_per_step= lab... |
18,985 | reinforcement learning pst self state previous state action self select_action(pstself state,reward self env do(actionself acc_rewards +reward self [(pst,action,self state)self get((pstaction,self state), )+ if (pst,actionin self visitsself visits[(pst,action)+ self [(pst,action)+(reward-self [(pst,action)])/self visit... |
18,986 | exercise it is possible to implement the model-based reinforcement learner by replacing qrvisitsres states with single dictionary that returns tuple (qrvtmwhere qr and are numbersand tm is map from resulting states into counts does this make the algorithm easier to understanddoes this make the algorithm more efficiente... |
18,987 | reinforcement learning - damaged and prize ahead if and else not damaged and prize ahead if not and else features [ , , , , , , , , , the next features are for prize locations and distances from outside in all directions for pr in simple_game_env prize_locs+[none]if ==prfeatures +[ -xy -yelsefeatures +[ fp feature for ... |
18,988 | return elif action ="upand ==simple_game_env ydim- return elif action ="downand == return elsereturn def towards_prize( , ,action, )"""action goes in the direction of the prize from ( , )""if is nonereturn elif ==( , )take into account the wall near the top-left prize if action ="leftand ( > or == and < )return elif ac... |
18,989 | reinforcement learning def simp_features(state,action)"""returns list of feature values for the state-action pair ""assert action in simple_game_env actions ( , , ,pstate would go to monster monster_ahead( , ,actionf would crash into wall wall_ahead( , ,actionf action is towards prize towards_prize( , ,action,preturn [... |
18,990 | self get_features get_features self actions env actions self discount discount self explore explore self step_size step_size self winit winit self label label self restart(restart(is used to make the learner relearn everything this is used by the plotter to create new plots rlfeatures py -(continued def restart(self)""... |
18,991 | reinforcement learning if flip(self explore)return random choice(self actionselsereturn argmaxe((next_actdot_product(self weightsself get_features(state,next_act))for next_act in self actions def show_actions(self,state=none)"""prints the value for each action in state this may be useful for debugging ""if state is non... |
18,992 | (csuppose your goal was to have the best accumulated reward after , steps you are allowed to change the exploration rate at fixed number of steps for each of the methodswhich is the best position to start exploiting morewhich method is betterwhat if you wanted to have the best reward after , or , stepsbased on this evi... |
18,993 | reinforcement learning next_state,reward self env do(self actionself add_to_buffer((self state,self action,reward,next_state)#remember experience self acc_rewards +reward next_action self select_action(next_statefeature_values self get_features(self state,self actionoldq dot_product(self weightsfeature_valuesnextq dot_... |
18,994 | multiagent systems minimax here we consider two-player zero-sum games here player only wins when another player loses this can be modeled as where there is single utility which one agent (the maximizing agentis trying minimize and the other agent (the minimizing agentis trying to minimize creating two-player game maspr... |
18,995 | multiagent systems def children(self)"""returns the list of all children ""return self allchildren def evaluate(self)"""returns the evaluation for this node if it is leaf""return self value the following gives the tree from figure of the book note how is used as value herebut never appears in the trace masproblem py -(... |
18,996 | figure magic square of tic-tac-toe played on the magic square note that we do not remove symmetries (what are the symmetrieshow do the symmetries of tic-tac-toe translate here?masproblem py -(continued class magic_sum(node)def __init__(selfxmove=truelast_move=noneavailable=[ , , , , , , , , ] =[] =[])"""this is node in... |
18,997 | multiagent systems self xo self +[sel]for sel in self availablereturn self allchildren def isleaf(self)""" leaf has no numbers available or is win for one of the players we only need to check for win for if it is currently ' turnand only check for win for if it is ' turn (otherwise it would have been win earlier""retur... |
18,998 | return max_score,max_path elsemin_score float("inf"min_path none for in node children()score,path minimax( ,depth+ if score min_scoremin_score score min_path name,path return min_score,min_path the following is depth-first minimax with - pruning it returns the value for node as well as best path for the agents masminim... |
18,999 | multiagent systems masminimax py -(continued from masproblem import fig magic_sumnode node max_display_level= print detailed trace minimax_alpha_beta(fig - , minimax_alpha_beta(magic_sum()- , #to see how much time alpha-beta pruning can save over minimaxuncomment the following#import timeit #timeit timer("minimax(magic... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.