blob: 57af57542e5d741eb8afd8d0b45d08c24e9e764b [file] [log] [blame]
#-------------------------------------------------------------
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
#-------------------------------------------------------------
#hyperparameter(lambda, intercept) grid search for l2svm
l2norm = function(Matrix[Double] X, Matrix[Double] y, Matrix[Double] B, Boolean icpt)
return (Matrix[Double] loss) {
if (icpt)
X = cbind(X, matrix(1, nrow(X), 1));
loss = as.matrix(sum((y - X%*%B)^2));
}
N = 1000;
no_lamda = 10;
stp = (0.1 - 0.0001)/no_lamda;
lamda = 0.0001;
Rbeta = matrix(0, rows=N+1, cols=no_lamda*2);
Rloss = matrix(0, rows=no_lamda*2, cols=1);
i = 1;
X = rand(rows=1000, cols=N, sparsity=1.0, seed=42);
y = rand(rows=1000, cols=1, min=0, max=2, seed=42);
y = ceil(y);
for (l in 1:no_lamda)
{
beta = l2svm(X=X, Y=y, intercept=FALSE, epsilon=1e-12,
lambda = lamda, verbose=FALSE);
Rbeta[1:nrow(beta),i] = beta;
Rloss[i,] = l2norm(X, y, beta, FALSE);
i = i + 1;
beta = l2svm(X=X, Y=y, intercept=TRUE, epsilon=1e-12,
lambda = lamda, verbose=FALSE);
Rbeta[1:nrow(beta),i] = beta;
Rloss[i,] = l2norm(X, y, beta, TRUE);
i = i + 1;
lamda = lamda + stp;
}
leastLoss = rowIndexMin(t(Rloss));
bestModel = Rbeta[,as.scalar(leastLoss)];
write(bestModel, $1, format="text");