soilspecdl 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- soilspecdl/__init__.py +1 -0
- soilspecdl/_modidx.py +48 -0
- soilspecdl/core.py +9 -0
- soilspecdl/dataloader.py +127 -0
- soilspecdl/models.py +103 -0
- soilspecdl-0.0.1.dist-info/METADATA +226 -0
- soilspecdl-0.0.1.dist-info/RECORD +11 -0
- soilspecdl-0.0.1.dist-info/WHEEL +5 -0
- soilspecdl-0.0.1.dist-info/entry_points.txt +2 -0
- soilspecdl-0.0.1.dist-info/licenses/LICENSE +201 -0
- soilspecdl-0.0.1.dist-info/top_level.txt +1 -0
soilspecdl/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.0.1"
|
soilspecdl/_modidx.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# Autogenerated by nbdev
|
|
2
|
+
|
|
3
|
+
d = { 'settings': { 'branch': 'main',
|
|
4
|
+
'doc_baseurl': '/soilspecdl',
|
|
5
|
+
'doc_host': 'https://franckalbinet.github.io',
|
|
6
|
+
'git_url': 'https://github.com/franckalbinet/soilspecdl',
|
|
7
|
+
'lib_path': 'soilspecdl'},
|
|
8
|
+
'syms': { 'soilspecdl.core': {'soilspecdl.core.foo': ('core.html#foo', 'soilspecdl/core.py')},
|
|
9
|
+
'soilspecdl.dataloader': { 'soilspecdl.dataloader.RegressionFloatBlock': ( 'dataloader.html#regressionfloatblock',
|
|
10
|
+
'soilspecdl/dataloader.py'),
|
|
11
|
+
'soilspecdl.dataloader.SpectralBlock': ('dataloader.html#spectralblock', 'soilspecdl/dataloader.py'),
|
|
12
|
+
'soilspecdl.dataloader.SpectralTarget': ( 'dataloader.html#spectraltarget',
|
|
13
|
+
'soilspecdl/dataloader.py'),
|
|
14
|
+
'soilspecdl.dataloader.SpectralTarget.__repr__': ( 'dataloader.html#spectraltarget.__repr__',
|
|
15
|
+
'soilspecdl/dataloader.py'),
|
|
16
|
+
'soilspecdl.dataloader.SpectralTarget.show': ( 'dataloader.html#spectraltarget.show',
|
|
17
|
+
'soilspecdl/dataloader.py'),
|
|
18
|
+
'soilspecdl.dataloader.TensorSpectrum': ( 'dataloader.html#tensorspectrum',
|
|
19
|
+
'soilspecdl/dataloader.py'),
|
|
20
|
+
'soilspecdl.dataloader.TensorSpectrum.__repr__': ( 'dataloader.html#tensorspectrum.__repr__',
|
|
21
|
+
'soilspecdl/dataloader.py'),
|
|
22
|
+
'soilspecdl.dataloader.TensorSpectrum.show': ( 'dataloader.html#tensorspectrum.show',
|
|
23
|
+
'soilspecdl/dataloader.py'),
|
|
24
|
+
'soilspecdl.dataloader.get_ks_splitter': ( 'dataloader.html#get_ks_splitter',
|
|
25
|
+
'soilspecdl/dataloader.py'),
|
|
26
|
+
'soilspecdl.dataloader.get_mir_k_1k_smp': ( 'dataloader.html#get_mir_k_1k_smp',
|
|
27
|
+
'soilspecdl/dataloader.py'),
|
|
28
|
+
'soilspecdl.dataloader.get_spectral_dls': ( 'dataloader.html#get_spectral_dls',
|
|
29
|
+
'soilspecdl/dataloader.py'),
|
|
30
|
+
'soilspecdl.dataloader.get_splitter': ('dataloader.html#get_splitter', 'soilspecdl/dataloader.py'),
|
|
31
|
+
'soilspecdl.dataloader.show_batch': ('dataloader.html#show_batch', 'soilspecdl/dataloader.py')},
|
|
32
|
+
'soilspecdl.models': { 'soilspecdl.models.ConvBlock': ('models.html#convblock', 'soilspecdl/models.py'),
|
|
33
|
+
'soilspecdl.models.ConvBlock.__init__': ('models.html#convblock.__init__', 'soilspecdl/models.py'),
|
|
34
|
+
'soilspecdl.models.ConvBlock.forward': ('models.html#convblock.forward', 'soilspecdl/models.py'),
|
|
35
|
+
'soilspecdl.models.ConvBlockBaseline': ('models.html#convblockbaseline', 'soilspecdl/models.py'),
|
|
36
|
+
'soilspecdl.models.ConvBlockBaseline.__init__': ( 'models.html#convblockbaseline.__init__',
|
|
37
|
+
'soilspecdl/models.py'),
|
|
38
|
+
'soilspecdl.models.ConvBlockBaseline.forward': ( 'models.html#convblockbaseline.forward',
|
|
39
|
+
'soilspecdl/models.py'),
|
|
40
|
+
'soilspecdl.models.FeatureExtractor': ('models.html#featureextractor', 'soilspecdl/models.py'),
|
|
41
|
+
'soilspecdl.models.FeatureExtractor.__init__': ( 'models.html#featureextractor.__init__',
|
|
42
|
+
'soilspecdl/models.py'),
|
|
43
|
+
'soilspecdl.models.FeatureExtractor.forward': ( 'models.html#featureextractor.forward',
|
|
44
|
+
'soilspecdl/models.py'),
|
|
45
|
+
'soilspecdl.models.MirzaiCNN': ('models.html#mirzaicnn', 'soilspecdl/models.py'),
|
|
46
|
+
'soilspecdl.models.MirzaiCNN.__init__': ('models.html#mirzaicnn.__init__', 'soilspecdl/models.py'),
|
|
47
|
+
'soilspecdl.models.MirzaiCNN.forward': ('models.html#mirzaicnn.forward', 'soilspecdl/models.py'),
|
|
48
|
+
'soilspecdl.models.cnt_params': ('models.html#cnt_params', 'soilspecdl/models.py')}}}
|
soilspecdl/core.py
ADDED
soilspecdl/dataloader.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"""Fastai DataLoader for spectroscopy data"""
|
|
2
|
+
|
|
3
|
+
# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/01_dataloader.ipynb.
|
|
4
|
+
|
|
5
|
+
# %% auto #0
|
|
6
|
+
__all__ = ['get_mir_k_1k_smp', 'get_ks_splitter', 'get_splitter', 'SpectralTarget', 'TensorSpectrum', 'show_batch',
|
|
7
|
+
'SpectralBlock', 'RegressionFloatBlock', 'get_spectral_dls']
|
|
8
|
+
|
|
9
|
+
# %% ../nbs/01_dataloader.ipynb #803b246c
|
|
10
|
+
import pandas as pd
|
|
11
|
+
import numpy as np
|
|
12
|
+
import torch
|
|
13
|
+
import matplotlib.pyplot as plt
|
|
14
|
+
#from torch.utils.data import DataLoader, SubsetRandomSampler
|
|
15
|
+
#from fastai.data.core import DataLoaders
|
|
16
|
+
from fastai.torch_core import TensorBase
|
|
17
|
+
from fastai.data.block import DataBlock, TransformBlock
|
|
18
|
+
from kennard_stone import train_test_split as ks_split
|
|
19
|
+
from fastai.data.block import RegressionBlock
|
|
20
|
+
from fastai.torch_core import TitledFloat
|
|
21
|
+
from plum import dispatch
|
|
22
|
+
|
|
23
|
+
import logging
|
|
24
|
+
logging.getLogger('kennard_stone').setLevel(logging.WARNING)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
# %% ../nbs/01_dataloader.ipynb #793adc74
|
|
28
|
+
def get_mir_k_1k_smp():
|
|
29
|
+
"Load MIR Kex (exchangeable potassium) 1000 subsamples from OSSL"
|
|
30
|
+
url = "https://gist.githubusercontent.com/franckalbinet/613654a8908e5fa6bf131b9b267815f3/raw/0feb62ff4d0a26f2befb657aa87745b756de89b0/mir-k-subset-1000.csv"
|
|
31
|
+
df = pd.read_csv(url)
|
|
32
|
+
y = df.iloc[:, -1].to_numpy()
|
|
33
|
+
X = df.iloc[:,:-1].to_numpy()
|
|
34
|
+
wns = df.columns[:-1].to_numpy().astype(int)
|
|
35
|
+
return X, y, wns
|
|
36
|
+
|
|
37
|
+
# %% ../nbs/01_dataloader.ipynb #0d7cc7f8
|
|
38
|
+
def get_ks_splitter(test_size=0.1, valid_size=0.1):
|
|
39
|
+
def _inner(X, y):
|
|
40
|
+
train_val_X, test_X, train_val_idx, test_idx = ks_split(X, np.arange(len(X)), test_size=test_size)
|
|
41
|
+
_, _, train_idx, valid_idx = ks_split(train_val_X, train_val_idx, test_size=valid_size / (1 - test_size))
|
|
42
|
+
return train_idx, valid_idx, test_idx
|
|
43
|
+
return _inner
|
|
44
|
+
|
|
45
|
+
# %% ../nbs/01_dataloader.ipynb #6abaf166
|
|
46
|
+
def get_splitter(train_pct=0.8, valid_pct=0.1, seed=42):
|
|
47
|
+
def _inner(X, y):
|
|
48
|
+
if not np.isclose(train_pct + valid_pct + (1-train_pct-valid_pct), 1.0):
|
|
49
|
+
raise ValueError("Split proportions must sum to 1")
|
|
50
|
+
n = len(X)
|
|
51
|
+
np.random.seed(seed)
|
|
52
|
+
shuffled_idx = np.random.permutation(n)
|
|
53
|
+
train_size = int(train_pct * n)
|
|
54
|
+
valid_size = int(valid_pct * n)
|
|
55
|
+
train_idx = shuffled_idx[:train_size]
|
|
56
|
+
valid_idx = shuffled_idx[train_size:train_size + valid_size]
|
|
57
|
+
test_idx = shuffled_idx[train_size + valid_size:]
|
|
58
|
+
return train_idx, valid_idx, test_idx
|
|
59
|
+
return _inner
|
|
60
|
+
|
|
61
|
+
# %% ../nbs/01_dataloader.ipynb #ca00acbb
|
|
62
|
+
class SpectralTarget(TitledFloat):
|
|
63
|
+
def show(self, ctx=None, **kwargs):
|
|
64
|
+
if ctx is not None: ctx.set_title(f"Target: {self:.3f}")
|
|
65
|
+
return ctx
|
|
66
|
+
|
|
67
|
+
def __repr__(self): return f"{float(self):.3f}"
|
|
68
|
+
|
|
69
|
+
# %% ../nbs/01_dataloader.ipynb #b3b6ba0f
|
|
70
|
+
class TensorSpectrum(TensorBase):
|
|
71
|
+
wns = None # set after loading data: TensorSpectrum.wns = wns
|
|
72
|
+
|
|
73
|
+
def show(self, ctx=None, title=None, figsize=None, **kwargs):
|
|
74
|
+
if ctx is None: _, ctx = plt.subplots(figsize=figsize)
|
|
75
|
+
ctx.plot(self.__class__.wns, self.squeeze().cpu(), **kwargs)
|
|
76
|
+
ctx.invert_xaxis()
|
|
77
|
+
ctx.grid(True)
|
|
78
|
+
if title is not None: ctx.set_title(f"Target value: {float(title):.3f}")
|
|
79
|
+
return ctx
|
|
80
|
+
|
|
81
|
+
def __repr__(self): return f"TensorSpectrum(shape={tuple(self.shape)})"
|
|
82
|
+
|
|
83
|
+
# %% ../nbs/01_dataloader.ipynb #5517f728
|
|
84
|
+
@dispatch
|
|
85
|
+
def show_batch(
|
|
86
|
+
x:TensorSpectrum, # Spectra (features)
|
|
87
|
+
y, # Soil property (target)
|
|
88
|
+
samples,
|
|
89
|
+
ctxs=None,
|
|
90
|
+
max_n=9,
|
|
91
|
+
ncols=3,
|
|
92
|
+
figsize=None,
|
|
93
|
+
**kwargs
|
|
94
|
+
):
|
|
95
|
+
n = min(len(samples), max_n)
|
|
96
|
+
ncols = min(ncols, n)
|
|
97
|
+
nrows = (n + ncols - 1) // ncols
|
|
98
|
+
if figsize is None: figsize = (6*ncols, 3*nrows)
|
|
99
|
+
fig, axs = plt.subplots(nrows, ncols, figsize=figsize)
|
|
100
|
+
axs = np.array(axs).flatten()
|
|
101
|
+
for s, ax in zip(samples[:n], axs[:n]):
|
|
102
|
+
s[0].show(ctx=ax, title=s[1], **kwargs)
|
|
103
|
+
for ax in axs[n:]: ax.axis('off')
|
|
104
|
+
plt.tight_layout()
|
|
105
|
+
|
|
106
|
+
# %% ../nbs/01_dataloader.ipynb #0b74f4d0
|
|
107
|
+
def SpectralBlock():
|
|
108
|
+
return TransformBlock(type_tfms=lambda x: TensorSpectrum(torch.tensor(x, dtype=torch.float32).unsqueeze(0)))
|
|
109
|
+
|
|
110
|
+
# %% ../nbs/01_dataloader.ipynb #7b3c460c
|
|
111
|
+
def RegressionFloatBlock():
|
|
112
|
+
return TransformBlock(type_tfms=lambda x: SpectralTarget(x))
|
|
113
|
+
|
|
114
|
+
# %% ../nbs/01_dataloader.ipynb #4a58cc06
|
|
115
|
+
def get_spectral_dls(X, y, wns, splitter=None, bs=32):
|
|
116
|
+
if splitter is None: splitter = get_splitter()
|
|
117
|
+
TensorSpectrum.wns = wns
|
|
118
|
+
train_idx, valid_idx, test_idx = splitter(X, y)
|
|
119
|
+
items = list(range(len(X)))
|
|
120
|
+
def _ds_splitter(o): return list(train_idx), list(valid_idx)
|
|
121
|
+
dblock = DataBlock(
|
|
122
|
+
blocks=(SpectralBlock(), RegressionBlock()),
|
|
123
|
+
splitter=_ds_splitter,
|
|
124
|
+
get_x=lambda i: X[i],
|
|
125
|
+
get_y=lambda i: y[i],
|
|
126
|
+
)
|
|
127
|
+
return dblock.dataloaders(items, bs=bs), test_idx
|
soilspecdl/models.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Models for the SoilspecDL project"""
|
|
2
|
+
|
|
3
|
+
# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/00_models.ipynb.
|
|
4
|
+
|
|
5
|
+
# %% auto #0
|
|
6
|
+
__all__ = ['ConvBlockBaseline', 'ConvBlock', 'FeatureExtractor', 'MirzaiCNN', 'cnt_params']
|
|
7
|
+
|
|
8
|
+
# %% ../nbs/00_models.ipynb #2bb84e93
|
|
9
|
+
from functools import partial
|
|
10
|
+
import torch
|
|
11
|
+
from torch.nn import (Module, AvgPool1d, LeakyReLU,
|
|
12
|
+
AdaptiveAvgPool1d, Sequential,
|
|
13
|
+
Dropout, Linear)
|
|
14
|
+
|
|
15
|
+
from fastai.layers import ConvLayer
|
|
16
|
+
from typing import Callable
|
|
17
|
+
|
|
18
|
+
# %% ../nbs/00_models.ipynb #d77ba715
|
|
19
|
+
class ConvBlockBaseline(Module):
|
|
20
|
+
def __init__(self, ni, nf):
|
|
21
|
+
super().__init__()
|
|
22
|
+
self.conv = Sequential(
|
|
23
|
+
torch.nn.Conv1d(ni, nf, kernel_size=3, stride=1, padding=1, bias=False),
|
|
24
|
+
torch.nn.BatchNorm1d(nf),
|
|
25
|
+
torch.nn.LeakyReLU(negative_slope=0.1)
|
|
26
|
+
)
|
|
27
|
+
self.pool = torch.nn.AvgPool1d(3)
|
|
28
|
+
|
|
29
|
+
def forward(self, x): return self.pool(self.conv(x))
|
|
30
|
+
|
|
31
|
+
# %% ../nbs/00_models.ipynb #654a2525
|
|
32
|
+
class ConvBlock(Module):
|
|
33
|
+
"Convolutional block with pooling."
|
|
34
|
+
def __init__(self,
|
|
35
|
+
ni, # input channels
|
|
36
|
+
nf, # output channels
|
|
37
|
+
ks=3, # kernel size
|
|
38
|
+
stride=1, # stride
|
|
39
|
+
act_cls=partial(LeakyReLU, negative_slope=0.1)
|
|
40
|
+
):
|
|
41
|
+
super().__init__()
|
|
42
|
+
self.conv = ConvLayer(ni, nf, ks=ks, stride=stride, bias=False,
|
|
43
|
+
# norm_type='NormType.Instance',
|
|
44
|
+
# norm_type='NormType.Batch',
|
|
45
|
+
act_cls=act_cls,
|
|
46
|
+
ndim=1)
|
|
47
|
+
self.pool = AvgPool1d(3)
|
|
48
|
+
|
|
49
|
+
def forward(self, x): return self.pool(self.conv(x))
|
|
50
|
+
|
|
51
|
+
# %% ../nbs/00_models.ipynb #ead64c03
|
|
52
|
+
class FeatureExtractor(Module):
|
|
53
|
+
def __init__(self,
|
|
54
|
+
in_channel=1, # input channels
|
|
55
|
+
out_channel=16, # base number of filters
|
|
56
|
+
conv_block_cls=ConvBlock,
|
|
57
|
+
):
|
|
58
|
+
super().__init__()
|
|
59
|
+
nfs = [out_channel * 2**i for i in range(5)]
|
|
60
|
+
self.layers = Sequential(*[
|
|
61
|
+
conv_block_cls(ni=in_channel if i==0 else nfs[i-1], nf=nfs[i])
|
|
62
|
+
for i in range(len(nfs))
|
|
63
|
+
])
|
|
64
|
+
self.adaptive_pool = AdaptiveAvgPool1d(1)
|
|
65
|
+
|
|
66
|
+
def forward(self, x):
|
|
67
|
+
x = self.layers(x)
|
|
68
|
+
return self.adaptive_pool(x)
|
|
69
|
+
|
|
70
|
+
# %% ../nbs/00_models.ipynb #f49cdcea
|
|
71
|
+
class MirzaiCNN(Module):
|
|
72
|
+
"""
|
|
73
|
+
1D Convolutional Neural Network for spectral data regression/classification.
|
|
74
|
+
|
|
75
|
+
Based on the architecture proposed in:
|
|
76
|
+
Albinet, F., Peng, Y., Eguchi, T., Smolders, E., Dercon, G., 2022. Prediction of exchangeable potassium in soil through mid-infrared spectroscopy and deep learning: From prediction to explainability. Artificial Intelligence in Agriculture 6, 230–241. https://doi.org/10.1016/j.aiia.2022.10.001
|
|
77
|
+
"""
|
|
78
|
+
def __init__(self,
|
|
79
|
+
in_channel: int=1, # input channels
|
|
80
|
+
out_channel: int=16, # base number of filters
|
|
81
|
+
conv_block_cls: Callable = ConvBlock,
|
|
82
|
+
is_classifier: bool=False, # if True, model will output probabilities
|
|
83
|
+
dropout: float=0.4 # dropout rate
|
|
84
|
+
):
|
|
85
|
+
super().__init__()
|
|
86
|
+
self.backbone = FeatureExtractor(in_channel, out_channel, conv_block_cls)
|
|
87
|
+
self.head = Sequential(
|
|
88
|
+
Dropout(dropout),
|
|
89
|
+
Linear(256, 1))
|
|
90
|
+
self.is_classifier = is_classifier
|
|
91
|
+
|
|
92
|
+
def forward(self, x):
|
|
93
|
+
x = self.backbone(x)
|
|
94
|
+
x = x.squeeze(-1)
|
|
95
|
+
x = self.head(x)
|
|
96
|
+
x = x.squeeze(-1)
|
|
97
|
+
return torch.sigmoid(x) if self.is_classifier else x
|
|
98
|
+
|
|
99
|
+
# %% ../nbs/00_models.ipynb #86f4147b
|
|
100
|
+
def cnt_params(model):
|
|
101
|
+
for name, param in model.named_parameters():
|
|
102
|
+
print(f"{name}: {param.numel():,} parameters")
|
|
103
|
+
print(f"\nTotal: {sum(p.numel() for p in model.parameters()):,} parameters")
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: soilspecdl
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Practical deep learning for soil infrared spectroscopy, built on the fastai framework.
|
|
5
|
+
Author-email: Franck Albinet <franckalbinet@gmail.com>
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Repository, https://github.com/franckalbinet/soilspecdl
|
|
8
|
+
Project-URL: Documentation, https://franckalbinet.github.io/soilspecdl/
|
|
9
|
+
Keywords: nbdev
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
12
|
+
Requires-Python: >=3.10
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Requires-Dist: fastai
|
|
16
|
+
Requires-Dist: soilspectfm
|
|
17
|
+
Requires-Dist: soilspecdata
|
|
18
|
+
Requires-Dist: pandas
|
|
19
|
+
Requires-Dist: seaborn
|
|
20
|
+
Requires-Dist: kennard-stone
|
|
21
|
+
Dynamic: license-file
|
|
22
|
+
|
|
23
|
+
# SoilSpecDL
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
|
|
27
|
+
|
|
28
|
+
**Practical deep learning for soil infrared spectroscopy, built on the
|
|
29
|
+
fastai framework.**
|
|
30
|
+
|
|
31
|
+
`soilspecdl` brings the [fastai](https://www.fast.ai/) philosophy to
|
|
32
|
+
soil spectroscopy: state-of-the-art deep learning models should be
|
|
33
|
+
accessible to domain scientists, not just ML practitioners. If you are a
|
|
34
|
+
soil scientist comfortable with R packages like `resemble` or
|
|
35
|
+
`prospectr`, this package is designed with you in mind.
|
|
36
|
+
|
|
37
|
+
Built on top of [fastai](https://www.fast.ai/) — a library renowned for
|
|
38
|
+
making deep learning approachable without sacrificing performance —
|
|
39
|
+
`soilspecdl` provides sensible defaults, minimal boilerplate, and a
|
|
40
|
+
layered API that lets you go deeper when you need to. Training a CNN on
|
|
41
|
+
a large MIR spectral library should take a few lines of code, not a PhD
|
|
42
|
+
in machine learning.
|
|
43
|
+
|
|
44
|
+
`soilspecdl` is part of a broader ecosystem for soil spectroscopy in
|
|
45
|
+
Python:
|
|
46
|
+
|
|
47
|
+
- [`soilspecdata`](https://fr.anckalbi.net/soilspecdata/) — fetch and
|
|
48
|
+
access large spectral libraries (KSSL, OSSL)
|
|
49
|
+
- [`soilspectfm`](https://fr.anckalbi.net/soilspectfm/) — preprocessing
|
|
50
|
+
and spectral transforms
|
|
51
|
+
- **`SoilSpecDL`** — deep learning modeling
|
|
52
|
+
|
|
53
|
+
## Get Started
|
|
54
|
+
|
|
55
|
+
``` python
|
|
56
|
+
from soilspecdata.datasets.ossl import get_ossl
|
|
57
|
+
from soilspectfm.core import SNV, TakeDerivative
|
|
58
|
+
from sklearn.pipeline import Pipeline
|
|
59
|
+
import numpy as np
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Load OSSL/USDA KSSL + ICRAF + … dataset large soil spectroscopy library
|
|
63
|
+
using the [SoilSpecData](https://fr.anckalbi.net/soilspecdata) python
|
|
64
|
+
package:
|
|
65
|
+
|
|
66
|
+
``` python
|
|
67
|
+
ossl = get_ossl()
|
|
68
|
+
mir_data = ossl.get_mir()
|
|
69
|
+
wns = mir_data.wavenumbers
|
|
70
|
+
|
|
71
|
+
X, y, ids = ossl.get_aligned_data(
|
|
72
|
+
spectra_data=mir_data,
|
|
73
|
+
target_cols='k.ext_usda.a725_cmolc.kg')
|
|
74
|
+
|
|
75
|
+
X.shape, y.shape, ids.shape, wns[:5], wns.shape
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
((57676, 1701),
|
|
79
|
+
(57676, 1),
|
|
80
|
+
(57676,),
|
|
81
|
+
array([600, 602, 604, 606, 608]),
|
|
82
|
+
(1701,))
|
|
83
|
+
|
|
84
|
+
A bit of pre-processing using
|
|
85
|
+
[SoilSpecTfm](https://fr.anckalbi.net/soilspectfm) python package:
|
|
86
|
+
|
|
87
|
+
``` python
|
|
88
|
+
pipe = Pipeline([
|
|
89
|
+
('snv', SNV()),
|
|
90
|
+
('derivative', TakeDerivative()),
|
|
91
|
+
])
|
|
92
|
+
X_tfm = pipe.fit_transform(X)
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
``` python
|
|
96
|
+
# Log-transforming the target (Exchangeable Potassium)
|
|
97
|
+
y_tfm = np.log1p(y.flatten())
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
``` python
|
|
101
|
+
from soilspecdl.dataloader import get_spectral_dls
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
Create a Fastai-like data loader with nice batch preview:
|
|
105
|
+
|
|
106
|
+
``` python
|
|
107
|
+
dls, test_idx = get_spectral_dls(X_tfm, y_tfm, wns)
|
|
108
|
+
dls.show_batch(max_n=12, ncols=4)
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+

|
|
112
|
+
|
|
113
|
+
Importing [albinet et
|
|
114
|
+
al.](https://www.sciencedirect.com/science/article/pii/S2589721722000186)
|
|
115
|
+
paper CNN architecture, fastai Learner, …
|
|
116
|
+
|
|
117
|
+
``` python
|
|
118
|
+
from soilspecdl.models import MirzaiCNN
|
|
119
|
+
from fastai.learner import Learner
|
|
120
|
+
from fastai.callback.schedule import lr_find
|
|
121
|
+
from fastai.losses import MSELossFlat
|
|
122
|
+
from fastai.metrics import R2Score
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
``` python
|
|
126
|
+
learn = Learner(dls, MirzaiCNN(), loss_func=MSELossFlat(), metrics=R2Score())
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
Finding “best” learning rate:
|
|
130
|
+
|
|
131
|
+
``` python
|
|
132
|
+
learn.lr_find()
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
Epoch 1/1 : |█-------------------| 5.07% [73/1441 00:00<00:12... 0.2062]
|
|
136
|
+
|
|
137
|
+
SuggestedLRs(valley=0.0020892962347716093)
|
|
138
|
+
|
|
139
|
+

|
|
140
|
+
|
|
141
|
+
``` python
|
|
142
|
+
learn.fit_one_cycle(40, lr_max=1e-3)
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
epoch train_loss valid_loss r2_score time
|
|
146
|
+
0 0.110809 0.084269 0.394419 00:07
|
|
147
|
+
1 0.079789 0.069087 0.503516 00:15
|
|
148
|
+
2 0.074917 0.060016 0.568708 00:07
|
|
149
|
+
3 0.064447 0.064101 0.539350 00:07
|
|
150
|
+
4 0.054324 0.056243 0.595819 00:07
|
|
151
|
+
5 0.061540 0.059759 0.570552 00:06
|
|
152
|
+
6 0.057230 0.138288 0.006216 00:07
|
|
153
|
+
7 0.057897 0.121253 0.128639 00:08
|
|
154
|
+
8 0.052471 0.092067 0.338378 00:07
|
|
155
|
+
9 0.045639 0.044204 0.682335 00:15
|
|
156
|
+
10 0.048287 0.184855 -0.328426 00:06
|
|
157
|
+
11 0.043516 0.108474 0.220473 00:06
|
|
158
|
+
12 0.040384 0.038102 0.726186 00:07
|
|
159
|
+
13 0.040395 0.063995 0.540110 00:06
|
|
160
|
+
14 0.034513 0.057830 0.584413 00:06
|
|
161
|
+
15 0.037132 0.044052 0.683426 00:06
|
|
162
|
+
16 0.036089 0.051145 0.632458 00:07
|
|
163
|
+
17 0.032155 0.074059 0.467791 00:15
|
|
164
|
+
18 0.034771 0.040014 0.712450 00:08
|
|
165
|
+
19 0.031389 0.068343 0.508866 00:06
|
|
166
|
+
20 0.033233 0.066360 0.523116 00:06
|
|
167
|
+
21 0.032475 0.035962 0.741569 00:07
|
|
168
|
+
22 0.028055 0.037719 0.728938 00:15
|
|
169
|
+
23 0.029821 0.068363 0.508722 00:07
|
|
170
|
+
24 0.027841 0.030044 0.784094 00:07
|
|
171
|
+
25 0.025044 0.029944 0.784813 00:06
|
|
172
|
+
26 0.026742 0.033762 0.757377 00:06
|
|
173
|
+
27 0.023458 0.043821 0.685087 00:06
|
|
174
|
+
28 0.022406 0.031492 0.773691 00:14
|
|
175
|
+
29 0.024227 0.027881 0.799640 00:15
|
|
176
|
+
30 0.022663 0.028077 0.798226 00:06
|
|
177
|
+
31 0.020502 0.028358 0.796213 00:06
|
|
178
|
+
32 0.021859 0.026163 0.811988 00:06
|
|
179
|
+
33 0.019432 0.027430 0.802882 00:07
|
|
180
|
+
34 0.019836 0.025392 0.817526 00:07
|
|
181
|
+
35 0.018150 0.025433 0.817233 00:07
|
|
182
|
+
36 0.020574 0.025172 0.819103 00:07
|
|
183
|
+
37 0.019895 0.025199 0.818912 00:14
|
|
184
|
+
38 0.019346 0.025025 0.820163 00:15
|
|
185
|
+
39 0.019031 0.025060 0.819907 00:06
|
|
186
|
+
|
|
187
|
+
## Developer Guide
|
|
188
|
+
|
|
189
|
+
If you are new to using `nbdev` here are some useful pointers to get you
|
|
190
|
+
started.
|
|
191
|
+
|
|
192
|
+
### Install soilspecai in Development mode
|
|
193
|
+
|
|
194
|
+
``` sh
|
|
195
|
+
# make sure soilspecai package is installed in development mode
|
|
196
|
+
$ pip install -e .
|
|
197
|
+
|
|
198
|
+
# make changes under nbs/ directory
|
|
199
|
+
# ...
|
|
200
|
+
|
|
201
|
+
# compile to have changes apply to soilspecai
|
|
202
|
+
$ nbdev_prepare
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
## Usage
|
|
206
|
+
|
|
207
|
+
### Installation
|
|
208
|
+
|
|
209
|
+
Install latest from the GitHub
|
|
210
|
+
[repository](https://github.com/franckalbinet/soilspecdl):
|
|
211
|
+
|
|
212
|
+
``` sh
|
|
213
|
+
$ pip install git+https://github.com/franckalbinet/soilspecdl.git
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
or from [conda](https://anaconda.org/franckalbinet/soilspecdl)
|
|
217
|
+
|
|
218
|
+
``` sh
|
|
219
|
+
$ conda install -c franckalbinet soilspecdl
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
or from [pypi](https://pypi.org/project/soilspecdl/)
|
|
223
|
+
|
|
224
|
+
``` sh
|
|
225
|
+
$ pip install soilspecdl
|
|
226
|
+
```
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
soilspecdl/__init__.py,sha256=sXLh7g3KC4QCFxcZGBTpG2scR7hmmBsMjq6LqRptkRg,22
|
|
2
|
+
soilspecdl/_modidx.py,sha256=pB0C8bxqHxcS-xWHqT_fE_4tgACnDdFsphvg8LbRT_I,5261
|
|
3
|
+
soilspecdl/core.py,sha256=ZSCMP--nHqpjhd_OdwtTPq-_bbRCWVMdkgNpBLQPzUQ,192
|
|
4
|
+
soilspecdl/dataloader.py,sha256=znG-Eize-9PCMTB4ggeXZhNnXu2IlMmnyKIdPTz6N0M,4785
|
|
5
|
+
soilspecdl/models.py,sha256=3qWXzH-4vl34iivY1mXs7DXjiWHNU4wCtIsYCB8luLw,3935
|
|
6
|
+
soilspecdl-0.0.1.dist-info/licenses/LICENSE,sha256=xV8xoN4VOL0uw9X8RSs2IMuD_Ss_a9yAbtGNeBWZwnw,11337
|
|
7
|
+
soilspecdl-0.0.1.dist-info/METADATA,sha256=mLqrmoEOVADaJYB_ze1-pxrtnXI-Dqyn0Q0nxGTIIwI,8134
|
|
8
|
+
soilspecdl-0.0.1.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
9
|
+
soilspecdl-0.0.1.dist-info/entry_points.txt,sha256=llGBT61JN048Si57zYRVSusODt5lUHqRyICuMr41HzY,42
|
|
10
|
+
soilspecdl-0.0.1.dist-info/top_level.txt,sha256=f54psXf07I5t_9byfwb65aG7VIVscQdpaqzVCZr-eJk,11
|
|
11
|
+
soilspecdl-0.0.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2022, fastai
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
soilspecdl
|