我是数据科学或机器学习领域的新手。我尝试从here实现代码,但是预测仅返回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])
这是尝试调用Forecast_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 ]])
非常感谢您的帮助。
答案 0 :(得分:2)
就分类而言,您的算法可以正常工作,但是您实施的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)
我已经在虹膜数据集上运行了该算法,只是为了查看它是否有效并正确地对所有分类。您可以自己进行测试。
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]
为简单起见,我认为您可以将其称为最佳实践。
答案 1 :(得分:0)
毕竟这是因为我使用Sigmoid,并且它返回0到1之间的值,所以我将数据集上的y值更改为0和1。现在它可以正常工作了。但准确性仍然不高。