Skip to content
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

WIP Write Generalized Linear Machine class #5006

Merged
merged 31 commits into from
Aug 4, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
0bbdb9b
made new files
Hephaestus12 Apr 8, 2020
6a65fa0
WIP made some basic protected functions
Hephaestus12 Apr 14, 2020
2d91213
made changes
Hephaestus12 Apr 16, 2020
e2faedb
make minor changes
Hephaestus12 Apr 17, 2020
e439de7
implement RandomMixin and IterativeMachine
Hephaestus12 Apr 18, 2020
5c2a6cb
implement RandomMixin and IterativeMachine
Hephaestus12 Apr 18, 2020
ad67ed0
implement ElasticNetPenalty class and remove proximal operator
Hephaestus12 Apr 20, 2020
73d726b
WIP implement SGDMinimizer class
Hephaestus12 Apr 20, 2020
c4e57b5
add GLMCostFunction class
Hephaestus12 Apr 21, 2020
32ec5e6
add GLMCostFunction class
Hephaestus12 Apr 21, 2020
07d262f
implement IterativeMachine with optimization classes
Hephaestus12 Apr 26, 2020
3bc2c16
make changes
Hephaestus12 Apr 29, 2020
3bfe4aa
mention references to pyGLMnet
Hephaestus12 Apr 29, 2020
23e2232
solved bugs
Hephaestus12 Apr 29, 2020
ff9c4bd
make changes to classes deriving from IterativeMachine
Hephaestus12 Apr 30, 2020
10bbee8
move GLMCostFunction to GLM.h
Hephaestus12 Apr 30, 2020
1d9da84
minor changes
Hephaestus12 Jun 23, 2020
d07cfdb
Add basic unit test.
Hephaestus12 Jul 7, 2020
551d134
Make changes.
Hephaestus12 Jul 8, 2020
c74cb24
Got GLM to work.
Hephaestus12 Jul 16, 2020
5b43658
Remove debugging code.
Hephaestus12 Jul 16, 2020
97a7a53
Add gradient test.
Hephaestus12 Jul 18, 2020
474e141
Miscellaneous.
Hephaestus12 Jul 21, 2020
582341c
Remove get_cost().
Hephaestus12 Jul 21, 2020
57d2e69
Add meta example.
Hephaestus12 Jul 21, 2020
d167089
Fix serialization issue.
Hephaestus12 Jul 25, 2020
763c7f6
Remove debugging code.
Hephaestus12 Jul 25, 2020
83c9f37
Address comments.
Hephaestus12 Jul 27, 2020
64a224d
Solve data conflict.
Hephaestus12 Jul 30, 2020
67a27ef
Remove friend class.
Hephaestus12 Jul 31, 2020
437e90b
Remove unnecessary comments.
Hephaestus12 Aug 2, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/shogun/classifier/AveragedPerceptron.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ void AveragedPerceptron::init()
ParameterProperties::MODEL)
}

