鸢尾花分类-对数几率回归实验代码实验结果python
时间: 2025-06-24 15:46:07 浏览: 11
### 关于鸢尾花分类的对数几率回归实验
以下是基于 Python 的鸢尾花数据集分类实验代码,采用逻辑回归(即对数几率回归)方法实现。该代码分为两部分:一部分利用 `scikit-learn` 提供的现成函数完成多分类任务;另一部分则手动实现了对数几率回归模型并进行了验证。
#### 使用 Scikit-Learn 实现逻辑回归
此部分展示了如何通过调用 `scikit-learn` 中的 `LogisticRegression` 函数来完成鸢尾花数据集的多分类任务[^1]:
```python
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
if __name__ == "__main__":
# 加载鸢尾花数据集
iris = datasets.load_iris()
X = iris.data
y = iris.target
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=666)
# 初始化逻辑回归模型
log_reg = LogisticRegression(multi_class='multinomial', solver='newton-cg')
# 训练模型
log_reg.fit(X_train, y_train)
# 测试模型性能
score = log_reg.score(X_test, y_test)
y_predict = log_reg.predict(X_test)
# 输出预测结果及准确率
print("Predicted labels (y_predict): {}.".format(y_predict))
print("Accuracy of the model on the test set: {:.2f}%".format(score * 100))
```
运行以上代码后,可以得到模型在测试集上的预测标签以及分类准确率。
---
#### 手动实现对数几率回归模型
如果希望深入了解算法内部机制,则可以通过手动编写代码实现对数几率回归模型[^2]。以下是一个简单的例子:
```python
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def softmax(Z):
expZ = np.exp(Z - np.max(Z, axis=1, keepdims=True))
return expZ / np.sum(expZ, axis=1, keepdims=True)
def compute_loss(Y, Y_hat):
m = Y.shape[0]
loss = -(np.sum(np.multiply(Y, np.log(Y_hat)))) / m
return loss
def fit(X, Y, learning_rate=0.1, epochs=1000):
m, n = X.shape
W = np.zeros((n, 3)) # 假设三类问题
b = np.zeros((1, 3))
losses = []
onehot_encoder = OneHotEncoder(sparse=False)
Y_one_hot = onehot_encoder.fit_transform(Y.reshape(-1, 1))
for epoch in range(epochs):
Z = np.dot(X, W) + b
Y_hat = softmax(Z)
J = compute_loss(Y_one_hot, Y_hat)
losses.append(J)
dW = (1/m) * np.dot(X.T, (Y_hat - Y_one_hot))
db = (1/m) * np.sum(Y_hat - Y_one_hot, axis=0, keepdims=True)
W -= learning_rate * dW
b -= learning_rate * db
return W, b, losses
if __name__ == "__main__":
iris = load_iris()
X = iris.data
y = iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=42)
W, b, _ = fit(X_train, y_train, learning_rate=0.1, epochs=1000)
Z_test = np.dot(X_test, W) + b
predictions = np.argmax(softmax(Z_test), axis=1)
accuracy = np.mean(predictions == y_test)
print(f"Test Accuracy: {accuracy:.2f}")
```
在此代码中,定义了一个自定义的梯度下降优化过程,并计算了交叉熵损失函数以评估模型表现。
---
### 结果分析
对于第一种方法,使用 `scikit-learn` 库中的 `LogisticRegression` 类型,通常可以获得较高的准确性,具体取决于随机划分的数据分布情况。而对于第二种方法,由于是从零开始构建模型,因此可能需要更多的时间调整超参数(如学习速率、迭代次数等),才能达到类似的精度水平[^2]。
阅读全文
相关推荐


















