id
int64
0
25.6k
text
stringlengths
0
4.59k
18,800
reasoning with constraints from cspexamples import test_csp def sls_solver(csp,prob_best= )"""stochastic local searcher (prob_best= )""se slsearcher(cspse search( ,prob_bestreturn se current_assignment def any_conflict_solver(csp)"""stochastic local searcher (any-conflict)""return sls_solver(csp, if __name__ ="__main__...
18,801
class softconstraint(constraint)""" constraint consists of scopea tuple of variables functiona real-valued function that can applied to tuple of values stringa string for printing the constraints all of the strings must be unique for the variables ""def __init__(selfscopefunctionstring=noneposition=none)constraint __in...
18,802
reasoning with constraints branch-and-bound search here we specialize the branch-and-bound algorithm (section on page cspsoft py -(continued from display import displayablevisualize import math class df_branch_and_bound_opt(displayable)"""returns branch and bound searcher for problem an optimal assignment with cost les...
18,803
for val in var domainself cbsearch({var:val}|asstnewcostrem_cons bnb df_branch_and_bound_opt(scsp bnb max_display_level= show more detail bnb optimize(version june
18,804
propositions and inference representing knowledge bases clause consists of head (an atomand body body is represented as list of atoms atoms are represented as strings logicproblem py -representations logics class clause(object)""" definite clause"" def __init__(self,head,body=[])"""clause with atom head and lost of ato...
18,805
propositions and inference self atom=atom def __str__(self)"""returns the string representation of clause ""return "askable self atom def yes(ans)"""returns true if the answer is yes in some form""return ans lower(in ['yes''yes ''oui''oui '' '' 'bilingual knowledge base is list of clauses and askables in order to make ...
18,806
clause('i_am'['i_think'])clause('i_think')clause('i_smell'['i_exist']]here is representation of the electrical domain of the textbooklogicproblem py -(continued elect kb(clause('light_l ')clause('light_l ')clause('ok_l ')clause('ok_l ')clause('ok_cb ')clause('ok_cb ')clause('live_outside')clause('live_l '['live_w '])cl...
18,807
propositions and inference clause('live_w '['live_w ''ok_cb '])clause('light_l ')clause('live_w '['live_outside'])clause('lit_l '['light_l ''live_l ''ok_l '])clause('lit_l '['light_l ''live_l ''ok_l '])clause('live_l '['live_w '])clause('live_w '['up_s ','live_w '])clause('live_w '['down_s ','live_w '])clause('live_w '...
18,808
""fp ask_askables(kbadded true while addedadded false added is true when an atom was added to fp this iteration for in kb clausesif head not in fp and all( in fp for in body)fp add( headadded true kb display( , head,"added to fp due to clause",creturn fp def ask_askables(kb)return {at for at in kb askables if yes(input...
18,809
propositions and inference exercise it is possible to be asymptotically more efficient (in terms of the number of elements in bodythan the method in the previous question by noticing that each element of the body of clause only needs to be checked once for examplethe clause dneeds only be considered when is added to fp...
18,810
exercise this code can re-ask question multiple times implement this code so that it only asks question once and remembers the answer also implement function to forget the answers exercise what search method is this usingimplement the search interface so that it can use aor other searching methods define an admissible ...
18,811
propositions and inference proofs append(proof_atreturn proofs the following provides simple unit test that is hard wired for triv_kblogicexplain py -(continued from logicproblem import triv_kb def test() prove_atom(triv_kb,'i_am'assert "triv_kb proving i_am gave "+str( prove_atom(triv_kb,'i_smell'assert =="fail""triv_...
18,812
trycommand inps[ if command ="quit"going false elif command ="ask"proof prove_atom(kbinps[ ]if proof ="fail"print("fail"elseprint("yes"elif command ="how"if proof=="fail"print("there is no proof"elif len(inps)== print_rule(proofelsetryups append(proofproof proof[ ][int(inps[ ])#nth argument of rule print_rule(proofexce...
18,813
propositions and inference try interact(electwhich clause is wrong in elect_bugtryinteract(elect_buglogicexplainask lit_l the following shows an interaction for the knowledge base electinteract(electlogicexplainask lit_l is up_s trueno is down_s trueyes is down_s trueyes yes logicexplainhow lit_l < light_l live_l ok_l ...
18,814
assumables atom can be made assumable by including assumable(ain the knowledge base knowledge base that can include assumables is declared with kba logicassumables py -definite clauses with assumables from logicproblem import clauseaskablekbyes class assumable(object)"""an askable atom"" def __init__(self,atom)"""claus...
18,815
propositions and inference for cl in self clauses_for_atom(selectedfor ass in self prove_all_ass(cl body+ans_body[ :],assumedunion of answers for each clause with head=selected elseempty body return [assumedone answer def conflicts(self)"""returns list of minimal conflicts""return minsets(self prove_all_ass(['false'])g...
18,816
clause('light_l ')assumable('ok_l ')assumable('ok_l ')assumable('ok_s ')assumable('ok_s ')assumable('ok_s ')assumable('ok_cb ')assumable('ok_cb ')assumable('live_outside')clause('live_l '['live_w '])clause('live_w '['up_s ','ok_s ','live_w '])clause('live_w '['down_s ','ok_s ','live_w '])clause('live_w '['up_s ''ok_s '...
18,817
propositions and inference ative deepening on the number of assumptionsgenerating conflicts and explanations togetherand pruning as early as possible version june
18,818
planning with certainty representing actions and planning problems the strips representation of an action consists ofthe name of the action preconditionsa dictionary of feature:value pairs that specifies that the feature must have this value for the action to be possible effectsa dictionary of feature:value pairs that ...
18,819
planning with certainty self name name self preconds preconds self effects effects self cost cost def __repr__(self)return self name strips domain consists ofa set of actions dictionary that maps each feature into set of possible values for the feature list of the actions stripsproblem py -(continued class strips_domai...
18,820
coffee shop (cs sam' office (off lab (labmail room (mr features to describe states actions rloc rob' location mc rhc rob has coffee mcc move counterclockwise swc sam wants coffee puc pickup coffee mw mail is waiting dc deliver coffee rhm rob has mail pum pickup mail dm move clockwise deliver mail figure robot delivery ...
18,821
planning with certainty move( , ,ac move( , ,tablea figure blocks world with two actions problem planning_problem(delivery_domain{'rloc':'lab''mw':true'swc':true'rhc':false'rhm':false}{'rloc':'off'}problem planning_problem(delivery_domain{'rloc':'lab''mw':true'swc':true'rhc':false'rhm':false}{'swc':false}problem planni...
18,822
to handle parameterized actions (which depend on the blocks involved)the actions and the features are all stringscreated for the all combinations of the blocks note that we treat moving to block separately from moving to the tablebecause the blocks needs to be clearbut the table always has room for another block strips...
18,823
planning with certainty figure blocks problem blocks tower {clear(' '):trueon(' '):' 'clear(' '):falseon(' '):' 'clear(' '):falseon(' '):' 'clear(' '):falseon(' '):'table'blocks planning_problem(blocks domtower initial state {on(' '):' ',on(' '):' ',on(' '):' '}#goal the problem blocks is to move the bottom block to th...
18,824
in forward plannera node is state state consists of an assignmentwhich is variable:value dictionary in order to be able to do multiple-path pruningwe need to define hash functionand equality between states stripsforwardplanner py -forward planner with strips actions from searchproblem import arcsearch_problem from stri...
18,825
planning with certainty for prop in self goal def start_node(self)"""returns start node""return self initial_state def neighbors(self,state)"""returns neighbors of state in this problem""return arc(stateself effect(act,state assignment)act costactfor act in self prob_domain actions if self possible(act,state assignment...
18,826
defining heuristics for planner each planning domain requires its own heuristics if you change the actionsyou will need to reconsider the heuristic functionas there might then be lower-cost pathwhich might make the heuristic non-admissible here is an example of defining (not very goodheuristic for the coffee delivery p...
18,827
planning with certainty stripsheuristic py -(continued def maxh(*heuristics)"""returns new heuristic function that is the maximum of the functions in heuristics heuristics is the list of arguments which must be heuristic functions ""return lambda state,goalmax( (state,goalfor in heuristicsdef newh(state,goal)return max...
18,828
regression planning to run the demoin folder "aipython"load "stripsregressionplanner py"and copy and paste the commentedout example queries at the bottom of that file in regression planner node is subgoal that need to be achieved subgoal object consists of an assignmentwhich is variable:value dictionary we make it hash...
18,829
planning with certainty def is_goal(selfsubgoal)"""if subgoal is true in the initial statea path has been found""goal_asst subgoal assignment return all(self initial_state[ ]==goal_asst[gfor in goal_asst def start_node(self)"""the start node is the top-level goal""return self top_goal def neighbors(self,subgoal)"""retu...
18,830
the heuristic is an (under)estimate of the cost of going from the initial state to subgoal ""return self heur(self initial_statesubgoal assignmentstripsregressionplanner py -(continued from searchbranchandbound import df_branch_and_bound from searchmpp import searchermpp from stripsproblem import problem problem proble...
18,831
planning with certainty def test_regression_heuristic(thisproblem=problem )print("\ ****regression no heuristic"print(searchermpp(regression_strips(thisproblem)search() print("\ ****regression with heuristics and "print(searchermpp(regression_strips(thisproblem,maxh( , ))search() if __name__ ="__main__"test_regression_...
18,832
for (feat,domin prob_domain feature_domain_dict items() initial state constraintsconstraints [constraint((feat_time_var[feat][ ],)is_(val)for (feat,valin initial_state items() goal constraints on the final stateconstraints +[constraint((feat_time_var[feat][number_stages],)is_(val)for (feat,valin goal items() preconditi...
18,833
planning with certainty and is ( )( returns false note that the underscore ('is part of the namehere we use it as the convention that it is function that returns function this uses two different styles to define is and if returning function defined by lambda is equivalent to returning the embedded functionexcept that t...
18,834
from stripsproblem import delivery_domain from cspconsistency import search_with_ac_from_cspcon_solver from stripsproblem import planning_problemproblem problem problem blocks blocks blocks problem con_plan(problem , should it succeedcon_plan(problem , should it succeedcon_plan(problem , should it succeedto use search ...
18,835
planning with certainty partial order planner maintains partial order of action instances an action instance consists of name and an index we need action instances because the same action could be carried out at different times stripspop py -partial-order planner using strips representation from searchproblem import ar...
18,836
actions is set of action instances constraints set of ( , pairsrepresenting < closed under transitivity agenda list of (subgoal,actionpairs to be achievedwhere subgoal is (variable,valuepair causal_links is set of ( , , tripleswhere ai are action instancesand is (variable,valuepair ""self actions actions set of action ...
18,837
planning with certainty search_problem __init__(selfself planning_problem planning_problem self start action_instance("start"self finish action_instance("finish" def is_goal(selfnode)return node agenda =[ def start_node(self)constraints {(self startself finish)agenda [(gself finishfor in self planning_problem goal item...
18,838
new_cls node causal_links [new_clinkfor consts in self protect_all_cls(node causal_links,new_a,consts )for consts in self protect_cl_for_actions(node actions,consts ,new_clink)yield arc(nodepop_node(new_actions,consts ,new_agenda ,new_cls)cost= given casual link ( subgoala )the following method protects the causal link...
18,839
planning with certainty ( ,cond, clinks[ select causal link rem_clinks clinks[ :remaining causal links if act ! and act ! and self deletes(act,cond)if self possible((act, ),constrs)new_const self add_constraint((act, ),constrsfor in self protect_all_cls(rem_clinks,act,new_const)yield if self possible(( ,act),constrs)ne...
18,840
return const todo [pairnewconst const copy(while todox , todo pop(newconst add(( , )for , in newconstif == and ( ,ynot in newconsttodo append(( , )if == and ( , not in newconsttodo append(( , )return newconst def possible(self,pair,constraint)( ,ypair return ( ,xnot in constraint some code for testingstripspop py -(con...
18,841
supervised machine learning this is the first on machine learning it covers the following topicsdatahow to load ittraining and test sets featuresmany of the features come directly from the data sometimes it is useful to construct featurese height might be boolean feature constructed from the real-values feature height ...
18,842
supervised machine learning dataset spect iris carbool holiday mail reading simp regr examples #columns input types boolean real categorical/real boolean boolean numerical target type boolean categorical real boolean boolean numerical figure some of the datasets used here mlr is uci machine learning repository represen...
18,843
ds target the feature corresponding to the target ( function as described aboveds input_features list of the input features learnproblem py -(continued class data_set(displayable)"" data set consists of list of training data and list of test data "" def __init__(selftraintest=noneprob_test= target_index= header=nonetar...
18,844
supervised machine learning self create_features(if target_typeself target ftype target_type self display( ,"there are",len(self input_features),"input features" def __str__(self)if self train and len(self train)> return ("data"+str(len(self train))+training examples+str(len(self test))+test examples+str(len(self train...
18,845
elsereturn "categoricalcreating boolean conditions from features some of the algorithms require boolean input features or features with range { in order to be able to use these algorithms on datasets that allow for arbitrary domains of input variableswe construct boolean conditions from the attributes there are caseswh...
18,846
supervised machine learning if self headerfeat __doc__ "{self header[ind]}=={true_val}elsefeat __doc__ " [{ind}]=={true_val}feat frange boolean feat ftype "booleanconds append(featelif all(isinstance(val,(int,float)for val in frange)if categorical_onlynumericaldon' make cuts def feat(ei=ind)return [ifeat __doc__ " [{in...
18,847
sure that each of the resulting domains is of equal size exercise this splits on whether the feature is less than one of the values in the training set sam suggested it might be better to split between the values in the training setand suggested using cutat (sorted frange[cutsorted frange[cut ])/ why might sam have sug...
18,848
supervised machine learning the prediction is either real value or {value probabilitydictionary or list the actual is either real number or key of the prediction learnproblem py -(continued class evaluate(object)""" container for the evaluation measures"" def squared_loss(predictionactual)"squared loss if isinstance(pr...
18,849
of the data equal to prob test [an alternative is to use random sample(which can guarantee that the test set will contain exactly particular proportion of the data however this would require knowing how many elements are in the data setwhich we may not knowas data may just be generator of the data ( when reading the da...
18,850
supervised machine learning """create dataset from file separator is the character that separates the attributes num_train is number specifying the first num_train tuples are trainingor none prob_test is the probability an example should in the test set (if num_train is nonehas_header is true if the first line of file ...
18,851
ferent files learnproblem py -(continued class data_from_files(data_set)def __init__(selftrain_file_nametest_file_nameseparator=','has_header=falsetarget_index= boolean_features=truecategorical=[]target_typenoneinclude_only=none)"""create dataset from separate training and file separator is the character that separates...
18,852
supervised machine learning when reading from file all of the values are strings this next method tries to convert each values into number (an int or floator booleanif it is possible learnproblem py -(continued def interpret_elements(str_list)"""make the elements of string list str_list numerical if possible otherwise ...
18,853
""self orig_dataset dataset self unary_functions unary_functions self binary_functions binary_functions self include_orig include_orig self target dataset target data_set __init__(self,dataset traintest=dataset testtarget_index dataset target_index def create_features(self)if self include_origself input_features self o...
18,854
supervised machine learning return ( )* (efeat __doc__ __doc__+"*"+ __doc__ return feat def eq_feat( , )""" new feature that is if and give same value ""def feat( )return if ( )== (eelse feat __doc__ __doc__+"=="+ __doc__ return feat def neq_feat( , )""" new feature that is if and give different values ""def feat( )ret...
18,855
def learn(self)"""returns predictora function from tuple to value for the target feature ""raise notimplementederror("learn"abstract method learning with no input features if we make the same prediction for each examplewhat prediction should we makethis can be used as naive baselineif more sophisticated method does not...
18,856
supervised machine learning learnnoinputs py -learning ignoring all input features from learnproblem import evaluate import mathrandomcollectionsstatistics import utilities argmax for (element,valuepairs class predict(object)"""the class of prediction methods for list of values please make the doc strings the same leng...
18,857
def rmean(datadomain=[ , ]mean = pseudo_count= )"regularized meanreturns real number mean is the mean to be used for data points with mean = pseudo_count= same as laplace for [ , data this works for enumerations as well as lists sum mean pseudo_count count pseudo_count for in datasum + count + return sum/count def mode...
18,858
supervised machine learning results {predictor{error_measure for error_measure in error_measuresfor predictor in predict allfor sample in range(num_samples)prob random random(training [ if random random()<prob else for in range(train_size)test [ if random random()<prob else for in range(test_size)for predictor in predi...
18,859
decision tree learning to run the decision tree learning demoin folder "aipython"load "learndt py"using ipython - learndt pyand it prints some test results to try more examplescopy and paste the commentedout commands at the bottom of that file this requires python with matplotlib the decision tree algorithm does binary...
18,860
supervised machine learning it only splits if the best split increases the error by at least gamma this implies it does not split whenthere are no more input features there are fewer examples than min number examplesall the examples agree on the value of the targetor the best split makes all examples in the same partit...
18,861
felse {false_tree __doc__})"fun num_leaves true_tree num_leaves false_tree num_leaves return fun learndt py -(continued def leaf_value(selfegsdomain)return self leaf_prediction((self target(efor in egs)domain def select_split(selfconditionsdata_subset)"""finds best feature to split on conditions is non-empty list of fe...
18,862
supervised machine learning return error def partition(data_subset,feature)"""partitions the data_subset by the feature""true_examples [false_examples [for example in data_subsetif feature(example)true_examples append(exampleelsefalse_examples append(examplereturn false_examplestrue_examples test caseslearndt py -(cont...
18,863
#data data_from_file('data/holiday csv'num_train= target_index=- )print("holiday csv"testdt(dataprint_tree=falsenote that different runs may provide different values as they split the training and test sets differently so if you have hypothesis about what works bettermake sure it is true for different runs exercise the...
18,864
supervised machine learning the above decision tree overfits the data one way to determine whether the prediction is overfitting is by cross validation the code below implements -fold cross validationwhich can be used to choose the value of parameters to best fit the training data if we want to use parameter tuning to ...
18,865
def validation_error(selflearnererror_measure**other_params)error tryfor in range(self num_folds)predictor learner(selftrain=list(self fold_complement( ))**other_paramslearn(error +sumerror_measure(predictor( )self target( )for in self fold( )except valueerrorreturn float("inf"#infinity return error/len(self datathe pl...
18,866
supervised machine learning data data_from_file('data/spect csv',target_index= seed= plot_error(datawarningmay take long time depending on the dataset #also trydata data_from_file('data/mail_reading csv'target_index=- data data_from_file('data/carbool csv'target_index=- seed= plot_error(datacriterion=evaluate log_lossl...
18,867
self input_features [one]+dataset input_features one is defined below self weights {feat:random uniform(-max_init,max_initfor feat in self input_featurespredictor predicts the value of an example from the current parameter settings predictor string gives string representation of the predictor learnlinear py -(continued...
18,868
supervised machine learning sigmoid(xis the function - the inverse of sigmoid is the logit function learnlinear py -(continued def sigmoid( )return /( +math exp(- ) def logit( )return -math log( / - sigmoid([ ]returns [ where vi exp(xi exp(xj the inverse of sigmoid is the logit function learnlinear py -(continued def s...
18,869
print("function learned is"learner predictor_string()for ecrit in evaluate all_criteriatest_error data evaluate_dataset(data testlearner predictorecritprint(average"ecrit __doc__"is"test_errorthe following plots the errors on the training and test sets as function of the number of steps of gradient descent learnlinear ...
18,870
supervised machine learning "test error:",test_errors[- ]learner learn(num_iter=stepplt plot(range( ,num_steps+ ,step),train_errors,ls='-',label=legend_label+"training"plt plot(range( ,num_steps+ ,step),test_errors,ls='--',label=legend_label+"test"plt legend(plt draw(learner display( "train error:",train_errors[- ]"tes...
18,871
learner linear_learner(datasquashed=falselearner learning_rate= learner learn( learner learning_rate= learner learn( learner learning_rate= learner learn( learner display( ,"function learned is"learner predictor_string()"error=",data evaluate_dataset(data trainlearner predictorevaluate squared_loss)plt plot([ [ for in ...
18,872
supervised machine learning col colors[degree len(colors)plt plot(x_values,[learner predictor([ ]for in x_values]linestyle=lscolor=collabel="degree="+str(degree)plt legend(loc='upper left'plt draw( trydata data_from_file('data/simp_regr csv'prob_test= boolean_features=falsetarget_index=- plot_prediction(data plot_polyn...
18,873
from learnlinear import plot_steps from learnproblem import data_from_file data data_from_file('data/holiday csv'target_index=- learner linear_learner_bsgd(dataplot_steps(learner learnerdata=data to plot polynomials with batching (compare to sgdfrom learnlinear import plot_polynomials plot_polynomials(datalearner_class...
18,874
supervised machine learning def conditions(self*argscolsample_bytree= **nargs)conds self base_dataset conditions(*args**nargsreturn random sample(condsint(colsample_bytree*len(conds)) boosting learner takes in dataset and base learnerand returns new predictor the base learnertakes datasetand returns learner object lear...
18,875
learnboosting py -(continued testing from learndt import dt_learner from learnproblem import data_setdata_from_file def sp_dt_learner(split_to_optimize=evaluate squared_lossleaf_prediction=predict mean,**nargs)"""creates learner with different default arguments replaced by **nargs ""def new_learner(dataset)return dt_le...
18,876
supervised machine learning plt plot(range(steps+ )learner errorsnext(markers)label= "min_child_weight={mcw}gamma={gamma}"plt legend(plt draw( plot_boosting_trees(datagradient tree boosting the following implements gradient boosted trees for classification if you want to use this gradient tree boosting for real problem...
18,877
return sigmoid(sum( (examplefor in self trees)+extra def leaf_value(selfegsdomain=[ , ])"""value at the leaves for examples egs domain argument is ignored""pred_acts [(self gtb_predictor( ),self target( )for in egsreturn sum( - for ( ,ain pred_acts/(sum( *( -pfor ( ,ain pred_acts)+self lambda_reg def sum_losses(selfdat...
18,878
neural networks and deep learning warningthis is not meant to be an efficient implementation of deep learning if you want to do serious machine learning on meduim-sized or large datawe would recommend keras ((arehoweverblack boxes the aipython neural network code should be seen like car engine made of glassyou can see ...
18,879
neural networks and deep learning """given list of inputsoutputs will produce list of length num_outputs nn is the neural network this layer is part of num outputs is the number of outputs for this layer ""self nn nn self num_inputs nn num_outputs output of nn is the input to this layer if num_outputsself num_outputs n...
18,880
""" completely connected layer""def __init__(selfnnnum_outputslimit=none)""" completely connected linear layer nn is neural network that the inputs come from num_outputs is the number of outputs the random initialization of parameters is in range [-limit,limit""layer __init__(selfnnnum_outputsif limit is nonelimit =mat...
18,881
neural networks and deep learning learnnn py -(continued class relu_layer(layer)"""rectified linear unit (reluf(zmax( zthe number of outputs is equal to the number of inputs ""def __init__(selfnn)layer __init__(selfnn def output_values(selfinput_valuestraining=false)"""returns the outputs for the input values it rememb...
18,882
def __init__(selfdatasetvalidation_proportion learning_rate= )"""creates neural network for datasetlayers is the list of layers ""self dataset dataset self output_type dataset target ftype self learning_rate learning_rate self input_features dataset input_features self num_outputs len(self input_featuresvalidation_num ...
18,883
neural networks and deep learning num_iter is the number of iterations over the batches overrides epochs if provided (allows for fractions of epochsreport_each means give the errors after each multiple of that iterations ""self batch_size min(batch_sizelen(self training_set)don' have batches bigger than training size i...
18,884
""" completely connected layer""def __init__(selfnnnum_outputslimit=nonealpha= epsilon - vel = )""" completely connected linear layer nn is neural network that the inputs come from num_outputs is the number of outputs max_init is the maximum value for random initialization of parameters vel is the initial velocity for ...
18,885
neural networks and deep learning for inp in range(self num_inputs+ )gradient self delta[out][inpself nn batch_size self ms[out][inpself rho*self ms[out][inp]( -self rhogradient** self weights[out][inp-self nn learning_rate/(self ms[out][inp]+self epsilon)** gradient self delta[out][inp dropout dropout is implemented a...
18,886
self rate rate layer __init__(selfnn def output_values(selfinput_valuestraining=false)"""returns the outputs for the input values it remembers the input values for the backprop ""if trainingscaling /( -self rateself outputs[ if flip(self rateelse inp*scaling make with probability rate for inp in input_valuesreturn self...
18,887
neural networks and deep learning nn do add_layer(linear_complete_layer(nn do, )#nn add_layer(sigmoid_layer(nn )comment this or the next nn do add_layer(relu_layer(nn do)nn do add_layer(dropout_layer(nn dorate= )#nn add_layer(linear_complete_layer(nn do, )when using output_type="booleannn do add_layer(linear_complete_l...
18,888
learnnn py -(continued from learnlinear import plot_steps from learnproblem import evaluate to show plotsplot_steps(learner nn data datacriterion=evaluate log_lossnum_steps= log_scale=falselegend_label="nn "plot_steps(learner nn data datacriterion=evaluate log_lossnum_steps= log_scale=falselegend_label="nn "plot_steps(...
18,889
neural networks and deep learning elseerror( "not implemented{data output_type}"nn learn(epochsthe following tests on mnist the original files are from com/exdb/mnistthis code assumes you use the csv files from com/projects/mnist-in-csv/and put them in the directory /mnistnote that this is very inefficientyou would be ...
18,890
(ewhat happens if you have neither the sigmoid layer nor relu layer after the first linear layerexercise do some version june
18,891
reasoning under uncertainty representing probabilistic models variable consists of namea domain and an optional ( ,yposition (for displayingthe domain of variable is list or tupleas the ordering will matter in the representation of factors probvariables py -probabilistic variables import random class variable(object)""...
18,892
reasoning under uncertainty def __repr__(self)return self name "variable({self name}) representing factors factor ismathematicallya function from variables into numberthat is given value for each of its variableit gives number factors are used for conditional probabilitiesutilities in the next and are explicitly constr...
18,893
"""returns string representing summary of the factor""return "{self name}({',join(str(varfor var in self variables)}) def to_table(selfvariables=nonegiven={})"""returns string representation of the factor allows for an arbitrary variable ordering variables is list of the variables in the factor (can contain other varia...
18,894
reasoning under uncertainty elsereturn " ({self child}) __repr__ __str__ the simplest cpd is the constant that has probability when the child has the value specified probfactors py -(continued class constantcpd(cpd)def __init__(selfvariablevalue)cpd __init__(selfvariable[]self value value def get_value(selfassignment)r...
18,895
noisy-or noisy-orfor boolean variable with boolean parents yk is parametrized by parameters pk where each <pi < the sematics is defined as though there are hidden variables zk where ( and (zi yi pi for > and where is true if and only if zk (where is "or"thus is false if all of the zi are false intuitivelyz is the proba...
18,896
reasoning under uncertainty from functools import reduce class tabfactor(factor) def __init__(selfvariablesvalues)factor __init__(selfvariablesself values values def get_value(selfassignment)return self get_val_rec(self valuesself variablesassignment def get_val_rec(selfvaluevariablesassignment)if variables =[]return v...
18,897
vars is set of variables factors is set of factors ""def __init__(selftitlevariables=nonefactors=none)self title title self variables variables self factors factors belief network (also known as bayesian networkis graphical model where all of the factors are conditional probabilitiesand every variable has conditional p...
18,898
reasoning under uncertainty self display( ,'select variable',vartop_order append(varnext_vars |{ch for ch in self children[varif all( in top_order for in self var parents[ch])self display( ,'var_with_no_parents_left',next_varsself display( ,"top_order",top_orderassert set(top_order)==set(self var parents),(top_order,se...
18,899
report-of-leaving tamper fire alarm smoke leaving report figure the report-of-leaving belief network f_b prob( ,[ ],[[ , ],[ , ]]f_c prob( ,[ ],[[ , ],[ , ]]f_d prob( ,[ ],[[ , ],[ , ]] bn_ ch beliefnetwork(" -chain"{ , , , }{f_a,f_b,f_c,f_d}report-of-leaving example the second belief networkbn_reportis example of pool...