不使用sklearn库
时间: 2023-11-14 20:21:26 浏览: 31
好的,那我们可以手写一个简单的分类器来对数据进行分类。以下是一个基于梯度下降的逻辑回归分类器的示例代码:
```python
import numpy as np
class LogisticRegression:
def __init__(self, lr=0.01, num_iterations=100000, fit_intercept=True):
self.lr = lr
self.num_iterations = num_iterations
self.fit_intercept = fit_intercept
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_iterations):
z = np.dot(X, self.theta)
h = self.sigmoid(z)
gradient = np.dot(X.T, (h - y)) / y.size
self.theta -= self.lr * gradient
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=0.5):
return self.predict_prob(X) >= threshold
```
在这个示例中,我们使用了逻辑回归模型来进行分类。该模型使用梯度下降算法来最小化损失函数,从而得到模型参数。在具体实现中,我们使用了sigmoid函数作为激活函数,用于将模型的输出映射到0到1之间,表示概率。然后我们可以使用阈值来将概率转换为二元分类结果。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)