if build_tree: # Build tree to predict age: f = file("data/%s_age.csv" % filename, "r") max_depth = 6 root = construct(f, ind_vars, target_var, max_depth) f.close() f = file("trees/age.tree", "w") write_tree(root, f) f.close() # Trim tree: TODO # Use tree to predict age: # Compile list of independent variables used to predict target variable tree = read_tree("trees/age.tree") f = file("data/%s_no_age.csv" % filename, "r") ind_vars[("PassengerId", "continuous")] = None data = get_data(f, ind_vars) var_dict = simplify_var_dict(ind_vars, None) # Output target variable predictions to csv. f = file("predictions/ages.csv", "w") f.write("PassengerId,%s\n" % target_var[0]) for datum in data: distribution = tree.predict(datum, var_dict) write_prediction(f, distribution, target_var, int(datum[var_dict["PassengerId"]])) f.close() # Write a new data file with age values. write_age_file(filename)
max_key = None for key in distribution.keys(): val = distribution[key] if val > max_val: max_val = val max_key = key f.write(',%s\n' % max_key) elif target_var[1] == 'continuous': f.write(',%f\n' % distribution[0]) else: raise Exception('Invalid varaible type: %s' % target_var[1]) if __name__ == '__main__': # Build tree from a .tree file. tree = read_tree('trees/cat_cont_with_age.tree') # Compile list of independent variables used to predict target variable f = file('data/test_titles_tickets_ages.csv', 'r') ind_vars = { ('Sex', 'categorical'): ['male', 'female'], ('Pclass', 'categorical'): ['1', '2', '3'], ('Embarked', 'categorical'): ['S', 'C', 'Q'], ('Title', 'categorical'): titles, ('Ticket_Code', 'categorical'): ticket_codes, ('SibSp', 'continuous'): None, ('Parch', 'continuous'): None, ('Fare', 'continuous'): None, ('Ticket_Val', 'continuous'): None, ('PassengerId', 'continuous'): None, }