pandas实现logistic回归
时间: 2023-07-11 10:07:44 浏览: 144
Logistic回归
使用pandas实现logistic回归的步骤如下:
1.导入所需的库和数据集:
```python
import pandas as pd
from sklearn.linear_model import LogisticRegression
df = pd.read_csv('data.csv')
```
2.将数据集分为训练集和测试集:
```python
train_data = df.iloc[:80, :]
test_data = df.iloc[80:, :]
```
3.将训练数据集的特征和目标变量分离:
```python
X_train = train_data.iloc[:, :-1]
y_train = train_data.iloc[:, -1]
```
4.训练模型:
```python
model = LogisticRegression()
model.fit(X_train, y_train)
```
5.使用测试集评估模型:
```python
X_test = test_data.iloc[:, :-1]
y_test = test_data.iloc[:, -1]
y_pred = model.predict(X_test)
accuracy = (y_pred == y_test).sum() / len(y_test)
print('Accuracy:', accuracy)
```
完整代码如下:
```python
import pandas as pd
from sklearn.linear_model import LogisticRegression
df = pd.read_csv('data.csv')
train_data = df.iloc[:80, :]
test_data = df.iloc[80:, :]
X_train = train_data.iloc[:, :-1]
y_train = train_data.iloc[:, -1]
model = LogisticRegression()
model.fit(X_train, y_train)
X_test = test_data.iloc[:, :-1]
y_test = test_data.iloc[:, -1]
y_pred = model.predict(X_test)
accuracy = (y_pred == y_test).sum() / len(y_test)
print('Accuracy:', accuracy)
```
阅读全文