title: Multiple independent variables / multiple linear regression in Swift
body: <p>I am looking for a <strong>Swift</strong> library or code to implement a <strong>Multiple Linear Regression</strong>.  Well, at least that's what I <em>think</em> I need.</p>
  
  <p>Right now I've got this, doing just a regular linear regression:</p>
  
  <pre><code>private func linearRegression(_ xs: [Double], ys: [Double]) -&gt; (Double) -&gt; Double {
  
  
      let sum1 = average(multiply(ys, xs)) - average(xs) * average(ys)
      let sum2 = average(multiply(xs, xs)) - pow(average(xs), 2)
      let slope = sum1 / sum2
      let intercept = average(ys) - slope * average(xs)
  
      return { x in
          return slope * x + intercept
      }
  }
  
  private func multiply(_ a: [Double], _ b: [Double]) -&gt; [Double] {
      return zip(a, b).map(*)
  }
  private func average(_ input: [Double]) -&gt; Double {
      return input.reduce(0, +) / Double(input.count)
  }
  
  
  let heights: [Double] = [ 20.0, 44.0, 66.0 ]
  let ages: [Double] = [ 0.1, 6.5, 12.0 ]
  
  let calc = linearRegression(heights, ys: ages)
  print(calc(66.0)) // 12.07
  </code></pre>
  
  <p>So in this case, I've got an input of <strong>heights</strong> (<strong>xs</strong>), and an output/result of <strong>ages</strong> (<strong>ys</strong>).</p>
  
  <p>What I need though, is to have <strong>2</strong> independent variables -- or 2 inputs.  So instead of "<strong>heights -> ages</strong>", I need "<strong>(heights, weights) -> ages</strong>".</p>
  
  <p>So basically, something like this:</p>
  
  <pre><code>let heightsAndWeights: [Double] = [ 
      (20.0, 7.2),
      (44.0, 58.0), 
      (66.0, 160.0) 
  ]
  let ages: [Double] = [ 0.1, 6.5, 12.0 ]
  </code></pre>
  
  <p>So in the end, I want to take a <strong>height</strong> and a <strong>weight</strong>, and get back an <strong>age</strong>, in a way that's fit to my input data (<strong>heightsAndWeights</strong>, above).</p>
  
  <p>I've been searching stackoverflow and google and have found a number of implementations in other languages, but they always depend on some library that does the magic.</p>
  
  <p>Swift 5, running on Ubuntu.</p>