void AveragedPerceptron::init_model(std::shared_ptr<Features> data)
void AveragedPerceptron::init_model(const std::shared_ptr<Features> data)
{
ASSERT(m_labels)
if (data)
Expand Down
4 changes: 2 additions & 2 deletions src/shogun/classifier/AveragedPerceptron.h
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,8 @@ namespace shogun
/** registers and initializes parameters */
void init();

virtual void init_model(std::shared_ptr<Features> data);
virtual void iteration();
void init_model(std::shared_ptr<Features> data) override;
void iteration() override;

protected:
/** learning rate */
Expand Down
2 changes: 1 addition & 1 deletion src/shogun/classifier/Perceptron.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ Perceptron::~Perceptron()
{
}

void Perceptron::init_model(std::shared_ptr<Features> data)
void Perceptron::init_model(const std::shared_ptr<Features> data)
{
if (data)
{
Expand Down
4 changes: 2 additions & 2 deletions src/shogun/classifier/Perceptron.h
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,8 @@ class Perceptron : public IterativeMachine<LinearMachine>
virtual const char* get_name() const { return "Perceptron"; }

protected:
virtual void init_model(std::shared_ptr<Features> data);
virtual void iteration();
void init_model(std::shared_ptr<Features> data) override;
void iteration() override;

protected:
/** learning rate */
Expand Down
2 changes: 1 addition & 1 deletion src/shogun/classifier/svm/NewtonSVM.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ NewtonSVM::~NewtonSVM()
{
}

void NewtonSVM::init_model(std::shared_ptr<Features> data)
void NewtonSVM::init_model(const std::shared_ptr<Features> data)
{
if (data)
{
Expand Down
4 changes: 2 additions & 2 deletions src/shogun/classifier/svm/NewtonSVM.h
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,8 @@ class NewtonSVM : public IterativeMachine<LinearMachine>
virtual const char* get_name() const { return "NewtonSVM"; }

protected:
virtual void init_model(std::shared_ptr<Features> data);
virtual void iteration();
void init_model(std::shared_ptr<Features> data) override;
void iteration() override;

private:
void obj_fun_linear();
Expand Down
170 changes: 170 additions & 0 deletions src/shogun/machine/GLM.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
/*
* This software is distributed under BSD 3-clause license (see LICENSE file).
*
* Author: Tej Sukhatme
*/

#include <shogun/features/DotFeatures.h>
#include <shogun/labels/Labels.h>
#include <shogun/labels/RegressionLabels.h>
#include <shogun/lib/observers/ObservedValueTemplated.h>
#include <shogun/machine/GLM.h>
#include <shogun/machine/LinearMachine.h>
#include <shogun/mathematics/NormalDistribution.h>
#include <shogun/mathematics/RandomNamespace.h>
#include <shogun/mathematics/linalg/LinalgNamespace.h>
#include <shogun/optimization/ConstLearningRate.h>
#include <shogun/optimization/ElasticNetPenalty.h>
#include <shogun/optimization/GradientDescendUpdater.h>
#include <shogun/optimization/SGDMinimizer.h>

#include <cmath>

using namespace shogun;

GLM::GLM()
{
SG_ADD_OPTIONS(
(machine_int_t*)&distribution, "distribution_type",
"variable to store name of distribution type",
ParameterProperties::HYPER, SG_OPTIONS(POISSON));
SG_ADD(
&m_eta, "eta",
"threshold parameter that linearizes the exp() function above eta",
ParameterProperties::HYPER);
SG_ADD(
&m_lambda, "lambda", "regularization parameter of penalty term",
ParameterProperties::HYPER);
SG_ADD(
&m_alpha, "alpha",
"weighting between L1 penalty and L2 penalty term of the loss function",
ParameterProperties::HYPER);
SG_ADD(
&m_tolerance, "tolerance", "convergence threshold or stopping criteria",
ParameterProperties::HYPER);
SG_ADD(
&m_learning_rate, "learning_rate", "learning rate for gradient descent",
ParameterProperties::HYPER);

m_gradient_updater = std::make_shared<GradientDescendUpdater>();
m_penalty = std::make_shared<ElasticNetPenalty>();
m_cost_function = std::make_shared<GLMCostFunction>();
}

GLM::GLM(
GLM_DISTRIBUTION distr, float64_t alpha, float64_t lambda,
float64_t learning_rate, int32_t max_iterations, float64_t tolerance,
float64_t eta)
: GLM()
{
distribution = distr;
m_alpha = alpha;
m_lambda = lambda;
m_learning_rate = learning_rate;
m_max_iterations = max_iterations;
m_tolerance = tolerance;
m_eta = eta;

m_penalty->set_l1_ratio(m_alpha);
}

std::shared_ptr<RegressionLabels>
GLM::apply_regression(std::shared_ptr<Features> data)
{
if (data)
{
if (!data->has_property(FP_DOT))
error("Specified features are not of type CDotFeatures");
set_features(std::static_pointer_cast<DotFeatures>(data));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there a reason why the features are added to the state here?

Copy link
Contributor Author

@Hephaestus12 Hephaestus12 Jul 31, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No particular reason, I did it this way as it was done like this in LinearMachine:

if (data)
{
if (!data->has_property(FP_DOT))
error("Specified features are not of type CDotFeatures");
set_features(std::static_pointer_cast<DotFeatures>(data));
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should I remove it?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not sure, you'll have to see if this has side effects that you rely on. @LiuYuHui do you know if this is required? Because you had to refactor this code recently in the feature branch

}

require(features, "Features are not provided");

auto num = features->get_num_vectors();
ASSERT(num > 0)
ASSERT(m_w.vlen == features->get_dim_feature_space())
SGVector<float64_t> out(num);
features->dense_dot_range(
out.vector, 0, num, NULL, m_w.vector, m_w.vlen, bias);
auto result = m_cost_function->non_linearity(
out, m_compute_bias, m_eta, distribution);

return std::make_shared<RegressionLabels>(result);
}

void GLM::init_model(const std::shared_ptr<Features> data)
{
ASSERT(m_labels)
if (data)
{
if (!data->has_property(FP_DOT))
error("Specified features are not of type CDotFeatures");
set_features(std::static_pointer_cast<DotFeatures>(data));
}
ASSERT(features)

NormalDistribution<float64_t> normal_dist;
const auto& n_features = features->get_dim_feature_space();

if (m_w.vlen == 0)
{
if (m_compute_bias && bias == 0)
bias = 1.0 / (n_features + 1) * normal_dist(m_prng);

if (n_features > 0)
{
m_w = SGVector<float64_t>(n_features);

std::generate(m_w.begin(), m_w.end(), [&]() {
auto rand = normal_dist(m_prng);
return 1.0 / (n_features + 1) * rand;
});
}
}
}

void GLM::iteration()
{
SGVector<float64_t> w_old = m_w.clone();

auto X = get_features()->get_computed_dot_feature_matrix();
auto y = regression_labels(get_labels())->get_labels();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this should be fixed at some point. I guess when we have the LabelEncoder in Machine, otherwise you are performing a potentially expensive operation in each iteration

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it seems like that RegressionLabels is what LabelEncoder lacks, currently, LabelEncoder only support MulticlassLabels and BinaryLabels.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

True, but it should be possible to add it?


auto gradient_w = m_cost_function->get_gradient_weights(
X, y, m_w, bias, m_lambda, m_alpha, m_compute_bias, m_eta,
distribution);
auto gradient_bias = m_cost_function->get_gradient_bias(
X, y, m_w, bias, m_compute_bias, m_eta, distribution);

// Update
// TODO: Use gradient updater
// m_gradient_updater->update_variable(m_w, gradient_w, learning_rate);
m_w = linalg::add(m_w, gradient_w, 1.0, -1 * m_learning_rate);

if (m_compute_bias)
bias -= m_learning_rate * gradient_bias;

// Apply proximal operator
// TODO: Use proximity updater.
// m_penalty->update_variable_for_proximity(m_w, m_lambda * m_alpha);
for (auto i : range(m_w.vlen))
{
if (std::abs(m_w[i]) < (m_lambda * m_alpha))
m_w[i] = 0;
else
{
if (m_w[i] > 0)
m_w[i] -= (m_lambda * m_alpha);
else
m_w[i] += (m_lambda * m_alpha);
}
}

// Convergence by relative parameter change tolerance
auto norm_update = linalg::norm(linalg::add(m_w, w_old, 1.0, -1.0));
float32_t checker = linalg::norm(m_w) == 0
? norm_update
: std::abs(norm_update / linalg::norm(m_w));
if (m_current_iteration > 0 && checker < m_tolerance)
m_complete = true;
}
Loading