Learner

fastai Learner extensions.


source

Learner.show_batch


def show_batch(
    kwargs:VAR_KEYWORD
):

Call self as a function.


source

Learner.remove_all_cbs


def remove_all_cbs(
    max_iters:int=10
):

Call self as a function.


source

Learner.one_batch


def one_batch(
    i, b
):

Call self as a function.


source

Learner.inverse_transform


def inverse_transform(
    df:DataFrame
):

Applies sklearn-type pipeline inverse transforms


source

Learner.transform


def transform(
    df:DataFrame
):

Applies sklearn-type pipeline transforms

⚠️ Important: save_all and load_all methods are designed for small datasets only. If you are using a larger dataset, you should use the standard save and load_learner methods.


source

load_all


def load_all(
    path:str='export', dls_fname:str='dls', model_fname:str='model', learner_fname:str='learner',
    device:NoneType=None, pickle_module:module=pickle, verbose:bool=False
):

Call self as a function.


source

Learner.save_all


def save_all(
    path:str='export', dls_fname:str='dls', model_fname:str='model', learner_fname:str='learner', verbose:bool=False
):

Call self as a function.

from tsai.data.core import get_ts_dls
from tsai.utils import remove_dir
X = np.random.rand(100, 2, 10)
dls = get_ts_dls(X)
learn = Learner(dls, InceptionTimePlus(2, 1), loss_func=MSELossFlat())
learn.save_all(Path.home()/'tmp', verbose=True)
learn2 = load_all(Path.home()/'tmp', verbose=True)
remove_dir(Path.home()/'tmp')
Learner saved:
path          = '/Users/nacho/tmp'
dls_fname     = '['dls_0.pth', 'dls_1.pth']'
model_fname   = 'model.pth'
learner_fname = 'learner.pkl'
Learner loaded:
path          = '/Users/nacho/tmp'
dls_fname     = '['dls_0.pth', 'dls_1.pth']'
model_fname   = 'model.pth'
learner_fname = 'learner.pkl'
/Users/nacho/tmp directory removed.

source

Learner.plot_metrics


def plot_metrics(
    nrows:int=1, # Number of rows in returned axes grid
    ncols:int=1, # Number of columns in returned axes grid
    figsize:tuple=None, # Width, height in inches of the returned figure
    imsize:int=3, # Size (in inches) of images that will be displayed in the returned figure
    suptitle:str=None, # Title to be set to returned figure
    sharex:bool | Literal['none', 'all', 'row', 'col']=False,
    sharey:bool | Literal['none', 'all', 'row', 'col']=False, squeeze:bool=True,
    width_ratios:Sequence[float] | None=None, height_ratios:Sequence[float] | None=None,
    subplot_kw:dict[str, Any] | None=None, gridspec_kw:dict[str, Any] | None=None
): # Returns both fig and ax as a tuple

Call self as a function.


source

Recorder.plot_metrics


def plot_metrics(
    nrows:NoneType=None, # Number of rows in returned axes grid
    ncols:NoneType=None, # Number of columns in returned axes grid
    figsize:NoneType=None, # Width, height in inches of the returned figure
    final_losses:bool=True, perc:float=0.5,
    imsize:int=3, # Size (in inches) of images that will be displayed in the returned figure
    suptitle:str=None, # Title to be set to returned figure
    sharex:bool | Literal['none', 'all', 'row', 'col']=False,
    sharey:bool | Literal['none', 'all', 'row', 'col']=False, squeeze:bool=True,
    width_ratios:Sequence[float] | None=None, height_ratios:Sequence[float] | None=None,
    subplot_kw:dict[str, Any] | None=None, gridspec_kw:dict[str, Any] | None=None
): # Returns both fig and ax as a tuple

Call self as a function.


source

get_arch


def get_arch(
    arch_name
):

Call self as a function.

for arch_name in all_arch_names:
    get_arch(arch_name)

source

ts_learner


