Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.GaussianProcessTuning/ILNumerics.2.14.4735.573/Algorithms/MachineLearning/ILOLS.cs @ 11054

Last change on this file since 11054 was 9102, checked in by gkronber, 12 years ago

#1967: ILNumerics source for experimentation

File size: 6.7 KB
Line 
1///
2///    This file is part of ILNumerics Community Edition.
3///
4///    ILNumerics Community Edition - high performance computing for applications.
5///    Copyright (C) 2006 - 2012 Haymo Kutschbach, http://ilnumerics.net
6///
7///    ILNumerics Community Edition is free software: you can redistribute it and/or modify
8///    it under the terms of the GNU General Public License version 3 as published by
9///    the Free Software Foundation.
10///
11///    ILNumerics Community Edition is distributed in the hope that it will be useful,
12///    but WITHOUT ANY WARRANTY; without even the implied warranty of
13///    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14///    GNU General Public License for more details.
15///
16///    You should have received a copy of the GNU General Public License
17///    along with ILNumerics Community Edition. See the file License.txt in the root
18///    of your distribution package. If not, see <http://www.gnu.org/licenses/>.
19///
20///    In addition this software uses the following components and/or licenses:
21///
22///    =================================================================================
23///    The Open Toolkit Library License
24///   
25///    Copyright (c) 2006 - 2009 the Open Toolkit library.
26///   
27///    Permission is hereby granted, free of charge, to any person obtaining a copy
28///    of this software and associated documentation files (the "Software"), to deal
29///    in the Software without restriction, including without limitation the rights to
30///    use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
31///    the Software, and to permit persons to whom the Software is furnished to do
32///    so, subject to the following conditions:
33///
34///    The above copyright notice and this permission notice shall be included in all
35///    copies or substantial portions of the Software.
36///
37///    =================================================================================
38///   
39
40using System;
41using System.Collections.Generic;
42using System.Linq;
43using System.Text;
44
45namespace ILNumerics {
46    public partial class ILMath {
47
48        internal delegate ILRetArray<T> ILRidgeRegressionApplyFunc<T>(ILInArray<T> X, ILRidgeRegressionResult<T> C);
49        /// <summary>
50        /// This class stores the result of a ridge regression
51        /// </summary>
52        /// <typeparam name="T">Element type (precision) for the result</typeparam>
53        /// <remarks>This class is returned from <see cref="ILNumerics.ILMath.ridge_regression(ILInArray&lt;double>, ILInArray&lt;double>, ILBaseArray, ILBaseArray)"/>
54        /// and all its overloads. The class stores all data needed to apply the regression result to new data points. Therefore a
55        /// function <see cref="ILNumerics.ILMath.ILRidgeRegressionResult{T}.Apply(ILNumerics.ILInArray{T}, ILNumerics.ILBaseArray[])" /> is provided.
56        /// <para>The class implements the <c>IDisposable</c> interface and should be used inside a 'using' block or manually be disposed
57        /// after use.</para></remarks>
58        public class ILRidgeRegressionResult<T> : ILResult<T> {
59            internal ILRidgeRegressionApplyFunc<T> m_applyFunc;
60            internal ILArray<T> m_centerX = ILMath.returnType<T>();
61            internal ILArray<T> m_centerY = ILMath.returnType<T>();
62            internal ILArray<T> m_weights = ILMath.returnType<T>();
63            internal int m_p = 1;
64            internal ILArray<T> m_pow = ILMath.returnType<T>();
65           
66            /// <summary>
67            /// Apply the result on new datapoints
68            /// </summary>
69            /// <param name="X">New datapoints, same dimension as used for learning</param>
70            /// <returns></returns>
71            public override ILRetArray<T> Apply(ILInArray<T> X, params ILBaseArray[] arguments) {
72                if (IsDisposed)
73                    throw new Exceptions.ILInvalidOperationException("the regression result is disposed already");
74                return m_applyFunc(X,this);
75            }
76
77            #region IDisposable Members
78            /// <summary>
79            /// Dispose off the result and free all storages used
80            /// </summary>
81            public override void Dispose() {
82                base.Dispose();
83                m_centerX.Dispose();
84                m_centerY.Dispose();
85                m_weights.Dispose();
86                m_pow.Dispose();
87            }
88
89            #endregion
90        }
91        /// <summary>
92        /// Ordinary least squares regression/ ridge regression
93        /// </summary>
94        /// <param name="X">Data matrix, data points in columns</param>
95        /// <param name="Y">Training targets (or 'labels') corresponding to <paramref name="X"/></param>
96        /// <param name="Degree">Highest degree of polynomials for the design matrix</param>
97        /// <param name="Regularization">Regularization constant (usually some "small" summand for stabilizing the matrix inversion).</param>
98        /// <returns>Train result used for applying the model to new data.</returns>
99        public static ILRidgeRegressionResult<double> ridge_regression(ILInArray<double> X, ILInArray<double> Y, ILBaseArray Degree, ILBaseArray Regularization) {
100            using (ILScope.Enter(X, Y, Degree, Regularization)) {
101
102                ILArray<double> x = check(X);
103                ILArray<double> y = check(Y);
104
105                ILRidgeRegressionResult<double> ret = new ILRidgeRegressionResult<double>();
106                double c = (double)todouble(Regularization);
107                int p = (int)toint32(Degree);
108                if (c < 0) c = 1e-10;
109                if (p < 1) p = 1;
110                ret.m_pow.a  = repmat(vec<double>(1,p).T,x.S[0],1)[full];
111                ILArray<double> Xd = pow(repmat(x, p, 1), repmat(ret.m_pow, 1, x.S[1]));
112                ret.m_p = p;
113                ret.m_centerX.a = mean(Xd,1);
114                ret.m_centerY.a = mean(y,1);
115                Xd.a = Xd - ret.m_centerX;
116                ILArray<double> Yd = y - ret.m_centerY;
117                ret.m_weights.a = linsolve(multiply(Xd,Xd.T) + c * eye(Xd.S[0],Xd.S[0]) , multiply(Xd,y.T));
118                ret.m_applyFunc = RidgeRegressionApply;
119                return ret;
120            }
121        }
122
123        internal static ILRetArray<double> RidgeRegressionApply(ILInArray<double> X, ILRidgeRegressionResult<double> C) {
124            using (ILScope.Enter(X)) {
125                int n = X.S[1];
126                ILArray<double> Xd = pow(repmat(X, C.m_p, 1),repmat(reshape(C.m_pow, numel(C.m_pow), 1), 1, n));
127                return multiply(C.m_weights.T, (Xd - repmat(C.m_centerX, 1, n))) + repmat(C.m_centerY, 1, n);
128            }
129        }
130
131    }
132}
Note: See TracBrowser for help on using the repository browser.