Skip to content

Commit 27f3ae6

Browse files
committed
string formatting conversion to f-string via flynt
1 parent 1ea6f1b commit 27f3ae6

19 files changed

+91
-99
lines changed

data/mnist_data_handler.py

+13-13
Original file line numberDiff line numberDiff line change
@@ -113,8 +113,8 @@ def get_unbalance_data(main_class: int, other_class_percentage: float, class_sel
113113

114114
def split_mnist_data(class_selection: Optional[List[int]] = None) -> None:
115115
(x_train, y_train), (x_test, y_test), input_shape, num_classes = get_basic_data()
116-
logging.info('splitting %i train examples' % x_train.shape[0])
117-
logging.info('splitting %i test examples' % x_test.shape[0])
116+
logging.info(f'splitting {x_train.shape[0]} train examples')
117+
logging.info(f'splitting {x_test.shape[0]} test examples')
118118

119119
separated_train_data: List[Tuple[np.array, np.array]] = [([], []) for _ in
120120
range(num_classes)]
@@ -171,24 +171,24 @@ def split_mnist_data(class_selection: Optional[List[int]] = None) -> None:
171171
)
172172

173173
for i, class_id in enumerate(ensured_class_selection):
174-
logging.info('%i train examples for class #%i' %
175-
(processed_separated_train_data[i][0].shape[0], class_id))
176-
logging.info('%i test examples for class #%i' %
177-
(processed_separated_test_data[i][0].shape[0], class_id))
174+
logging.info(
175+
f'{processed_separated_train_data[i][0].shape[0]} train examples for class #{class_id}')
176+
logging.info(
177+
f'{processed_separated_test_data[i][0].shape[0]} test examples for class #{class_id}')
178178

179179
data_path: str = DATA_PATH + 'mnist'
180180
if not os.path.exists(data_path):
181181
os.makedirs(data_path)
182182

183183
if len(ensured_class_selection) == num_classes:
184-
np.savez('%s/mnist_train_split' %
185-
data_path, processed_separated_train_data)
186-
np.savez('%s/mnist_test_split' %
187-
data_path, processed_separated_test_data)
184+
np.savez(f'{data_path}/mnist_train_split',
185+
processed_separated_train_data)
186+
np.savez(f'{data_path}/mnist_test_split',
187+
processed_separated_test_data)
188188
else:
189-
np.savez('%s/mnist_train_split_%s' % (data_path, ''.join(str(e) + '_' for e in ensured_class_selection)),
189+
np.savez(f"{data_path}/mnist_train_split_{''.join(str(e) + '_' for e in ensured_class_selection)}",
190190
processed_separated_train_data)
191-
np.savez('%s/mnist_test_split_%s' % (data_path, ''.join(str(e) + '_' for e in ensured_class_selection)),
191+
np.savez(f"{data_path}/mnist_test_split_{''.join(str(e) + '_' for e in ensured_class_selection)}",
192192
processed_separated_test_data)
193193

194-
logging.info("saved split data to \"%s\"" % data_path)
194+
logging.info(f"saved split data to \"{data_path}\"")

data/model_data.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -106,4 +106,4 @@ def check_model_supported_layer(self) -> None:
106106
for index, layer in enumerate(self.model.layers):
107107
if layer.__class__.__name__ not in SUPPORTED_LAYER and layer.__class__.__name__ not in IGNORED_LAYER:
108108
raise Exception(
109-
"'%s' layer type of model not supported!" % layer.__class__.__name__)
109+
f"'{layer.__class__.__name__}' layer type of model not supported!")

evaluation/create_plot.py

+13-15
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,9 @@ def save_plot(name: str) -> None:
3131
BASE_PATH, os.path.join('storage', 'evaluation'))
3232
if not os.path.exists(directory_path):
3333
os.makedirs(directory_path)
34-
file_path: str = '%s/%s.svg' % (directory_path, name)
34+
file_path: str = f'{directory_path}/{name}.svg'
3535
plt.savefig(file_path)
36-
file_path = '%s/%s.jpg' % (directory_path, name)
36+
file_path = f'{directory_path}/{name}.jpg'
3737
plt.savefig(file_path)
3838

3939