def ts_learner(
    dls, arch:NoneType=None, c_in:NoneType=None, c_out:NoneType=None, seq_len:NoneType=None, d:NoneType=None,
    s_cat_idxs:NoneType=None, s_cat_embeddings:NoneType=None, s_cat_embedding_dims:NoneType=None,
    s_cont_idxs:NoneType=None, o_cat_idxs:NoneType=None, o_cat_embeddings:NoneType=None,
    o_cat_embedding_dims:NoneType=None, o_cont_idxs:NoneType=None, splitter:function=trainable_params,
    loss_func:NoneType=None, opt_func:function=Adam, lr:float=0.001, cbs:NoneType=None, metrics:NoneType=None,
    path:NoneType=None, model_dir:str='models', wd:NoneType=None, wd_bn_bias:bool=False, train_bn:bool=True,
    moms:tuple=(0.95, 0.85, 0.95), train_metrics:bool=False, valid_metrics:bool=True, seed:NoneType=None,
    device:NoneType=None, verbose:bool=False, patch_len:NoneType=None, patch_stride:NoneType=None,
    fusion_layers:int=128, fusion_act:str='relu', fusion_dropout:float=0.0, fusion_use_bn:bool=True,
    pretrained:bool=False, weights_path:NoneType=None, exclude_head:bool=True, cut:int=-1, init:NoneType=None,
    arch_config:dict={}
)->Learner:

Call self as a function.


source

tsimage_learner


def tsimage_learner(
    dls, arch:NoneType=None, pretrained:bool=False, loss_func:NoneType=None, opt_func:function=Adam, lr:float=0.001,
    cbs:NoneType=None, metrics:NoneType=None, path:NoneType=None, model_dir:str='models', wd:NoneType=None,
    wd_bn_bias:bool=False, train_bn:bool=True, moms:tuple=(0.95, 0.85, 0.95), c_in:NoneType=None,
    c_out:NoneType=None, device:NoneType=None, verbose:bool=False, init:NoneType=None, arch_config:dict={}
):

Call self as a function.


source

Learner.decoder


def decoder(
    o
):

Call self as a function.

from tsai.data.core import *
from tsai.data.external import get_UCR_data
from tsai.models.FCNPlus import FCNPlus
X, y, splits = get_UCR_data('OliveOil', verbose=True, split_data=False)
tfms  = [None, [TSCategorize()]]
dls = get_ts_dls(X, y, splits=splits, tfms=tfms)
learn = ts_learner(dls, FCNPlus)
for p in learn.model.parameters():
    p.requires_grad=False
test_eq(count_parameters(learn.model), 0)
learn.freeze()
test_eq(count_parameters(learn.model), 1540)
learn.unfreeze()
test_eq(count_parameters(learn.model), 264580)

learn = ts_learner(dls, 'FCNPlus')
for p in learn.model.parameters():
    p.requires_grad=False
test_eq(count_parameters(learn.model), 0)
learn.freeze()
test_eq(count_parameters(learn.model), 1540)
learn.unfreeze()
test_eq(count_parameters(learn.model), 264580)
Dataset: OliveOil
X      : (60, 1, 570)
y      : (60,)
splits : (#30) [0,1,2,3,4,5,6,7,8,9...] (#30) [30,31,32,33,34,35,36,37,38,39...] 
learn.show_batch();

from fastai.metrics import accuracy
from tsai.data.preprocessing import TSRobustScale
X, y, splits = get_UCR_data('OliveOil', split_data=False)
tfms  = [None, TSClassification()]
batch_tfms = TSRobustScale()
dls = get_ts_dls(X, y, tfms=tfms, splits=splits, batch_tfms=batch_tfms)
learn = ts_learner(dls, FCNPlus, metrics=accuracy, train_metrics=True)
learn.fit_one_cycle(2)
learn.plot_metrics()
epoch train_loss train_accuracy valid_loss valid_accuracy time
0 1.480875 0.266667 1.390461 0.300000 00:02
1 1.476655 0.266667 1.387370 0.300000 00:01

if not os.path.exists("./models"): os.mkdir("./models")
if not os.path.exists("./data"): os.mkdir("./data")
np.save("data/X_test.npy", X[splits[1]])
np.save("data/y_test.npy", y[splits[1]])
learn.export("./models/test.pth")