Skip to content
Snippets Groups Projects

fixed problem with filenames of jsons

1 unresolved thread
1 file
+ 1
1
Compare changes
  • Side-by-side
  • Inline
%% Cell type:markdown id:11afed6e-38ec-4dde-9b76-aa5343ac1d7e tags:
# Training mit Korrektur für Export
Zur Vollständigkeit hier nochmals das ganze Notebook, einfach erst unten mit der Korrektur.
Siehe [Errata:-Export-muss-anders-sein-als-bisher](#Errata:-Export-muss-anders-sein-als-bisher)
%% Cell type:code id:08ae75c1-c131-4f74-8976-bdf9846702bd tags:
``` python
from fastcore.foundation import L
from fastcore.xtras import Path # @patch'd properties to the Pathlib module
from fastai.callback.schedule import fit_one_cycle, lr_find
from fastai.data.block import CategoryBlock, DataBlock
from fastai.data.transforms import get_image_files, RandomSplitter
from fastai.learner import Learner
from fastai.metrics import error_rate
from torchvision.models.resnet import resnet34, resnet18
import torchvision.models as torch_models
from fastai.vision.all import (
aug_transforms,
ImageBlock,
RegressionBlock,
vision_learner,
PILImage,
)
import json
import matplotlib.pyplot as plt
```
%% Cell type:code id:0cc3ae95-d44f-4e68-a635-e358604f1cd6 tags:
``` python
image_path = Path('data/sluggish-cheetah')
image_path.exists()
```
%% Cell type:code id:0f14ac6d-0a46-4530-8da2-5aa9f633a5fc tags:
``` python
def read_data_from_json(image):
with open(image_path/f'{image.stem}.json') as f:
with open(image_path/f'{image.stem.replace('picture', 'data')}.json') as f:
json_file = json.load(f)
return[float(json_file['throttle']), float(json_file['steering'])]
```
%% Cell type:code id:86cf73d1-ff45-4564-880e-fe8af9eafd22 tags:
``` python
img = PILImage.create(next(image_path.glob('*.png')))
img.show()
```
%% Cell type:code id:f1c5763e-d5ec-4e55-9d61-2cdb29f0f338 tags:
``` python
read_data_from_json(next(image_path.glob('*.png')))
```
%% Cell type:code id:4e935563-92bc-4b4a-ada6-e30e041929d9 tags:
``` python
data_block = DataBlock(
blocks=(ImageBlock, RegressionBlock(n_out=2)),
get_items=get_image_files,
splitter=RandomSplitter(),
get_y=read_data_from_json
)
```
%% Cell type:code id:1b6789e5-c1b2-4438-8286-8709a1334bcc tags:
``` python
data_loaders = data_block.dataloaders(Path(image_path), bs=32)
```
%% Cell type:code id:556d6b72-bf44-4a6e-a8bb-2efee0963a8d tags:
``` python
data_loaders.show_batch()
```
%% Cell type:code id:265f99f9-9f50-4038-9636-367e0b3c705b tags:
``` python
learn = vision_learner(data_loaders, resnet34)
```
%% Cell type:code id:4bf34214-5e95-4302-8332-0fabdc9fb867 tags:
``` python
learn.lr_find()
```
%% Cell type:code id:a1658d21-21a6-405c-bdaf-c782858b3acb tags:
``` python
lr = 3e-03
```
%% Cell type:code id:5c808fd5-e966-45ab-8656-e96dbe4361ff tags:
``` python
learn.fine_tune(25, lr)
```
%% Cell type:code id:76b674ec-08ad-4cb7-b9f7-885c764090ad tags:
``` python
learn.show_results(ds_idx=1)
```
%% Cell type:code id:eb202bf2-8fee-43f2-a75e-81e5dc6b926b tags:
``` python
learn.predict(next(image_path.glob('*.png')))
```
%% Cell type:code id:2d3b75a6-2ff6-4eb7-8ec0-271c1f277bc3 tags:
``` python
files = get_image_files(image_path)
test_dl = learn.dls.test_dl(files)
preds = learn.get_preds(dl=test_dl)
preds
```
%% Cell type:markdown id:f6e2d88e-434c-4224-bf62-5a8b317670cc tags:
# Errata: Export muss anders sein als bisher
Neu müssen wir via ONNX gehen!
%% Cell type:markdown id:dd2809e7-20af-47ac-82b7-e6a190580e81 tags:
## ONNX installieren
%% Cell type:code id:83bdb96b-cdc5-44f4-ae19-99e6b20c7d1d tags:
``` python
# onnx installieren
!pip install onnx --quiet
```
%% Cell type:markdown id:b0bc51a2-e498-4207-9dac-54f33bc20042 tags:
## Unsere Daten exportieren
* Der Pfad `models/example.onnx` ist was angepasst werden sollte, sonst wird der potentiell überschrieben.
* `input_names=["image"]` und `output_names=["data"]` müssen so heissen und dürfen nicht umbenannt werden. Kleine Frage: Warum könnte das sein?
%% Cell type:code id:1ca20a2e-1688-43ad-b905-7262dcbd6c01 tags:
``` python
import torch
from PIL import Image
from torchvision import transforms
model = learn.model
# Modell auf eval setzen, damit die Gewichte korrekt exportiert werden!
model.eval()
# wir brauchen ein Beispiel Bild um den Input für ONNX festzulegen
convert_tensor = transforms.ToTensor()
with Image.open(next(image_path.glob('*.png'))) as img:
# wir müssen das Bild in das richtige Format bringen, das
# übernimmt fastai sonst für uns, onnx kennt aber fastai nicht, nur unser model.
tensor_img = convert_tensor(img).unsqueeze(0)
torch.onnx.export(
model,
tensor_img.cuda(),
"models/example.onnx",
input_names=["image"],
output_names=["data"]
)
```
%% Cell type:markdown id:3fe6b654-30fa-4340-ac1c-ac61bdba26cb tags:
## Exportiertes Modell auf Korrektheit prüfen
%% Cell type:code id:2cbd02a1-da82-433a-a9b9-03a287df055b tags:
``` python
# ensure correctness
import onnx
onnx_model = onnx.load("models/example.onnx")
onnx.checker.check_model(onnx_model)
```
%% Cell type:markdown id:1aa074c0-6334-4f12-8dcb-019364ccb2b9 tags:
## Durchspielen, was auf unserem Fahrzeug passieren wird
Dafür braucht es *nur* onnxruntime (`ort`) und pytorch.
%% Cell type:code id:70eb00a6-2858-430d-8bbb-0b8ce03eb779 tags:
``` python
# onnxruntime installieren
!pip install onnxruntime --quiet
```
%% Cell type:code id:b2a6b04d-e171-4c7a-8aaf-988f3dd70c34 tags:
``` python
from PIL import Image
from torchvision import transforms
from pathlib import Path
import onnxruntime as ort
import numpy
convert_tensor = transforms.ToTensor()
def get_inference(image_path):
with Image.open(image_path) as img:
# wir müssen das Bild in das richtige Format bringen, das
# übernimmt fastai sonst für uns, onnx kennt aber fastai nicht, nur unser model.
tensor_img = convert_tensor(img).unsqueeze(0).numpy()
ort_sess = ort.InferenceSession('models/example.onnx')
outputs = ort_sess.run(None, {'image': tensor_img})
steering, throttle = outputs[0][0]
return steering, throttle
```
%% Cell type:markdown id:d6d6ec97-96f8-4faf-b694-266b84fc578c tags:
Tut das auch?
%% Cell type:code id:4aef8ecd-0cfc-4a4e-9202-fddd689099fc tags:
``` python
# wir nehmen ein einzelnes Bild von uns, auf dem Fahrzeug kommt dies vom Stream
example_image_path = next(Path('data/sluggish-cheetah').glob('*.png'))
steering, throttle = get_inference(example_image_path)
steering, throttle
```
%% Cell type:markdown id:0d65f448-2abd-4de4-9131-f3a7433687d0 tags:
### Wer mag, kann das auch mit ein paar Bildern prüfen
%% Cell type:code id:2bef070d-0d42-4646-9723-7ab858a93d61 tags:
``` python
images_iterator = Path('data/sluggish-cheetah').glob('*.png')
# Annahme: es gibt (mindestens) 20 Bilder
for _ in range(20):
im = next(images_iterator)
steering, throttle = get_inference(im)
print(steering, throttle)
```
%% Cell type:markdown id:25fb2731-e22e-4292-a55f-854583ec81a2 tags:
# Auf das Fahrzeug übertragen
**Wenn das funktioniert hat**, können wir das models/example.onnx herunterladen und auf dem Fahrzeug an zu den uploads kopieren (zB. `uploads/models/2022-11-11_round-course.onnx`) und dann `SELF_DRIVING_MODEL_PATH` im docker-compose.yml anpassen (zB. `SELF_DRIVING_MODEL_PATH: "uploads/models/2022-11-11_round-course.onnx"`) und `docker compose up -d` ausführen.
Wenn der Learner importiert wurde, kann dieser wie vorhin weiter verwendet werden.
%% Cell type:code id:379572f1-2be5-4719-9a03-391fccf1c66d tags:
``` python
```
Loading