Search code examples
pythonlogistic-regression

Logistic Regression Function Using Sklearn in Python


I have a problem with my logistic regression function, I'm using Pycharm IDE and sklearn.linear_model package LogisticRegression.

My debugger shows AttributeError 'tuple' object has no attribute 'fit' and 'predict'.

Codebelow:

def logistic_regression(df, y):
x_train, x_test, y_train, y_test = train_test_split(
    df, y, test_size=0.25, random_state=0)

sc = StandardScaler()
x_train = sc.fit_transform(x_train)
x_test = sc.transform(x_test)

clf = LogisticRegression(random_state=0, solver='sag',
                         penalty='l2', max_iter=1000, multi_class='multinomial'),
clf.fit(x_train, y_train)
y_pred = clf.predict(x_test)

return classification_metrics.print_metrics(y_test, y_pred, 'Logistic regression')

Can anyone help spotting the mistake here? Because for other functions I tried fit and predict seem fine.


Solution

  • There is small mistake in the code as I mentioned in the comment.

    please remove the comma in the Logistic Regression model object creation.

    Also there is no such function called classification_metrics.print_metrics

    so I have used the metrics.classification_report

    from sklearn.model_selection import train_test_split
    from sklearn.preprocessing import StandardScaler
    from sklearn.linear_model import LogisticRegression
    from sklearn import metrics
    def logistic_regression(df, y):
        x_train, x_test, y_train, y_test = train_test_split(df, y, test_size=0.25, random_state=0)
    
        sc = StandardScaler()
        x_train = sc.fit_transform(x_train)
        x_test = sc.transform(x_test)
    
        clf = LogisticRegression(random_state=0, solver='sag', penalty='l2', max_iter=1000, multi_class='multinomial')
        clf.fit(x_train, y_train)
        y_pred = clf.predict(x_test)
    
        return metrics.classification_report(y_test, y_pred)
    

    function call

    logistic_regression(df, y)