Skip to content

Commit a035ae6

Browse files
committed
Fix type annotation and typo
1 parent c004c1a commit a035ae6

File tree

2 files changed

+43
-57
lines changed

2 files changed

+43
-57
lines changed

tensorcircuit/templates/ensemble.py

+36-51
Original file line numberDiff line numberDiff line change
@@ -3,43 +3,48 @@
33
"""
44

55
import tensorflow as tf
6+
import keras
67
import numpy as np
8+
from typing import Any, Optional, Sequence, Tuple, List
9+
10+
NDArray = Any
11+
kwargus = Any
712

813

914
class bagging: # A.K.A. voting
10-
def __init__(self):
11-
self.models = []
12-
self.is_trained = []
15+
def __init__(self) -> None:
16+
self.models: List[keras.engine.functional.Functional]= []
17+
self.model_trained: List[bool] = []
1318
self.count = 0
1419
self.need_confidence = True # Help in reducing numbers of get_confidence runs
1520
self.permit_train = False
1621

17-
def append(self, model, is_trained):
22+
def append(self, model: keras.engine.functional.Functional, model_trained: bool) -> None:
1823
"""
1924
Add model to the voting method
2025
"""
2126
self.models.append(model)
22-
self.is_trained.append(is_trained)
27+
self.model_trained.append(model_trained)
2328
self.count += 1
2429

25-
def __train_model(self, i, **kwargs):
30+
def __train_model(self, i: int, **kwargs: kwargus) -> None:
2631
"""
2732
Train a model if it isn't trained already
2833
"""
29-
if not self.is_trained[i]:
34+
if not self.model_trained[i]:
3035
self.need_confidence = True
31-
self.is_trained[i] = True
32-
self.models[i]
36+
self.model_trained[i] = True
3337
self.models[i].trainable
3438
self.models[i].fit(**kwargs)
3539

36-
def train(self, **kwargs):
40+
def train(self, **kwargs: kwargus) -> None:
3741
"""
3842
Train all models in the class, **kwargs expect to receive the argus that can be directly sent to tf.fit
3943
Expected to be run after finishing compile
4044
"""
4145
if not self.permit_train:
42-
raise Exception("Needed to be compiled before training")
46+
#raise Exception("Needed to be compiled before training")
47+
raise ValueError()
4348
for i in range(self.count):
4449
if "verbose" in kwargs:
4550
if kwargs["verbose"] == 1:
@@ -48,15 +53,15 @@ def train(self, **kwargs):
4853
print("Model ", i + 1, "/", self.count, " is training...")
4954
self.__train_model(i, **kwargs)
5055

51-
def compile(self, **kwargs):
56+
def compile(self, **kwargs: kwargus) -> None:
5257
"""
5358
Compile code
5459
"""
5560
self.permit_train = True
5661
for i in range(self.count):
5762
self.models[i].compile(**kwargs)
5863

59-
def __get_confidence(self, model_index, input):
64+
def __get_confidence(self, model_index: int, input: NDArray) -> NDArray:
6065
"""
6166
Get the confidence value that is needed by voting.
6267
Number of calling this function is reduced by self.need_confidence
@@ -73,65 +78,45 @@ def __get_confidence(self, model_index, input):
7378
More voting strategies can be added beneath, a single function, and a if function in self.predict
7479
"""
7580

76-
def __voting_weight(self, array):
81+
def __voting_weight(self, array: NDArray) -> NDArray:
7782
result = []
7883
for i in array:
7984
result.append(self.__voting_weight_single(i))
80-
return result
85+
return np.array(result)
8186

82-
def __voting_most(self, array):
83-
result = []
84-
for i in array:
85-
result.append(self.__voting_most_single(i))
87+
def __voting_average(self, array: NDArray) -> NDArray:
88+
result = np.mean(array, axis=1)
8689
return result
8790

88-
def __voting_average(self, array):
89-
result = []
90-
for i in array:
91-
result.append(self.__voting_average_single(i))
92-
return result
93-
94-
def __voting_weight_single(self, array):
91+
def __voting_weight_single(self, array: NDArray) -> float:
9592
opp_array = np.ones(len(array)) - array
9693
weight = np.absolute(opp_array - array)
9794
weight_sum = np.sum(weight)
9895
weight = weight / weight_sum
9996
result = array * weight
100-
return np.sum(result)
101-
102-
def __voting_most_single(self, array):
103-
weight = array.size
104-
result = 0
105-
for i in array:
106-
result += i / weight
107-
return result
108-
109-
def __voting_average_single(self, array):
110-
result = array / array.size
111-
return np.sum(result)
97+
return float(np.sum(result))
11298

113-
def predict(self, input_data, voting_policy: str = "none"):
99+
def predict(self, input_data: NDArray, voting_policy: str = "None") -> NDArray:
114100
"""
115101
Input data is expected to be a 2D array that the first layer is different input data (into the trained models)
116102
"""
117103
if self.need_confidence:
118104
predictions = []
119105
for i in range(self.count):
120106
predictions.append(np.array(self.__get_confidence(i, input_data)))
121-
predictions = np.array(predictions)
122-
self.predictions = np.transpose(predictions)
107+
self.predictions = np.transpose(np.array(predictions))
123108
if voting_policy == "weight":
124109
return self.__voting_weight(self.predictions)
125110
elif voting_policy == "most":
126-
return self.__voting_most(self.predictions)
111+
return self.__voting_average(self.predictions)
127112
elif voting_policy == "average":
128113
return self.__voting_average(self.predictions)
129-
elif voting_policy == "none":
114+
elif voting_policy == "None" or voting_policy == "none":
130115
return self.predictions
131116
else:
132-
raise Exception("voting_policy must be none, weight, most, or average")
117+
raise ValueError()
133118

134-
def __acc_binarify(self, array):
119+
def __acc_binarify(self, array: NDArray) -> NDArray:
135120
"""
136121
Needed for ACC test
137122
"""
@@ -140,20 +125,20 @@ def __acc_binarify(self, array):
140125
result.append(1 if (i > 0.5) else 0)
141126
return result
142127

143-
def __eval_accuracy(self, input_data):
128+
def __eval_accuracy(self, input_data: NDArray) -> float:
144129
input_data[1] = self.__acc_binarify(input_data[1])
145130
algo = tf.keras.metrics.Accuracy()
146131
algo.reset_state()
147132
algo.update_state(input_data[0], input_data[1])
148-
return algo.result().numpy()
133+
return float(algo.result().numpy())
149134

150-
def __eval_auc(self, input_data):
135+
def __eval_auc(self, input_data: NDArray) -> float:
151136
algo = tf.keras.metrics.AUC()
152137
algo.reset_state()
153138
algo.update_state(input_data[0], input_data[1])
154-
return algo.result().numpy()
139+
return float(algo.result().numpy())
155140

156-
def eval(self, input_data, evaluation_method: str = "acc"):
141+
def eval(self, input_data: List[NDArray], evaluation_method: str = "acc") -> float:
157142
"""
158143
Expect input data to be a 2D array, which a 1D array of yTrue followed by a 1D array of yPred is expected to be the components of the 2D array
159144
"""
@@ -162,4 +147,4 @@ def eval(self, input_data, evaluation_method: str = "acc"):
162147
elif evaluation_method == "auc":
163148
return self.__eval_auc(input_data)
164149
else:
165-
raise Exception("evaluation_method must be acc or auc")
150+
raise ValueError()

tests/test_ensemble.py

+7-6
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
import tensorflow as tf
2-
import numpy as np
31
import os
42
import sys
3+
import tensorflow as tf
4+
import numpy as np
55

66
thisfile = os.path.abspath(__file__)
77
modulepath = os.path.dirname(os.path.dirname(thisfile))
@@ -13,13 +13,13 @@
1313

1414
def test_ensemble_bagging():
1515
data_amount = 100 # Amount of data to be used
16-
linear_demension = 4 # linear demension of the data
16+
linear_dimension = 4 # linear demension of the data
1717
epochs = 10
1818
batch_size = 32
1919
lr = 1e-3
2020

2121
x_train, y_train = (
22-
np.ones([data_amount, linear_demension]),
22+
np.ones([data_amount, linear_dimension]),
2323
np.ones([data_amount, 1]),
2424
)
2525

@@ -29,7 +29,7 @@ def model():
2929
DROP = 0.1
3030

3131
activation = "selu"
32-
inputs = tf.keras.Input(shape=(linear_demension,), name="digits")
32+
inputs = tf.keras.Input(shape=(linear_dimension,), name="digits")
3333
x0 = tf.keras.layers.Dense(
3434
1,
3535
kernel_regularizer=tf.keras.regularizers.l2(9.613e-06),
@@ -60,8 +60,9 @@ def model():
6060
)
6161

6262
v_weight = obj_bagging.predict(x_train, "weight")
63-
v_most = obj_bagging.predict(x_train, "most")
6463
v_average = obj_bagging.predict(x_train, "average")
6564
validation_data = []
6665
validation_data.append(obj_bagging.eval([y_train, v_weight], "acc"))
6766
validation_data.append(obj_bagging.eval([y_train, v_weight], "auc"))
67+
68+
test_ensemble_bagging()

0 commit comments

Comments
 (0)