1.4.3 A Gaussian fit
formula-fit resolves the formula against the table and fits the family that #:family names, the Gaussian by default, with the same keywords as that family’s fit procedure. The model prints as the fit does, with the formula after the family:
> (define bp-fit (formula-fit (~ bp age dose marker) patients #:lambda 0.5)) > bp-fit #<glmnet:gaussian (~ bp age dose marker) λ=0.5 dev=0.9137 nz=2/3>
coef returns an association list keyed by name, with the intercept first under R’s name for it, "(Intercept)". The lasso has found the two predictors that blood pressure depends on:
> (coef bp-fit)
'(("(Intercept)" . 93.51132211478343)
("age" . 0.5139586017419673)
("dose" . -1.7735029027253124)
("marker" . 0.0))
> (cdr (assoc "dose" (coef bp-fit))) -1.7735029027253124
predict takes a new table and reads the predictors from it by name. The columns can come in any order, and other columns are ignored; a missing predictor is an error that names it:
> (define new-patients (list (cons "id" '(101 102)) (cons "marker" '(0.5 -0.5)) (cons "dose" '(2.0 8.0)) (cons "age" '(40 70)))) > (predict bp-fit new-patients) '(110.52266037901148 115.30040101491863)
> (predict bp-fit (list (cons "age" '(40)) (cons "dose" '(2.0)))) predict: the table has no column with this name
column: "marker"
columns of the table: '("age" "dose")
formula-path fits a regularization path, and formula-cv cross-validates one, with the keywords of the family’s path fitter and cross-validation procedure. Both keep the names:
> (formula-path (~ bp age dose marker) patients #:lambda '(4.0 1.0 0.25))
#<glmnet-path:gaussian (~ bp age dose marker)
Df %Dev Lambda
1 2 59.39 4.00
2 2 89.85 1.00
3 2 91.75 0.25>
> (define bp-cv (formula-cv (~ bp age dose marker) patients)) > bp-cv
#<glmnet-cv:gaussian (~ bp age dose marker) Mean-Squared Error
Lambda Index Measure SE Nonzero
min 0.2724 36 9.255 1.138 2
1se 0.7579 25 10.19 1.374 2>
> (coef bp-cv)
'(("(Intercept)" . 94.09234504611852)
("age" . 0.49554398525920623)
("dose" . -1.6834215534687091)
("marker" . 0.0))
> (coef bp-cv #:lambda 'lambda-min)
'(("(Intercept)" . 92.99845164212019)
("age" . 0.530213232303164)
("dose" . -1.8530179478570004)
("marker" . 0.0))
The model is a formula-model. formula-model-fit returns the result it holds, which is exactly what the family’s procedure returns for the same columns as a matrix:
> (formula-model-fit bp-fit) #<glmnet:gaussian λ=0.5 dev=0.9137 nz=2/3>
> (equal? (formula-model-fit bp-fit) (lasso (map list age dose marker) bp #:lambda 0.5)) #t