Conditions | 1 |
Total Lines | 56 |
Code Lines | 29 |
Lines | 0 |
Ratio | 0 % |
Changes | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
1 | import numpy as np |
||
7 | def test_issue_25(): |
||
8 | # set a path to save the dataframe |
||
9 | path = "./search_data.csv" |
||
10 | search_space = { |
||
11 | "n_neighbors": list(range(1, 50)), |
||
12 | } |
||
13 | |||
14 | # get para names from search space + the score |
||
15 | para_names = list(search_space.keys()) + ["score"] |
||
16 | |||
17 | # init empty pandas dataframe |
||
18 | search_data = pd.DataFrame(columns=para_names) |
||
19 | search_data.to_csv(path, index=False) |
||
20 | |||
21 | def objective_function(para): |
||
22 | # score = random.choice([1.2, 2.3, np.nan]) |
||
23 | score = np.nan |
||
24 | |||
25 | # you can access the entire dictionary from "para" |
||
26 | parameter_dict = para.para_dict |
||
27 | |||
28 | # save the score in the copy of the dictionary |
||
29 | parameter_dict["score"] = score |
||
30 | |||
31 | # append parameter dictionary to pandas dataframe |
||
32 | search_data = pd.read_csv(path, na_values="nan") |
||
33 | search_data_new = pd.DataFrame( |
||
34 | parameter_dict, columns=para_names, index=[0] |
||
35 | ) |
||
36 | |||
37 | # search_data = search_data.append(search_data_new) |
||
38 | search_data = pd.concat( |
||
39 | [search_data, search_data_new], ignore_index=True |
||
40 | ) |
||
41 | |||
42 | search_data.to_csv(path, index=False, na_rep="nan") |
||
43 | |||
44 | return score |
||
45 | |||
46 | hyper0 = Hyperactive() |
||
47 | hyper0.add_search(objective_function, search_space, n_iter=50) |
||
48 | hyper0.run() |
||
49 | |||
50 | search_data_0 = pd.read_csv(path, na_values="nan") |
||
51 | """ |
||
52 | the second run should be much faster than before, |
||
53 | because Hyperactive already knows most parameters/scores |
||
54 | """ |
||
55 | hyper1 = Hyperactive() |
||
56 | hyper1.add_search( |
||
57 | objective_function, |
||
58 | search_space, |
||
59 | n_iter=50, |
||
60 | memory_warm_start=search_data_0, |
||
61 | ) |
||
62 | hyper1.run() |
||
63 |