Skip to content

Commit d047ff8

Browse files
[pre-commit.ci] pre-commit suggestions (#321)
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Jirka Borovec <[email protected]> Co-authored-by: jirka <[email protected]>
1 parent 4338f20 commit d047ff8

File tree

11 files changed

+38
-38
lines changed

11 files changed

+38
-38
lines changed

.pre-commit-config.yaml

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ ci:
99

1010
repos:
1111
- repo: https://github.com/pre-commit/pre-commit-hooks
12-
rev: v4.5.0
12+
rev: v4.6.0
1313
hooks:
1414
- id: end-of-file-fixer
1515
- id: trailing-whitespace
@@ -23,7 +23,7 @@ repos:
2323
- id: detect-private-key
2424

2525
- repo: https://github.com/codespell-project/codespell
26-
rev: v2.2.6
26+
rev: v2.3.0
2727
hooks:
2828
- id: codespell
2929
additional_dependencies: [tomli]
@@ -37,7 +37,7 @@ repos:
3737
args: ["--in-place"]
3838

3939
- repo: https://github.com/pre-commit/mirrors-prettier
40-
rev: v3.1.0
40+
rev: v4.0.0-alpha.8
4141
hooks:
4242
- id: prettier
4343
files: \.(json|yml|yaml|toml)
@@ -54,7 +54,7 @@ repos:
5454
- mdformat_frontmatter
5555

5656
- repo: https://github.com/astral-sh/ruff-pre-commit
57-
rev: v0.3.5
57+
rev: v0.5.0
5858
hooks:
5959
# try to fix what is possible
6060
- id: ruff

course_UvA-DL/05-transformers-and-MH-attention/Transformers_MHAttention.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@
8787
os.makedirs(file_path.rsplit("/", 1)[0], exist_ok=True)
8888
if not os.path.isfile(file_path):
8989
file_url = base_url + file_name
90-
print("Downloading %s..." % file_url)
90+
print(f"Downloading {file_url}...")
9191
try:
9292
urllib.request.urlretrieve(file_url, file_path)
9393
except HTTPError as e:
@@ -796,7 +796,7 @@ def _create_model(self):
796796
num_heads=self.hparams.num_heads,
797797
dropout=self.hparams.dropout,
798798
)
799-
# Output classifier per sequence lement
799+
# Output classifier per sequence element
800800
self.output_net = nn.Sequential(
801801
nn.Linear(self.hparams.model_dim, self.hparams.model_dim),
802802
nn.LayerNorm(self.hparams.model_dim),
@@ -948,8 +948,8 @@ def _calculate_loss(self, batch, mode="train"):
948948
acc = (preds.argmax(dim=-1) == labels).float().mean()
949949

950950
# Logging
951-
self.log("%s_loss" % mode, loss)
952-
self.log("%s_acc" % mode, acc)
951+
self.log(f"{mode}_loss", loss)
952+
self.log(f"{mode}_acc", acc)
953953
return loss, acc
954954

955955
def training_step(self, batch, batch_idx):
@@ -1419,8 +1419,8 @@ def _calculate_loss(self, batch, mode="train"):
14191419
preds = preds.squeeze(dim=-1) # Shape: [Batch_size, set_size]
14201420
loss = F.cross_entropy(preds, labels) # Softmax/CE over set dimension
14211421
acc = (preds.argmax(dim=-1) == labels).float().mean()
1422-
self.log("%s_loss" % mode, loss)
1423-
self.log("%s_acc" % mode, acc, on_step=False, on_epoch=True)
1422+
self.log(f"{mode}_loss", loss)
1423+
self.log(f"{mode}_acc", acc, on_step=False, on_epoch=True)
14241424
return loss, acc
14251425

14261426
def training_step(self, batch, batch_idx):

course_UvA-DL/06-graph-neural-networks/GNN_overview.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@
6161
os.makedirs(file_path.rsplit("/", 1)[0], exist_ok=True)
6262
if not os.path.isfile(file_path):
6363
file_url = base_url + file_name
64-
print("Downloading %s..." % file_url)
64+
print(f"Downloading {file_url}...")
6565
try:
6666
urllib.request.urlretrieve(file_url, file_path)
6767
except HTTPError as e:
@@ -616,7 +616,7 @@ def forward(self, data, mode="train"):
616616
elif mode == "test":
617617
mask = data.test_mask
618618
else:
619-
assert False, "Unknown forward mode: %s" % mode
619+
assert False, f"Unknown forward mode: {mode}"
620620

621621
loss = self.loss_module(x[mask], data.y[mask])
622622
acc = (x[mask].argmax(dim=-1) == data.y[mask]).sum().float() / mask.sum()
@@ -671,7 +671,7 @@ def train_node_classifier(model_name, dataset, **model_kwargs):
671671
trainer.logger._default_hp_metric = None # Optional logging argument that we don't need
672672

673673
# Check whether pretrained model exists. If yes, load it and skip training
674-
pretrained_filename = os.path.join(CHECKPOINT_PATH, "NodeLevel%s.ckpt" % model_name)
674+
pretrained_filename = os.path.join(CHECKPOINT_PATH, f"NodeLevel{model_name}.ckpt")
675675
if os.path.isfile(pretrained_filename):
676676
print("Found pretrained model, loading...")
677677
model = NodeLevelGNN.load_from_checkpoint(pretrained_filename)
@@ -790,7 +790,7 @@ def print_results(result_dict):
790790
# %%
791791
print("Data object:", tu_dataset.data)
792792
print("Length:", len(tu_dataset))
793-
print("Average label: %4.2f" % (tu_dataset.data.y.float().mean().item()))
793+
print(f"Average label: {tu_dataset.data.y.float().mean().item():4.2f}")
794794

795795
# %% [markdown]
796796
# The first line shows how the dataset stores different graphs.
@@ -957,7 +957,7 @@ def train_graph_classifier(model_name, **model_kwargs):
957957
trainer.logger._default_hp_metric = None
958958

959959
# Check whether pretrained model exists. If yes, load it and skip training
960-
pretrained_filename = os.path.join(CHECKPOINT_PATH, "GraphLevel%s.ckpt" % model_name)
960+
pretrained_filename = os.path.join(CHECKPOINT_PATH, f"GraphLevel{model_name}.ckpt")
961961
if os.path.isfile(pretrained_filename):
962962
print("Found pretrained model, loading...")
963963
model = GraphLevelGNN.load_from_checkpoint(pretrained_filename)

course_UvA-DL/07-deep-energy-based-generative-models/Deep_Energy_Models.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@
6868
os.makedirs(file_path.rsplit("/", 1)[0], exist_ok=True)
6969
if not os.path.isfile(file_path):
7070
file_url = base_url + file_name
71-
print("Downloading %s..." % file_url)
71+
print(f"Downloading {file_url}...")
7272
try:
7373
urllib.request.urlretrieve(file_url, file_path)
7474
except HTTPError as e:
@@ -770,7 +770,7 @@ def train_model(**kwargs):
770770
rand_imgs = torch.rand((128,) + model.hparams.img_shape).to(model.device)
771771
rand_imgs = rand_imgs * 2 - 1.0
772772
rand_out = model.cnn(rand_imgs).mean()
773-
print("Average score for random images: %4.2f" % (rand_out.item()))
773+
print(f"Average score for random images: {rand_out.item():4.2f}")
774774

775775
# %% [markdown]
776776
# As we hoped, the model assigns very low probability to those noisy images.
@@ -781,7 +781,7 @@ def train_model(**kwargs):
781781
train_imgs, _ = next(iter(train_loader))
782782
train_imgs = train_imgs.to(model.device)
783783
train_out = model.cnn(train_imgs).mean()
784-
print("Average score for training images: %4.2f" % (train_out.item()))
784+
print(f"Average score for training images: {train_out.item():4.2f}")
785785

786786
# %% [markdown]
787787
# The scores are close to 0 because of the regularization objective that was added to the training.
@@ -803,8 +803,8 @@ def compare_images(img1, img2):
803803
plt.xticks([(img1.shape[2] + 2) * (0.5 + j) for j in range(2)], labels=["Original image", "Transformed image"])
804804
plt.yticks([])
805805
plt.show()
806-
print("Score original image: %4.2f" % score1)
807-
print("Score transformed image: %4.2f" % score2)
806+
print(f"Score original image: {score1:4.2f}")
807+
print(f"Score transformed image: {score2:4.2f}")
808808

809809

810810
# %% [markdown]

course_UvA-DL/08-deep-autoencoders/Deep_Autoencoders.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@
6464
file_path = os.path.join(CHECKPOINT_PATH, file_name)
6565
if not os.path.isfile(file_path):
6666
file_url = base_url + file_name
67-
print("Downloading %s..." % file_url)
67+
print(f"Downloading {file_url}...")
6868
try:
6969
urllib.request.urlretrieve(file_url, file_path)
7070
except HTTPError as e:

course_UvA-DL/09-normalizing-flows/NF_image_modeling.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@
6868
file_path = os.path.join(CHECKPOINT_PATH, file_name)
6969
if not os.path.isfile(file_path):
7070
file_url = base_url + file_name
71-
print("Downloading %s..." % file_url)
71+
print(f"Downloading {file_url}...")
7272
try:
7373
urllib.request.urlretrieve(file_url, file_path)
7474
except HTTPError as e:
@@ -518,7 +518,7 @@ def visualize_dequantization(quants, prior=None):
518518
plt.plot([inp[indices[0][-1]]] * 2, [0, prob[indices[0][-1]]], color=color)
519519
x_ticks.append(inp[indices[0][0]])
520520
x_ticks.append(inp.max())
521-
plt.xticks(x_ticks, ["%.1f" % x for x in x_ticks])
521+
plt.xticks(x_ticks, [f"{x:.1f}" for x in x_ticks])
522522
plt.plot(inp, prob, color=(0.0, 0.0, 0.0))
523523
# Set final plot properties
524524
plt.ylim(0, prob.max() * 1.1)
@@ -1199,8 +1199,8 @@ def print_num_params(model):
11991199
table = [
12001200
[
12011201
key,
1202-
"%4.3f bpd" % flow_dict[key]["result"]["val"][0]["test_bpd"],
1203-
"%4.3f bpd" % flow_dict[key]["result"]["test"][0]["test_bpd"],
1202+
"{:4.3f} bpd".format(flow_dict[key]["result"]["val"][0]["test_bpd"]),
1203+
"{:4.3f} bpd".format(flow_dict[key]["result"]["test"][0]["test_bpd"]),
12041204
"%2.0f ms" % (1000 * flow_dict[key]["result"]["time"]),
12051205
"%2.0f ms" % (1000 * flow_dict[key]["result"].get("samp_time", 0)),
12061206
"{:,}".format(sum(np.prod(p.shape) for p in flow_dict[key]["model"].parameters())),

course_UvA-DL/10-autoregressive-image-modeling/Autoregressive_Image_Modeling.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@
9292
file_path = os.path.join(CHECKPOINT_PATH, file_name)
9393
if not os.path.isfile(file_path):
9494
file_url = base_url + file_name
95-
print("Downloading %s..." % file_url)
95+
print(f"Downloading {file_url}...")
9696
try:
9797
urllib.request.urlretrieve(file_url, file_path)
9898
except HTTPError as e:

course_UvA-DL/11-vision-transformer/Vision_Transformer.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@
6969
os.makedirs(file_path.rsplit("/", 1)[0], exist_ok=True)
7070
if not os.path.isfile(file_path):
7171
file_url = base_url + file_name
72-
print("Downloading %s..." % file_url)
72+
print(f"Downloading {file_url}...")
7373
try:
7474
urllib.request.urlretrieve(file_url, file_path)
7575
except HTTPError as e:
@@ -353,8 +353,8 @@ def _calculate_loss(self, batch, mode="train"):
353353
loss = F.cross_entropy(preds, labels)
354354
acc = (preds.argmax(dim=-1) == labels).float().mean()
355355

356-
self.log("%s_loss" % mode, loss)
357-
self.log("%s_acc" % mode, acc)
356+
self.log(f"{mode}_loss", loss)
357+
self.log(f"{mode}_acc", acc)
358358
return loss
359359

360360
def training_step(self, batch, batch_idx):
@@ -396,7 +396,7 @@ def train_model(**kwargs):
396396
# Check whether pretrained model exists. If yes, load it and skip training
397397
pretrained_filename = os.path.join(CHECKPOINT_PATH, "ViT.ckpt")
398398
if os.path.isfile(pretrained_filename):
399-
print("Found pretrained model at %s, loading..." % pretrained_filename)
399+
print(f"Found pretrained model at {pretrained_filename}, loading...")
400400
# Automatically loads the model with the saved hyperparameters
401401
model = ViT.load_from_checkpoint(pretrained_filename)
402402
else:

course_UvA-DL/12-meta-learning/Meta_Learning.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@
9292
os.makedirs(file_path.rsplit("/", 1)[0], exist_ok=True)
9393
if not os.path.isfile(file_path):
9494
file_url = base_url + file_name
95-
print("Downloading %s..." % file_url)
95+
print(f"Downloading {file_url}...")
9696
try:
9797
urllib.request.urlretrieve(file_url, file_path)
9898
except HTTPError as e:
@@ -525,8 +525,8 @@ def calculate_loss(self, batch, mode):
525525
preds, labels, acc = self.classify_feats(prototypes, classes, query_feats, query_targets)
526526
loss = F.cross_entropy(preds, labels)
527527

528-
self.log("%s_loss" % mode, loss)
529-
self.log("%s_acc" % mode, acc)
528+
self.log(f"{mode}_loss", loss)
529+
self.log(f"{mode}_acc", acc)
530530
return loss
531531

532532
def training_step(self, batch, batch_idx):
@@ -573,7 +573,7 @@ def train_model(model_class, train_loader, val_loader, **kwargs):
573573
# Check whether pretrained model exists. If yes, load it and skip training
574574
pretrained_filename = os.path.join(CHECKPOINT_PATH, model_class.__name__ + ".ckpt")
575575
if os.path.isfile(pretrained_filename):
576-
print("Found pretrained model at %s, loading..." % pretrained_filename)
576+
print(f"Found pretrained model at {pretrained_filename}, loading...")
577577
# Automatically loads the model with the saved hyperparameters
578578
model = model_class.load_from_checkpoint(pretrained_filename)
579579
else:
@@ -947,8 +947,8 @@ def outer_loop(self, batch, mode="train"):
947947
opt.step()
948948
opt.zero_grad()
949949

950-
self.log("%s_loss" % mode, sum(losses) / len(losses))
951-
self.log("%s_acc" % mode, sum(accuracies) / len(accuracies))
950+
self.log(f"{mode}_loss", sum(losses) / len(losses))
951+
self.log(f"{mode}_acc", sum(accuracies) / len(accuracies))
952952

953953
def training_step(self, batch, batch_idx):
954954
self.outer_loop(batch, mode="train")

course_UvA-DL/13-contrastive-learning/SimCLR.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -760,7 +760,7 @@ def train_resnet(batch_size, max_epochs=100, **kwargs):
760760
# Check whether pretrained model exists. If yes, load it and skip training
761761
pretrained_filename = os.path.join(CHECKPOINT_PATH, "ResNet.ckpt")
762762
if os.path.isfile(pretrained_filename):
763-
print("Found pretrained model at %s, loading..." % pretrained_filename)
763+
print(f"Found pretrained model at {pretrained_filename}, loading...")
764764
model = ResNet.load_from_checkpoint(pretrained_filename)
765765
else:
766766
L.seed_everything(42) # To be reproducible

flash_tutorials/image_classification/image_classification.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# %% [markdown]
2-
# In this tutorial, we'll go over the basics of lightning Flash by finetuning/predictin with an ImageClassifier on [Hymenoptera Dataset](https://www.kaggle.com/ajayrana/hymenoptera-data) containing ants and bees images.
2+
# In this tutorial, we'll go over the basics of lightning Flash by finetuning/prediction with an ImageClassifier on [Hymenoptera Dataset](https://www.kaggle.com/ajayrana/hymenoptera-data) containing ants and bees images.
33
#
44
# # Finetuning
55
#

0 commit comments

Comments
 (0)