-
Notifications
You must be signed in to change notification settings - Fork 46
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Added ShrunkCovariance #309
Merged
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
4bf257b
added working shrunk covariance
norm4nn 238f181
Merge branch 'shrunk_cov' of https://github.com/norm4nn/scholar
norm4nn f605f27
added utilites for covariance, added tests for shrunk covariance
norm4nn 4b50ca6
Added docs
norm4nn 7e4378b
Added docs
norm4nn df80bc3
added '?' sign to assume_centered option
norm4nn 4ec5bc5
Update lib/scholar/covariance/shrunk_covariance.ex
norm4nn 3f38654
Update lib/scholar/covariance/shrunk_covariance.ex
norm4nn 5323af1
Update lib/scholar/covariance/shrunk_covariance.ex
norm4nn 34f8574
Update lib/scholar/covariance/utils.ex
norm4nn f72d08f
reverted to empirical_covariance
norm4nn 0f7ab42
mix format
norm4nn File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,119 @@ | ||
defmodule Scholar.Covariance.ShrunkCovariance do | ||
@moduledoc """ | ||
Covariance estimator with shrinkage. | ||
""" | ||
import Nx.Defn | ||
|
||
@derive {Nx.Container, containers: [:covariance, :location]} | ||
defstruct [:covariance, :location] | ||
|
||
opts_schema = [ | ||
assume_centered?: [ | ||
default: false, | ||
type: :boolean, | ||
doc: """ | ||
If `true`, data will not be centered before computation. | ||
Useful when working with data whose mean is almost, but not exactly | ||
zero. | ||
If `false`, data will be centered before computation. | ||
""" | ||
], | ||
shrinkage: [ | ||
default: 0.1, | ||
type: :float, | ||
doc: "Coefficient in the convex combination used for the computation | ||
of the shrunk estimate. Range is [0, 1]." | ||
] | ||
] | ||
|
||
@opts_schema NimbleOptions.new!(opts_schema) | ||
@doc """ | ||
Fit the shrunk covariance model to `x`. | ||
|
||
## Options | ||
|
||
#{NimbleOptions.docs(@opts_schema)} | ||
|
||
## Return Values | ||
|
||
The function returns a struct with the following parameters: | ||
|
||
* `:covariance` - Tensor of shape `{num_features, num_features}`. Estimated covariance matrix. | ||
* `:location` - Tensor of shape `{num_features,}`. | ||
Estimated location, i.e. the estimated mean. | ||
|
||
## Examples | ||
|
||
iex> key = Nx.Random.key(0) | ||
iex> {x, _new_key} = Nx.Random.multivariate_normal(key, Nx.tensor([0.0, 0.0]), Nx.tensor([[0.8, 0.3], [0.2, 0.4]]), shape: {10}, type: :f32) | ||
iex> model = Scholar.Covariance.ShrunkCovariance.fit(x) | ||
iex> model.covariance | ||
#Nx.Tensor< | ||
f32[2][2] | ||
[ | ||
[0.7721845507621765, 0.19141492247581482], | ||
[0.19141492247581482, 0.33952537178993225] | ||
] | ||
> | ||
iex> model.location | ||
#Nx.Tensor< | ||
f32[2] | ||
[0.18202415108680725, -0.09216632694005966] | ||
> | ||
iex> key = Nx.Random.key(0) | ||
iex> {x, _new_key} = Nx.Random.multivariate_normal(key, Nx.tensor([0.0, 0.0]), Nx.tensor([[0.8, 0.3], [0.2, 0.4]]), shape: {10}, type: :f32) | ||
iex> model = Scholar.Covariance.ShrunkCovariance.fit(x, shrinkage: 0.4) | ||
iex> model.covariance | ||
#Nx.Tensor< | ||
f32[2][2] | ||
[ | ||
[0.7000747323036194, 0.1276099532842636], | ||
[0.1276099532842636, 0.41163527965545654] | ||
] | ||
> | ||
iex> model.location | ||
#Nx.Tensor< | ||
f32[2] | ||
[0.18202415108680725, -0.09216632694005966] | ||
> | ||
""" | ||
|
||
deftransform fit(x, opts \\ []) do | ||
fit_n(x, NimbleOptions.validate!(opts, @opts_schema)) | ||
end | ||
|
||
defnp fit_n(x, opts) do | ||
shrinkage = opts[:shrinkage] | ||
|
||
if shrinkage < 0 or shrinkage > 1 do | ||
raise ArgumentError, | ||
""" | ||
expected :shrinkage option to be in [0, 1] range, \ | ||
got shrinkage: #{inspect(Nx.shape(x))}\ | ||
""" | ||
end | ||
|
||
{x, location} = Scholar.Covariance.Utils.center(x, opts[:assume_centered?]) | ||
|
||
covariance = | ||
Scholar.Covariance.Utils.empirical_covariance(x) | ||
|> shrunk_covariance(shrinkage) | ||
|
||
%__MODULE__{ | ||
covariance: covariance, | ||
location: location | ||
} | ||
end | ||
|
||
defnp shrunk_covariance(emp_cov, shrinkage) do | ||
num_features = Nx.axis_size(emp_cov, 1) | ||
shrunk_cov = (1.0 - shrinkage) * emp_cov | ||
emp_cov_trace = Scholar.Covariance.Utils.trace(emp_cov) | ||
mu = Nx.sum(emp_cov_trace) / num_features | ||
|
||
mask = Nx.iota(Nx.shape(shrunk_cov)) | ||
selector = Nx.remainder(mask, num_features + 1) == 0 | ||
|
||
shrunk_cov + shrinkage * mu * selector | ||
end | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
defmodule Scholar.Covariance.Utils do | ||
@moduledoc false | ||
import Nx.Defn | ||
require Nx | ||
|
||
defn center(x, assume_centered? \\ false) do | ||
x = | ||
case Nx.shape(x) do | ||
{_} -> Nx.new_axis(x, 1) | ||
_ -> x | ||
end | ||
|
||
location = | ||
if assume_centered? do | ||
0 | ||
else | ||
Nx.mean(x, axes: [0]) | ||
end | ||
|
||
{x - location, location} | ||
end | ||
|
||
defn empirical_covariance(x) do | ||
n = Nx.axis_size(x, 0) | ||
|
||
covariance = Nx.dot(x, [0], x, [0]) / n | ||
|
||
case Nx.shape(covariance) do | ||
{} -> Nx.reshape(covariance, {1, 1}) | ||
_ -> covariance | ||
end | ||
end | ||
|
||
defn trace(x) do | ||
x | ||
|> Nx.take_diagonal() | ||
|> Nx.sum() | ||
end | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You should be able to use
Nx.covariance/2
instead.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't think so, look at the PR description
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Right, I forgot to ask: @norm4nn did you try setting
ddof: 0
when callingNx.covariance/2
?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sorry,
ddof: 0
is default. It's strange that the tests are failing, becauseNx.covariance/2
does exactly what is implemented here. Could it be the case that the data in your test is not centered and you are usingNx.covariance/2
?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah, you are right! This is the case, I will fix this on Thursday.