2
$\begingroup$

I try to use linear regression for insurance data . But had error on the when try to call a function with features parameter. Here is my code:

def h(x):
    global w
    return np.sum(np.transpose(w)*x)
    raise NotImplementedError()

when try with a simple data it works fine,

w, x = [1,2,3], [2,3,4]
h(x)

the output is : 20

but when try to use the dataset, it errors:

features = dataset.drop(["charges"], axis=1).values
h(features )

it returns error:

ValueError: operands could not be broadcast together with shapes (3,) (1338,) 

so the features looks like this:

array([[0.1173913 , 0.        , 0.35698144, 0.        , 1.        ],
       [0.1       , 1.        , 0.48331988, 1.        , 0.        ],
       [0.27391304, 1.        , 0.46674738, 3.        , 0.        ],
       ...,
       [0.1       , 0.        , 0.5496099 , 0.        , 0.        ],
       [0.15217391, 0.        , 0.3117837 , 0.        , 0.        ],
       [0.84782609, 0.        , 0.38216303, 0.        , 1.        ]])

The data i used is insurance.csv from kaggle.com

$\endgroup$
2
  • 1
    $\begingroup$ You'll have to update your weight vector w for the matrix multiplication to work. $\endgroup$
    – bkshi
    Mar 14, 2020 at 17:07
  • $\begingroup$ i'm sorry im new to this field, how to do that? $\endgroup$ Mar 17, 2020 at 9:23

1 Answer 1

1
$\begingroup$

It looks like you're trying to multiply a matrix and a vector point-wise. Such an operation is not defined. I think you should use X.dot(w), where X is a feature $\bf matrix$ and w is the wights $\bf vector$. np.dot can operate with objects of different nature (like matrices and vectors). So in h I'd write return X.dot(w). Also, I'd call it only with a matrix X (for consistency), even if there's an object it would be $X \in \mathbb{R}^{1 \times d}$ in that case. Watch carefully after shapes of the objects which enter functions.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.