Implementing multiple linear regression in Swift
The MultipleLinearRegression class contains a vector of weights, and staff for data normalization:
class MultipleLinearRegression {
public var weights: [Double]!
public init() {}
public var normalization = false
public var xMeanVec = [Double]()
public var xStdVec = [Double]()
public var yMean = 0.0
public var yStd = 0.0
...
} Hypothesis and prediction:
public func predict(xVec: [Double]) -> Double {
if normalization {
let input = xVec
let differenceVec = vecSubtract([1.0]+input, xMeanVec)
let normalizedInputVec = vecDivide(differenceVec, xStdVec)
let h = hypothesis(xVec: normalizedInputVec)
return h * yStd + yMean
} else {
return hypothesis(xVec: [1.0]+xVec)
}
}
private func hypothesis(xVec: [Double]) -> Double {
var result = 0.0
vDSP_dotprD(xVec, 1, weights, 1, &result, vDSP_Length(xVec.count))
return result
}
public func predict(xMat: [[Double]]) -> [Double] {
let...