首页 > 解决方案 > 逻辑回归仅预测 1 个类别

问题描述

我是数据科学或机器学习的新手。我尝试从这里实现代码,但预测只返回 1 个类。这是我的代码:

classification_data = data.drop([10], axis=1).values
classification_label = data[10].values

class LogisticRegression:
    def __init__(self, lr=0.01, num_iter=100000):
        self.lr = lr
        self.num_iter = num_iter
        self.weights = None
        self.bias = None

    def fit(self, X, y):
        '''Build a logistic regression classifier from the training set (X, y)'''

        n_samples, n_features = X.shape

        # init parameters
        self.weights = np.zeros(n_features)
        self.bias = 0

        # gradient descent
        for _ in range(self.num_iter):
            # approximate y with linear combination of weights and x, plus bias
            linear_model = np.dot(X, self.weights) + self.bias
            # apply sigmoid function
            y_predicted = self._sigmoid(linear_model)

            # compute gradients
            dw = (1 / n_samples) * np.dot(X.T, (y_predicted - y))
            db = (1 / n_samples) * np.sum(y_predicted - y)
            # update parameters
            self.weights -= self.lr * dw
            self.bias -= self.lr * db
        #raise NotImplementedError()

    def predict_proba(self, X):
        return self._sigmoid(X)
        raise NotImplementedError()

    def predict(self, X, threshold=0.5): # default threshold adalah 0.5
        '''Predict class value for X'''
        '''hint: you can use predict_proba function to classify based on given threshold'''
        linear_model = np.dot(X, self.weights) + self.bias
        #print (linear_model)
        y_predicted = self._sigmoid(linear_model)
        #print (self.predict_proba(linear_model))
        y_predicted_cls = [2 if i > threshold else 1 for i in y_predicted]

        return np.array(y_predicted_cls)
        raise NotImplementedError()

    def _sigmoid(self, x):
        return 1 / (1 + np.exp(-x))

当我尝试调用预测时,它只返回一个类:

model.predict(classification_data, threshold=0.5)

结果:

array([2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, etc])

这是尝试调用 predict_proba 的时候:

model.predict_proba(classification_data)

结果:

array([[0.58826319, 0.5       , 0.52721189, ..., 0.60211507, 0.64565631,
        0.62245933],
       [0.58586893, 0.73105858, 0.52944351, ..., 0.57793101, 0.62245933,
        0.61387647],
       [0.63513751, 0.73105858, 0.57590132, ..., 0.6357912 , 0.55971365,
        0.52497919]. etc ]])

非常感谢任何帮助。

标签: pythonmachine-learninglogistic-regression

解决方案


就分类而言,您的算法可以正常工作,但您执行不正确predict_proba

您现在使用它的方式分别self._sigmoid应用于每个预测变量。您希望将其应用于线性模型的结果 - 与在函数中应用它的方式相同predict

从您提供的输出中可以看出predict_proba,结果是 2D 张量,而不是预期的 1D 数组。该功能的正确实现是

def predict_proba(self, X):
    linear_model = np.dot(X, self.weights) + self.bias
    return self._sigmoid(linear_model)

我已经在 iris 数据集上运行了该算法,只是为了看看它是否有效并且它对所有内容进行了正确分类。你可以自己测试一下。

from sklearn.datasets import load_iris
from sklearn.metrics import confusion_matrix

iris = load_iris()
X = iris.data
y = iris.target
y[y == 2] = 1 # turning the problem into binary classification

log_reg = LogisticRegression()
log_reg.fit(X, y)

yproba = log_reg.predict_proba(X)
ypred = log_reg.predict(X)

cm = confusion_matrix(y, ypred)

这种情况下的混淆矩阵是

50  |  0
----------
0   |  100

在上面的示例中,模型是在完整数据集上训练的,但即使对于训练/测试拆分,也获得了相同的结果(所有内容都被正确分类)。

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

log_reg = LogisticRegression()
log_reg.fit(X_train, y_train)

cm = confusion_matrix(y_test, ypred)

在这种情况下,混淆矩阵是

8   |  0
----------
0   |  22

结论是您的算法可以正常工作。奇怪的行为(如果有的话)可能应该归因于您输入算法的数据。(您确定它不应该为您的案例中的所有测试观察预测同一类吗?)

请注意,我在您的代码中又更改了一行

# from the original where you are returning 1s and 2s
y_predicted_cls = [1 if i > threshold else 0 for i in y_predicted]

为了简单起见,我猜你可以称之为最佳实践。


推荐阅读