Python实现Logistic回归:代码示例和应用
以下是一个简单的实现Logistic回归的Python代码:
import numpy as np
class LogisticRegression:
def __init__(self, lr=0.01, num_iter=100000, fit_intercept=True, verbose=False):
self.lr = lr
self.num_iter = num_iter
self.fit_intercept = fit_intercept
self.verbose = verbose
def __add_intercept(self, X):
intercept = np.ones((X.shape[0], 1))
return np.concatenate((intercept, X), axis=1)
def __sigmoid(self, z):
return 1 / (1 + np.exp(-z))
def __loss(self, h, y):
return (-y * np.log(h) - (1 - y) * np.log(1 - h)).mean()
def fit(self, X, y):
if self.fit_intercept:
X = self.__add_intercept(X)
self.theta = np.zeros(X.shape[1])
for i in range(self.num_iter):
z = np.dot(X, self.theta)
h = self.__sigmoid(z)
gradient = np.dot(X.T, (h - y)) / y.size
self.theta -= self.lr * gradient
if self.verbose and i % 10000 == 0:
z = np.dot(X, self.theta)
h = self.__sigmoid(z)
print(f'Loss: {self.__loss(h, y)}\t')
def predict_prob(self, X):
if self.fit_intercept:
X = self.__add_intercept(X)
return self.__sigmoid(np.dot(X, self.theta))
def predict(self, X, threshold):
return self.predict_prob(X) >= threshold
使用方法:
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
X, y = make_classification(n_samples=1000, n_features=10, n_classes=2, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = LogisticRegression(lr=0.1, num_iter=300000)
model.fit(X_train, y_train)
predictions = model.predict(X_test, 0.5)
print(f'Accuracy: {(predictions == y_test).mean()}')
该代码使用梯度下降算法实现Logistic回归,并在训练数据上进行了拟合。在测试数据上进行了预测,并计算了准确率。
原文地址: https://www.cveoy.top/t/topic/mJuw 著作权归作者所有。请勿转载和采集!