Error while implementing logistic regression

Issue

This Content is from Stack Overflow. Question asked by Pranav167

I am practicing implementing logistic regression and have some doubts about the below code which I have taken from the site.

y=data[‘Survived’] —>> Target Variable
,x=data.drop([‘Survived’],axis=1)

from sklearn.model_selection import train_test_split
train_x,test_x,train_y,test_y=train_test_split(x,y,random_state=101,stratify=y)

r=LogisticRegression()

val=lr.fit(train_x,train_y)

pred1=val.predict(test_x)

lr.score(test_x, test_y),pred1[:10]

The output of the above code is —->>
(0.7757847533632287, array([0, 0, 0, 0, 1, 1, 0, 1, 0, 0], dtype=int64))

My question here are

  1. Why have we used lr.score(test_x, test_y) and not lr.score(pred1, test_y) to calculate score as pred1 is our predicted value ?

  2. If I use pred1 –> lr.score(pred1, test_y) then it throws below error & I want to know the reason of this error

ValueError: Expected 2D array, got 1D array instead:
array=[0 0 0 0 1 1 0 1 0 0 0 1 1 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 1 1 0 0
1 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 1 1 0
1 0 0 0 0 1 0 0 1 0 0 0 0 0 1 0 1 0 1 0 0 0 0 1 1 0 0 1 0 0 0 0 1 1 0 0 0
0 0 0 1 1 0 1 0 0 0 0 0 1 0 0 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 1
0 0 0 1 1 0 0 0 1 0 1 1 0 0 1 0 1 0 1 0 1 1 1 1 0 1 0 0 0 1 1 0 1 0 1 1 0
0 0 1 1 0 0 0 0 0 0 0 1 0 0 0 1 0 0 1 1 0 0 0 1 0 0 1 0 1 1 0 0 1 0 0 1 1
0].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

3)If I use fit_transform() instead of fit() in the model then too I get error

lr=LogisticRegression()

val=lr.fit_transform(train_x,train_y)

pred1=val.predict(test_x)

lr.score(test_x, test_y),pred1[:10]

Output–>
AttributeError: ‘LogisticRegression’ object has no attribute ‘fit_transform’



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?