Linear Regression. Python function returns a 4x4 matrix instead of a floating number like in an equivalent Octave function
I am trying to translate code from Octave to python, and I am stuck. I am aware they are Libraries out there such as Scikit etc but for my own learning I would like to be able to implement the cost function from scratch. Furthermore, I managed to solve some issues by looking into NumPy documentation, but I am still stuck with one last one. 606
The function doesn't return the expected result. I am providing everything you need to reproduce below. Nothing more is needed. The python function returns a 4x4 matrices instead of a float like it does in Octave and
Actual results: an numpy.ndarray Expected results: a floating number
* The function in computeCost(X, y, theta) in Octave:
function J = computeCost(X, y, theta) m = length(y); J = (((X*theta)-y)'*((X*theta)-y))/(2*m); end
* The function compute_cost(X, y, theta) in python ``` from numpy import dot
def compute_cost(X, y, theta): m = len(y) ans = (X * theta) - y product = dot((1/(2*m)), dot(ans, ans.T)) return product ```
* The tests:
``` import unittest import numpy as np from ml.ml_utils import compute_cost
class TestComputeCost(unittest.TestCase): data = np.loadtxt('../data/data1.txt', delimiter=',') x = data[:, 0] y = data[:, 1] m = len(y) X = np.vstack((np.ones(m), x))
def test_compute_cost_with_theta_zeros(self):
theta = np.zeros((2, 1), dtype=int)
result = compute_cost(self.X, self.y, theta)
self.assertEqual(round(result, 2), 32.07,
'Result is wrong!')
def test_compute_cost_with_theta_values(self):
theta = np.array([[-1], [2]])
result = compute_cost(self.X, self.y, theta)
self.assertEqual(round(result, 2), 54.24,
'Result is wrong!')
if name == 'main': unittest.main()
```
* data1.txt
6.1101,<PHONE_NUMBER>,<PHONE_NUMBER>,<PHONE_NUMBER>,11.854 5.8598,<PHONE_NUMBER>,11.886 7.4764,<PHONE_NUMBER>,12 6.4862,<PHONE_NUMBER>,<PHONE_NUMBER>,<PHONE_NUMBER>,15.505 5.734,<PHONE_NUMBER>,<PHONE_NUMBER>,<PHONE_NUMBER>,<PHONE_NUMBER>,<PHONE_NUMBER>,<PHONE_NUMBER>,3.6518 7.0708,5.3893 6.1891,3.1386 20.27,<PHONE_NUMBER>,4.263 6.3261,<PHONE_NUMBER>,<PHONE_NUMBER>,<PHONE_NUMBER>,<PHONE_NUMBER>,<PHONE_NUMBER>,<PHONE_NUMBER>,<PHONE_NUMBER>,-1.22 6.5894,5.9966 9.2482,<PHONE_NUMBER>,<PHONE_NUMBER>,<PHONE_NUMBER>,<PHONE_NUMBER>,<PHONE_NUMBER>,<PHONE_NUMBER>,10.117 6.3534,<PHONE_NUMBER>,<PHONE_NUMBER>,3.9115 11.708,5.3854 5.7737,<PHONE_NUMBER>,<PHONE_NUMBER>,1.0463 5.0702,<PHONE_NUMBER>,1.844 11.7,<PHONE_NUMBER>,1.0179 7.5402,<PHONE_NUMBER>,<PHONE_NUMBER>,<PHONE_NUMBER>,<PHONE_NUMBER>,<PHONE_NUMBER>,-<PHONE_NUMBER>,<PHONE_NUMBER>,<PHONE_NUMBER>,3.9624 9. 509