QuizGenerator 0.1.3__py3-none-any.whl → 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,227 @@
1
+ import abc
2
+ import logging
3
+ import math
4
+ import keras
5
+ import numpy as np
6
+
7
+ from QuizGenerator.question import Question, QuestionRegistry, Answer
8
+ from QuizGenerator.contentast import ContentAST
9
+ from QuizGenerator.constants import MathRanges
10
+
11
+ log = logging.getLogger(__name__)
12
+
13
+
14
+ class WeightCounting(Question, abc.ABC):
15
+ @abc.abstractmethod
16
+ def get_model(self) -> keras.Model:
17
+ pass
18
+
19
+ @staticmethod
20
+ def model_to_python(model: keras.Model, fields=None, include_input=True):
21
+ if fields is None:
22
+ fields = []
23
+
24
+ def sanitize(v):
25
+ """Convert numpy types to pure Python."""
26
+ if isinstance(v, np.generic): # np.int64, np.float32, etc.
27
+ return v.item()
28
+ if isinstance(v, (list, tuple)):
29
+ return type(v)(sanitize(x) for x in v)
30
+ if isinstance(v, dict):
31
+ return {k: sanitize(x) for k, x in v.items()}
32
+ return v
33
+
34
+ lines = []
35
+ lines.append("keras.models.Sequential([")
36
+
37
+ # ---- Emit an Input line if we can ----
38
+ # model.input_shape is like (None, H, W, C) or (None, D)
39
+ if include_input and getattr(model, "input_shape", None) is not None:
40
+ input_shape = sanitize(model.input_shape[1:]) # drop batch dimension
41
+ # If it's a 1D shape like (784,), keep as tuple; if scalar, still fine.
42
+ lines.append(f" keras.layers.Input(shape={input_shape!r}),")
43
+
44
+ # ---- Emit all other layers ----
45
+ for layer in model.layers:
46
+ # If user explicitly had an Input layer, we don't want to duplicate it
47
+ if isinstance(layer, keras.layers.InputLayer):
48
+ # You *could* handle it specially here, but usually we just skip
49
+ continue
50
+
51
+ cfg = layer.get_config()
52
+
53
+ # If fields is empty, include everything; otherwise filter by fields.
54
+ if fields:
55
+ items = [(k, v) for k, v in cfg.items() if k in fields]
56
+ else:
57
+ items = cfg.items()
58
+
59
+ arg_lines = [
60
+ f"{k}={sanitize(v)!r}" # !r so strings get quotes, etc.
61
+ for k, v in items
62
+ ]
63
+ args = ",\n ".join(arg_lines)
64
+
65
+ lines.append(
66
+ f" keras.layers.{layer.__class__.__name__}("
67
+ f"{'\n ' if args else ''}{args}{'\n ' if args else ''}),"
68
+ )
69
+
70
+ lines.append("])")
71
+ return "\n".join(lines)
72
+
73
+ def refresh(self, *args, **kwargs):
74
+ super().refresh(*args, **kwargs)
75
+
76
+ refresh_success = False
77
+ while not refresh_success:
78
+ try:
79
+ self.model, self.fields = self.get_model()
80
+ refresh_success = True
81
+ except ValueError as e:
82
+ log.error(e)
83
+ log.info(f"Regenerating {self.__class__.__name__} due to improper configuration")
84
+ continue
85
+
86
+ self.num_parameters = self.model.count_params()
87
+ self.answers["num_parameters"] = Answer.integer(
88
+ "num_parameters",
89
+ self.num_parameters
90
+ )
91
+
92
+ return True
93
+
94
+ def get_body(self, **kwargs) -> ContentAST.Section:
95
+ body = ContentAST.Section()
96
+
97
+ body.add_element(
98
+ ContentAST.Paragraph(
99
+ [
100
+ ContentAST.Text("Given the below model, how many parameters does it use?")
101
+ ]
102
+ )
103
+ )
104
+
105
+ body.add_element(
106
+ ContentAST.Code(
107
+ self.model_to_python(
108
+ self.model,
109
+ fields=self.fields
110
+ )
111
+ )
112
+ )
113
+
114
+ body.add_element(ContentAST.LineBreak())
115
+
116
+ body.add_element(
117
+ ContentAST.Answer(self.answers["num_parameters"], "Number of Parameters")
118
+ )
119
+
120
+ return body
121
+
122
+ def get_explanation(self, **kwargs) -> ContentAST.Section:
123
+ explanation = ContentAST.Section()
124
+
125
+ def markdown_summary(model) -> ContentAST.Table:
126
+ # Ensure the model is built by running build() or calling it once
127
+ if not model.built:
128
+ try:
129
+ model.build(model.input_shape)
130
+ except:
131
+ pass # Some subclassed models need real data to build
132
+
133
+ data = []
134
+
135
+ total_params = 0
136
+
137
+ for layer in model.layers:
138
+ name = layer.name
139
+ ltype = layer.__class__.__name__
140
+
141
+ # Try to extract output shape
142
+ try:
143
+ outshape = tuple(layer.output.shape)
144
+ except:
145
+ outshape = "?"
146
+
147
+ params = layer.count_params()
148
+ total_params += params
149
+
150
+ data.append([name, ltype, outshape, params])
151
+
152
+ data.append(["**Total**", "", "", f"**{total_params}**"])
153
+ return ContentAST.Table(data=data, headers=["Layer", "Type", "Output Shape", "Params"])
154
+
155
+
156
+ summary_lines = []
157
+ self.model.summary(print_fn=lambda x: summary_lines.append(x))
158
+ explanation.add_element(
159
+ # ContentAST.Text('\n'.join(summary_lines))
160
+ markdown_summary(self.model)
161
+ )
162
+
163
+ return explanation
164
+
165
+
166
+ @QuestionRegistry.register("cst463.WeightCounting-CNN")
167
+ class WeightCounting_CNN(WeightCounting):
168
+
169
+ def get_model(self) -> tuple[keras.Model, list[str]]:
170
+ input_size = self.rng.choice(np.arange(28, 32))
171
+ cnn_num_filters = self.rng.choice(2 ** np.arange(8))
172
+ cnn_kernel_size = self.rng.choice(1 + np.arange(10))
173
+ cnn_strides = self.rng.choice(1 + np.arange(10))
174
+ pool_size = self.rng.choice(1 + np.arange(10))
175
+ pool_strides = self.rng.choice(1 + np.arange(10))
176
+ num_output_size = self.rng.choice([1, 10, 32, 100])
177
+
178
+ # Let's just make a small model
179
+ model = keras.models.Sequential(
180
+ [
181
+ keras.layers.Input((input_size, input_size, 1)),
182
+ keras.layers.Conv2D(
183
+ filters=cnn_num_filters,
184
+ kernel_size=(cnn_kernel_size, cnn_kernel_size),
185
+ strides=(cnn_strides, cnn_strides),
186
+ padding="valid"
187
+ ),
188
+ keras.layers.MaxPool2D(
189
+ pool_size=(pool_size, pool_size),
190
+ strides=(pool_strides, pool_strides)
191
+ ),
192
+ keras.layers.Dense(
193
+ num_output_size
194
+ )
195
+ ]
196
+ )
197
+ return model, ["filters", "kernel_size", "strides", "padding", "pool_size"]
198
+
199
+
200
+ @QuestionRegistry.register("cst463.WeightCounting-RNN")
201
+ class WeightCounting_RNN(WeightCounting):
202
+ def get_model(self) -> tuple[keras.Model, list[str]]:
203
+ timesteps = int(self.rng.choice(np.arange(20, 41)))
204
+ feature_size = int(self.rng.choice(np.arange(8, 65)))
205
+
206
+ rnn_units = int(self.rng.choice(2 ** np.arange(4, 9)))
207
+ rnn_type = self.rng.choice(["SimpleRNN"])
208
+ return_sequences = bool(self.rng.choice([True, False]))
209
+
210
+ num_output_size = int(self.rng.choice([1, 10, 32, 100]))
211
+
212
+ RNNLayer = getattr(keras.layers, rnn_type)
213
+
214
+ model = keras.models.Sequential([
215
+ keras.layers.Input((timesteps, feature_size)),
216
+ RNNLayer(
217
+ units=rnn_units,
218
+ return_sequences=return_sequences,
219
+ ),
220
+ keras.layers.Dense(num_output_size),
221
+ ])
222
+ return model, ["units", "return_sequences"]
223
+
224
+
225
+ @QuestionRegistry.register()
226
+ class ConvolutionCalculation(Question):
227
+ pass