-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathmodel_api.jl
84 lines (63 loc) · 2.3 KB
/
model_api.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
module TestModelAPI
using Test
using MLJBase
import MLJModelInterface
using ..Models
using Distributions
using StableRNGs
using JLSO
rng = StableRNG(661)
@testset "predict_*" begin
X = rand(rng, 5)
yfinite = categorical(collect("abaaa"))
ycont = float.(1:5)
clf = ConstantClassifier()
fitresult, _, _ = MLJBase.fit(clf, 1, X, yfinite)
@test predict_mode(clf, fitresult, X)[1] == 'a'
@test_throws ArgumentError predict_mean(clf, fitresult, X)
@test_throws ArgumentError predict_median(clf, fitresult, X)
rgs = ConstantRegressor()
fitresult, _, _ = MLJBase.fit(rgs, 1, X, ycont)
@test predict_mean(rgs, fitresult, X)[1] == 3
@test predict_median(rgs, fitresult, X)[1] == 3
@test_throws ArgumentError predict_mode(rgs, fitresult, X)
end
mutable struct UnivariateFiniteFitter <: MLJModelInterface.Probabilistic
alpha::Float64
end
UnivariateFiniteFitter(;alpha=1.0) = UnivariateFiniteFitter(alpha)
@testset "models that fit a distribution" begin
function MLJModelInterface.fit(model::UnivariateFiniteFitter,
verbosity, X, y)
α = model.alpha
N = length(y)
_classes = classes(y)
d = length(_classes)
frequency_given_class = Distributions.countmap(y)
prob_given_class =
Dict(c => (frequency_given_class[c] + α)/(N + α*d) for c in _classes)
fitresult = MLJBase.UnivariateFinite(prob_given_class)
report = (params=Distributions.params(fitresult),)
cache = nothing
verbosity > 0 && @info "Fitted a $fitresult"
return fitresult, cache, report
end
MLJModelInterface.predict(model::UnivariateFiniteFitter,
fitresult,
X) = fitresult
MLJModelInterface.input_scitype(::Type{<:UnivariateFiniteFitter}) =
Nothing
MLJModelInterface.target_scitype(::Type{<:UnivariateFiniteFitter}) =
AbstractVector{<:Finite}
y = coerce(collect("aabbccaa"), Multiclass)
X = nothing
model = UnivariateFiniteFitter(alpha=0)
mach = machine(model, X, y)
fit!(mach, verbosity=0)
ytest = y[1:3]
yhat = predict(mach, nothing) # single UnivariateFinite distribution
@test cross_entropy(fill(yhat, 3), ytest) ≈
[-log(1/2), -log(1/2), -log(1/4)]
end
end
true