给出python实现逻辑斯蒂回归的代码,不能调用sklearn的库
时间: 2024-05-05 22:19:04 浏览: 93
基于jupyter notebook的python编程—–运用sklearn库,导入文件数据模拟一元线性回归分析
好的,以下是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)
# initialize weights as zeros
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)}')
def predict_proba(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_proba(X) >= threshold
```
这个代码使用了梯度下降算法来训练模型。fit方法用于拟合数据,predict方法用于预测数据,predict_proba方法用于返回预测概率。
阅读全文