逻辑回归二分类算法python
时间: 2023-07-07 13:45:20 浏览: 69
逻辑回归是一种二分类算法,可以用来预测一个二元变量的结果。在Python中,可以使用scikit-learn库中的LogisticRegression类来实现逻辑回归算法。下面是一个简单的例子:
首先,引入需要的库:
```python
from sklearn.linear_model import LogisticRegression
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
```
然后,生成模拟数据集:
```python
X, y = make_classification(n_samples=1000, n_features=10, n_informative=5, n_redundant=0, random_state=42)
```
接着,将数据集划分为训练集和测试集:
```python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
```
接下来,使用LogisticRegression类进行模型训练:
```python
clf = LogisticRegression()
clf.fit(X_train, y_train)
```
最后,使用测试集进行模型评估:
```python
score = clf.score(X_test, y_test)
print("Accuracy: {:.2f}%".format(score*100))
```
完整代码如下:
```python
from sklearn.linear_model import LogisticRegression
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_informative=5, n_redundant=0, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
clf = LogisticRegression()
clf.fit(X_train, y_train)
score = clf.score(X_test, y_test)
print("Accuracy: {:.2f}%".format(score*100))
```