@@ -65,7 +65,7 @@ def create_importance_plot(filename: str, importance_name: str, timed_name: bool
6565
plot.axvline(x=90, color='red')
6666
trans = transforms.blended_transform_factory(
6767
plot.get_yticklabels()[0].get_transform(), plot.transData)
68-
plot.text(0.9, -0.025, '{:.0f}'.format(90), color='red', transform=trans,
68+
plot.text(0.9, -0.025, f'{90:.0f}', color='red', transform=trans,
6969
va='bottom', ha='center')
7070

7171
save_plot(importance_name)
@@ -106,10 +106,10 @@ def create_importance_plot_compare_regularizer(filename: str, importance_names:
106106
plot.axvline(x=90, color='red')
107107
trans = transforms.blended_transform_factory(
108108
plot.get_yticklabels()[0].get_transform(), plot.transData)
109-
plot.text(0.9, -0.025, '{:.0f}'.format(90), color='red', transform=trans,
109+
plot.text(0.9, -0.025, f'{90:.0f}', color='red', transform=trans,
110110
va='bottom', ha='center')
111111

112-
save_plot('regularizer_compare_%s' % check_importance_type)
112+
save_plot(f'regularizer_compare_{check_importance_type}')
113113

114114
if show:
115115
plt.show()
@@ -144,7 +144,7 @@ def create_importance_plot_compare_bn_parameter(filename: str, importance_names:
144144
for line in plot.lines:
145145
plt.setp(line, linewidth=3, alpha=0.6)
146146

147-
save_plot('bn_parameter_compare_%s' % check_importance_type)
147+
save_plot(f'bn_parameter_compare_{check_importance_type}')
148148

149149
if show:
150150
plt.show()
@@ -157,10 +157,9 @@ def create_importance_plot_compare_class_vs_all(filename: str, importance_name:
157157
show: bool = False) -> None:
158158
converted_data: List[List[Any]] = []
159159

160-
importance_data_name: str = '%s_[%s]' % (
161-
check_importance_type, class_index) if class_specific_data else check_importance_type
160+
importance_data_name: str = f'{check_importance_type}_[{class_index}]' if class_specific_data else check_importance_type
162161
overall_importance_label_name: str = 'all_classes'
163-
class_importance_label_name: str = 'class_[%s]' % class_index
162+
class_importance_label_name: str = f'class_[{class_index}]'
164163
data: Dict[Any, Any] = load_data(filename, importance_name, timed_name)
165164

166165
for percent, percent_data in data.items():
@@ -181,8 +180,8 @@ def create_importance_plot_compare_class_vs_all(filename: str, importance_name:
181180
plot: Axes = df.plot(legend=True)
182181
plot.set_ylabel('Prediction Accuracy')
183182

184-
save_plot('%s_class_compare_%s_%i' %
185-
(importance_name, check_importance_type, class_index))
183+
save_plot(
184+
f'{importance_name}_class_compare_{check_importance_type}_{class_index}')
186185

187186
if show:
188187
plt.show()
@@ -195,9 +194,8 @@ def create_importance_plot_compare_classes_vs_all(filename: str, importance_name
195194
converted_data: List[List[Any]] = []
196195

197196
for i in range(10):
198-
importance_data_name: str = '%s_[%s]' % (
199-
check_importance_type, i) if class_specific_data else check_importance_type
200-
class_importance_label_name: str = "Digit \"%s\"" % i
197+
importance_data_name: str = f'{check_importance_type}_[{i}]' if class_specific_data else check_importance_type
198+
class_importance_label_name: str = f"Digit \"{i}\""
201199
data: Dict[Any, Any] = load_data(filename, importance_name, timed_name)
202200

203201
for percent, percent_data in data.items():
@@ -223,7 +221,7 @@ def create_importance_plot_compare_classes_vs_all(filename: str, importance_name
223221
for line in plot.lines:
224222
plt.setp(line, linewidth=3, alpha=0.7)
225223

226-
save_plot('%s_class_compare_%s' % (importance_name, check_importance_type))
224+
save_plot(f'{importance_name}_class_compare_{check_importance_type}')
227225

228226
if show:
229227
plt.show()

evaluation/evaluator.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ def prune_model(self,
100100
self.importance_calculation.name,
101101
data)
102102

103-
logging.info('Pruned edges: %i' % pruned_edges)
103+
logging.info(f'Pruned edges: {pruned_edges}')
104104

105105
def accuracy_report(self, truths: np.array, predictions: np.array) -> Dict[str, Any]:
106106
accuracy_report: Dict[str, Any] = dict()
@@ -136,10 +136,10 @@ def test_model(self, importance_prune_percent: str) -> None:
136136
test_score = self.model_data.model.evaluate(
137137
self.x_test, self.y_test, verbose=0)
138138

139-
logging.info('Train loss: %f, Train accuracy: %f' %
140-
(train_score[0], train_score[1]))
141-
logging.info('Test loss: %f, Test accuracy: %f' %
142-
(test_score[0], test_score[1]))
139+
logging.info(
140+
f'Train loss: {train_score[0]:f}, Train accuracy: {train_score[1]:f}')
141+
logging.info(
142+
f'Test loss: {test_score[0]:f}, Test accuracy: {test_score[1]:f}')
143143

144144
truth_train: np.array = np.argmax(self.y_train, axis=1)
145145
predict_train: np.array = self.model_data.model.predict(self.x_train)

examples/create_images.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ def plot_histogram(path: str) -> None:
7979
pdf = KernelDensity(kernel='epanechnikov', bandwidth=bandwidth).fit(
8080
z_values).score_samples(x_grid[:, None])
8181
ax.plot(x_grid, np.exp(pdf), linewidth=2, alpha=0.6,
82-
label='bandwidth=%.2f' % bandwidth)
82+
label=f'bandwidth={bandwidth:.2f}')
8383

8484
ax.hist(z_values, slots, facecolor='gray',
8585
histtype='stepfilled', alpha=0.4, density=True)

examples/evaluation_plots.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,8 @@
2828

2929
def create_importance_data(model_data: ModelData, importance_type: ImportanceType) -> None:
3030
pn = ProcessedNetwork(model_data=model_data)
31-
pn.generate_importance_data('mnist/mnist_train_split%s' % split_suffix,
32-
'mnist/mnist_test_split%s' % split_suffix,
31+
pn.generate_importance_data(f'mnist/mnist_train_split{split_suffix}',
32+
f'mnist/mnist_test_split{split_suffix}',
3333
importance_type)
3434
model_data.store_model_data()
3535
model_data.save_data()
@@ -56,8 +56,8 @@ def evaluate_importance(model_data: ModelData, importance_type: ImportanceType,
5656
model_data: ModelData = create(
5757
name=name, batch_size=128, epochs=15, layer_data=layer_data, regularized=False)
5858
split_suffix: str = ''
59-
if not os.path.exists('%smnist/mnist_train_split%s' % (DATA_PATH, split_suffix)) or not os.path.exists(
60-
'%smnist/mnist_test_split' % DATA_PATH):
59+
if not os.path.exists(f'{DATA_PATH}mnist/mnist_train_split{split_suffix}') or not os.path.exists(
60+
f'{DATA_PATH}mnist/mnist_test_split'):
6161
split_mnist_data()
6262

6363
importance_types: List[ImportanceType] = [

examples/process_mnist_model.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -33,13 +33,13 @@
3333
split_suffix: str = ''
3434
if class_selection is not None:
3535
('_' + ''.join(str(e) + '_' for e in class_selection))
36-
if not os.path.exists('%smnist/mnist_train_split%s' % (DATA_PATH, split_suffix)) or not os.path.exists(
37-
'%smnist/mnist_test_split' % DATA_PATH):
36+
if not os.path.exists(f'{DATA_PATH}mnist/mnist_train_split{split_suffix}') or not os.path.exists(
37+
f'{DATA_PATH}mnist/mnist_test_split'):
3838
split_mnist_data(class_selection)
3939

4040
pn = ProcessedNetwork(model_data=basic_model_data)
41-
pn.generate_importance_data('mnist/mnist_train_split%s' % split_suffix,
42-
'mnist/mnist_test_split%s' % split_suffix,
41+
pn.generate_importance_data(f'mnist/mnist_train_split{split_suffix}',
42+
f'mnist/mnist_test_split{split_suffix}',
4343
importance_type)
4444
basic_model_data.store_model_data()
4545
basic_model_data.save_data()

gui/ui_window.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ def __init__(self) -> None:
4444

4545
self.gui_root.protocol('WM_DELETE_WINDOW', self.on_closing)
4646
self.gui_root.geometry(
47-
'+%d+%d' % (self.window_config['screen_x'], self.window_config['screen_y']))
47+
f"+{self.window_config['screen_x']}+{self.window_config['screen_y']}")
4848
self.gui_root.bind('<Configure>', self.handle_configure)
4949

5050
def start(self, layer_data: Optional[List[int]] = None) -> None:

neural_network_preprocessing/create_mnist_model.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ def create(name: str, batch_size: int, epochs: int, layer_data: List[int], learn
4646
regularized: bool = False, train_type: ModelTrainType = ModelTrainType.BALANCED, main_class: Optional[int] = None,
4747
other_class_percentage: Optional[float] = None, class_selection: Optional[List[int]] = None) -> ModelData:
4848
logging.info(
49-
"Create MNIST neural network model with training type \"%s\"." % train_type.name)
49+
f"Create MNIST neural network model with training type \"{train_type.name}\".")
5050

5151
if train_type is not ModelTrainType.UNBALANCED:
5252
(x_train, y_train), (x_test,
@@ -61,8 +61,8 @@ def create(name: str, batch_size: int, epochs: int, layer_data: List[int], learn
6161
(x_train, y_train), (x_test, y_test), input_shape, num_classes = get_unbalance_data(main_class,
6262
other_class_percentage,
6363
class_selection)
64-
logging.info('Train examples: %i' % x_train.shape[0])
65-
logging.info('Test examples: %i' % x_test.shape[0])
64+
logging.info(f'Train examples: {x_train.shape[0]}')
65+
logging.info(f'Test examples: {x_test.shape[0]}')
6666

6767
if class_selection is not None:
6868
num_classes = len(class_selection)
@@ -93,8 +93,8 @@ def evaluate_model(model_data: ModelData, x_train: Any, y_train: Any, x_test: An
9393
-> ModelData:
9494
train_score = model_data.model.evaluate(x_train, y_train, verbose=0)
9595
test_score = model_data.model.evaluate(x_test, y_test, verbose=0)
96-
logging.info('Train loss: %f, Train accuracy: %f, Test loss: %f, Test accuracy: %f' % (
97-
train_score[0], train_score[1], test_score[0], test_score[1]))
96+
logging.info(
97+
f'Train loss: {train_score[0]:f}, Train accuracy: {train_score[1]:f}, Test loss: {test_score[0]:f}, Test accuracy: {test_score[1]:f}')
9898

9999
c_y_test = np.argmax(y_test, axis=1)
100100

@@ -111,8 +111,8 @@ def evaluate_model(model_data: ModelData, x_train: Any, y_train: Any, x_test: An
111111
def calculate_performance_of_model(model_data: ModelData) -> ModelData:
112112
(x_train, y_train), (x_test, y_test), input_shape, num_classes = get_prepared_data()
113113

114-
logging.info('Train examples: %i' % x_train.shape[0])
115-
logging.info('Test examples: %i' % x_test.shape[0])
114+
logging.info(f'Train examples: {x_train.shape[0]}')
115+
logging.info(f'Test examples: {x_test.shape[0]}')
116116

117117
model_data.reload_model()
118118
model_data.model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adam(0.001),

neural_network_preprocessing/neural_network.py

+10-10
Original file line numberDiff line numberDiff line change
@@ -67,8 +67,8 @@ def get_fine_tuned_model_data(self, class_index: int, train_data: Tuple[np.array
6767

6868
train_score = modified_model.evaluate(x_train, y_train, verbose=0)
6969
test_score = modified_model.evaluate(x_test, y_test, verbose=0)
70-
logging.info('Class %i: Train loss: %f, Train accuracy: %f, Test loss: %f, Test accuracy: %f' % (
71-
class_index, train_score[0], train_score[1], test_score[0], test_score[1]))
70+
logging.info(
71+
f'Class {class_index}: Train loss: {train_score[0]:f}, Train accuracy: {train_score[1]:f}, Test loss: {test_score[0]:f}, Test accuracy: {test_score[1]:f}')
7272

7373
c_y_test = np.argmax(y_test, axis=1)
7474
prediction_test = np.argmax(modified_model.predict(x_test), axis=1)
@@ -84,7 +84,7 @@ def get_fine_tuned_model_data(self, class_index: int, train_data: Tuple[np.array
8484
fine_tuned_data['test_accuracy'] = str(test_score[1])
8585
fine_tuned_data['classification_report'] = c_report
8686

87-
self.model_data.store_data('modified_fine_tuned_performance', self.name, 'class_%i' % class_index,
87+
self.model_data.store_data('modified_fine_tuned_performance', self.name, f'class_{class_index}',
8888
fine_tuned_data)
8989

9090
return modified_model
@@ -109,17 +109,17 @@ def extract_importance_from_model(self, original_model: Model, fine_tuned_model:
109109
def generate_importance_for_data(self, train_data_path: str, test_data_path: str) -> Tuple[List[np.array],
110110
List[np.array]]:
111111
raw_train_data: dict = np.load(
112-
'%s/%s.npz' % (DATA_PATH, train_data_path), allow_pickle=True)
112+
f'{DATA_PATH}/{train_data_path}.npz', allow_pickle=True)
113113
train_data: List[np.array] = raw_train_data['arr_0']
114114

115115
raw_test_data: dict = np.load(
116-
'%s/%s.npz' % (DATA_PATH, test_data_path), allow_pickle=True)
116+
f'{DATA_PATH}/{test_data_path}.npz', allow_pickle=True)
117117
test_data: List[np.array] = raw_test_data['arr_0']
118118

119119
if (len(train_data) is not self.num_classes and self.num_classes is not None) or (
120120
len(test_data) is not self.num_classes and self.num_classes is not None):
121121
raise Exception(
122-
'Data does not match number of classes %i.' % self.num_classes)
122+
f'Data does not match number of classes {self.num_classes}.')
123123

124124
for i, (class_test_data, class_train_data) in enumerate(zip(test_data, train_data)):
125125
fine_tuned_model = self.get_fine_tuned_model_data(
@@ -160,8 +160,8 @@ def generate_importance_data(self, train_data_path: str, test_data_path: str,
160160
max_node_importance = node_class_importance
161161
normalized_node_importance_data.append(
162162
normalized_layer_importance / max_node_importance)
163-
logging.info('Node importance - Min: %f, Max: %f' %
164-
(min_node_importance, max_node_importance))
163+
logging.info(
164+
f'Node importance - Min: {min_node_importance:f}, Max: {max_node_importance:f}')
165165
node_importance_data = normalized_node_importance_data
166166

167167
normalized_edge_importance_data: List[np.array] = []
@@ -179,8 +179,8 @@ def generate_importance_data(self, train_data_path: str, test_data_path: str,
179179
min_edge_importance = current_edge_min
180180
absolute_layer_data /= max_edge_importance
181181
new_layer_data.append(absolute_layer_data)
182-
logging.info('Edge importance - Min: %f, Max: %f' %
183-
(min_edge_importance, max_edge_importance))
182+
logging.info(
183+
f'Edge importance - Min: {min_edge_importance:f}, Max: {max_edge_importance:f}')
184184
normalized_edge_importance_data.append(
185185
np.stack(new_layer_data, axis=0))
186186
edge_importance_data = normalized_edge_importance_data

opengl_helper/buffer.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,8 @@ def load(self, data: Any) -> None:
5454
self.size = data.nbytes
5555
if self.ssbo:
5656
if data.nbytes > self.max_ssbo_size:
57-
raise Exception('Data to big for SSBO (%d bytes, max %d bytes).' % (
58-
data.nbytes, self.max_ssbo_size))
57+
raise Exception(
58+
f'Data to big for SSBO ({data.nbytes} bytes, max {self.max_ssbo_size} bytes).')
5959

6060
glBindBuffer(GL_SHADER_STORAGE_BUFFER, self.handle)
6161
glBufferData(GL_SHADER_STORAGE_BUFFER,
@@ -185,7 +185,7 @@ def load_empty(self, dtype: Any, size: int, component_size: int) -> None:
185185
empty = np.zeros(int(self.max_ssbo_size / 4), dtype=dtype)
186186
buffer_count = math.ceil(
187187
int(size / component_size) / int(self.max_ssbo_size / (component_size * self.object_size * 4)))
188-
logging.info('Data split into %i buffer' % buffer_count)
188+
logging.info(f'Data split into {buffer_count} buffer')
189189
for i in range(buffer_count):
190190
if i >= len(self.handle):
191191
self.handle.append(glGenBuffers(1))

opengl_helper/shader.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def uniform_func_3iv(location: int, data: List[int]) -> None:
4242

4343
return uniform_func_3iv
4444
raise Exception(
45-
"Uniform setter function for '%s' not defined." % uniform_setter)
45+
f"Uniform setter function for '{uniform_setter}' not defined.")
4646

4747

4848
class ShaderSetting:

opengl_helper/texture.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -90,5 +90,5 @@ def __init__(self) -> None:
9090
def activate(self, position: int) -> None:
9191
if position < 0 or position > self.max_textures:
9292
raise Exception(
93-
"OGL Texture position '%d' not available." % position)
93+
f"OGL Texture position '{position}' not available.")
9494
glActiveTexture(GL_TEXTURE0 + position)

0 commit comments

Comments
 (0)