分别使用sklearn自带的LogisticRegression和自定义的梯度下降法对鸢尾花数据集进行逻辑回归。(注意输入的特征我们使用鸢尾花数据集的前两个特征,输出的目标值也就是类别只有0,1需要设置剔除多余的类别)。根据题目生成图像
时间: 2025-06-28 19:05:30 浏览: 14
下面是使用sklearn自带的`LogisticRegression`以及自定义梯度下降法对鸢尾花数据集(仅取前两类)进行二分类,并绘制决策边界的过程。
### 使用 `sklearn.LogisticRegression`
首先展示如何利用现成库完成任务:
```python
from sklearn import datasets
import numpy as np
from sklearn.linear_model import LogisticRegression
import matplotlib.pyplot as plt
# 加载并准备数据
iris = datasets.load_iris()
X = iris.data[:, :2] # 只用前两个特征
y = (iris.target != 0) * 1 # 类别标签转换为布尔型然后转整数,只保留第0类和第1类的数据
# 创建逻辑回归模型实例化并训练
clf_lr = LogisticRegression(random_state=0).fit(X[y <= 1], y[y <= 1])
# 绘制结果图
plt.figure(figsize=(8,6))
x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02),
np.arange(y_min, y_max, 0.02))
Z = clf_lr.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1]
Z = Z.reshape(xx.shape)
plt.contourf(xx, yy, Z, alpha=.7)
for i in [0, 1]:
idx = (y == i)
plt.scatter(X[idx, 0], X[idx, 1],
c=['blue', 'red'][i], edgecolor='white',
label=f'Class {i}')
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')
plt.legend(loc="best")
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
plt.title("Decision boundary using sklearn's Logisitc Regression")
plt.show()
```
**解释**
- 这段程序加载了Iris数据集中所有样本但是只选择了第一第二列作为输入变量,同时将目标值限定于前两种类型。
- 接着建立了一个基于最大似然估计的标准logistic regression classifier。
- 最后通过matplotlib画出决策边界的图形表示形式,在这个图中还可以看到不同类型的点分布情况。
### 自定义梯度下降算法实现逻辑回归
接下来介绍怎样从零构建自己的逻辑回归器:
```python
class CustomLogReg:
def __init__(self):
self.w = None
@staticmethod
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def fit(self, X_train, Y_train, learning_rate=0.01, num_iterations=1000):
m, n = X_train.shape
w = np.zeros((n+1,))
ones = np.ones(m).reshape(-1, 1)
X = np.hstack([ones, X_train])
for iteration in range(num_iterations):
z = np.dot(X, w.T)
A = self.sigmoid(z)
dz = A-Y_train
dw = np.dot(dz,X)/m
w -= learning_rate*dw
self.w = w
def predict_probabilities(self, X_test):
ones = np.ones(len(X_test)).reshape(-1, 1)
X_new = np.hstack([ones, X_test])
probabilities = self.sigmoid(np.dot(X_new,self.w.T))
return probabilities
def predict(self, X_test, threshold=0.5):
probs = self.predict_probabilities(X_test)
predictions = np.where(probs >=threshold , 1., 0.)
return predictions
custom_clf = CustomLogReg()
custom_clf.fit(X[y<=1], y[y<=1])
# Plotting the results of custom logistic regressor
plt.figure(figsize=(8,6))
plt.contourf(xx,yy,
custom_clf.predict_probabilities(
np.array([xx.ravel(), yy.ravel()]).T
).reshape(xx.shape),alpha=0.7)
for i in [0,1]:
idx=y==i
plt.scatter(X[idx,0],X[idx,1],
c=["blue","red"][i],
edgecolors='w',
label=f"Class {i}")
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')
plt.legend(loc="upper left")
plt.title('Custom implemented Logistic Regressor Decision Boundary')
plt.show()
```
这段代码实现了与上面类似的功能,但这次是从头开始编写一个简单的逻辑回归模型。为了简化起见,这里没有包含如正则化的额外功能;这只是一个基本版本用于学习目的。
#### 注意事项:
- 在实际应用时你需要考虑更多细节例如参数调整、过拟合等问题;
- 如果想要提高性能或准确性你可以添加更多复杂性比如引入正则项等改进措施。
阅读全文
相关推荐

















