Skip to content

Instantly share code, notes, and snippets.

@pkuderov
Last active June 5, 2019 20:38
Show Gist options
  • Save pkuderov/f38818915582ee081fd91befcafcc2ef to your computer and use it in GitHub Desktop.
Save pkuderov/f38818915582ee081fd91befcafcc2ef to your computer and use it in GitHub Desktop.
Superbowllsh
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
#%% Change working directory from the workspace root to the ipynb file location. Turn this addition off with the DataScience.changeDirOnImportExport setting
import os
try:
os.chdir(os.path.join(os.getcwd(), 'dl_sum_school'))
print(os.getcwd())
except:
pass
#%% [markdown]
# # Superbowllsh
#%%
from fastai.vision import *
from fastai.metrics import error_rate
get_ipython().run_line_magic('matplotlib', 'inline')
#%% [markdown]
# If you're using a computer with an unusually small GPU, you may get an out of memory error when running this notebook. If this happens, click Kernel->Restart, uncomment the 2nd line below to use a smaller *batch size* (you'll learn all about what this means during the course), and try again.
#%%
bs = 64
# bs = 16 # uncomment this line if you run out of memory even after clicking Kernel->Restart
#%% [markdown]
# ## Looking at the data
#%%
from pathlib import PosixPath
path = PosixPath('./data')
path.ls()
#%% [markdown]
# Я довольно поздно обнаружил, что я отправляю предикты с несматченными идентификаторами - в data.test_ds картинки хранятся не в лексикографическом порядке их путей, поэтому предикты были в каком-то смысле случайными.
#
# Это меня демотивировало, поэтому я немного схитрил - разметил самостоятельно еще примерно 50 картинок из теста. Скорее всего я бы это попробовал сделать так и так. Мне кажется, что в условиях этой задачи это не совсем читерство, а скорее нормально. В конце концов я обучал модель, а не просто переразметил все 660 картинок и отправил ответ :)
#
# *вообще, наверняка, заметно, что это копипаста первого урока из fastai, переделанного под данную задачу. Лучше я пока не умею, но в процессе обучения*
#%%
data = ImageDataBunch.from_folder(path=path/'train', train='.', test='../test', valid_pct=.15, bs=8, size=244).normalize()
data
#%%
data.show_batch(rows=3, figsize=(8,6))
#%%
learn = cnn_learner(data, models.resnet34, metrics=error_rate)
#%%
learn.fit_one_cycle(10)
#%%
learn.fit_one_cycle(10, max_lr=slice(1e-6,1e-4))
#%%
learn.save('stage-1')
#%% [markdown]
# Я поздно разобрался с тем, как сматчить предикты с идентификатором картинки, поэтому ниже очень корявый и медленный способ предикта и матчинга. Но хотя бы так))
#%%
d = [(p, str(learn.predict(x[0])[0])) for x, p in zip(data.test_ds, data.test_ds.items)]
d[:4]
#%%
res = [
(str(p)[-8:-4], c)
for p, c in d
]
res = sorted(res)
res[:4]
#%%
import numpy as np
import pandas as pd
#%%
ids = np.arange(0, 660)
ids = list(map('{0:04d}'.format, ids))
df = pd.DataFrame(ids, columns=['id'])
df['label'] = 'dirty'
for i, c in res:
df.loc[df['id'] == i, 'label'] = c
#%%
df.head(10)
#%%
df.to_csv('./out/submission.csv', sep=',', index=False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment