给我一个python logistic回归代码示例
时间: 2023-03-14 12:29:45 浏览: 47
import numpy as np
from sklearn.linear_model import LogisticRegression
# training data
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([0, 0, 0, 1])
# create and train model
model = LogisticRegression()
model.fit(X, y)
# predict
predictions = model.predict(X)
# results
print(predictions)
#[0 0 0 1]
相关问题
能给我一个stacking的python代码示例吗
当然可以,以下是一个简单的stacking代码示例:
```python
from sklearn.model_selection import KFold
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
import numpy as np
# 创建第一层模型
model1 = RandomForestClassifier(n_estimators=50, random_state=1)
model2 = GradientBoostingClassifier(n_estimators=50, random_state=1)
# 创建第二层模型
model3 = LogisticRegression()
# 加载数据集
X = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
y = np.array([0,1,1,0])
# 初始化第二层模型的输入集
meta_X = np.zeros((X.shape[0], 2))
# 使用K折交叉验证训练第一层模型并生成meta数据集
kf = KFold(n_splits=5, shuffle=True, random_state=1)
for train_index, test_index in kf.split(X):
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
model1.fit(X_train, y_train)
model2.fit(X_train, y_train)
meta_X[test_index, 0] = model1.predict(X_test)
meta_X[test_index, 1] = model2.predict(X_test)
# 训练第二层模型并进行预测
model3.fit(meta_X, y)
meta_pred = model3.predict(meta_X)
# 输出第二层模型的准确率
print('Final accuracy:', accuracy_score(y, meta_pred))
```
这个例子中,我们使用了两个基础分类器(随机森林和梯度提升树)和一个逻辑回归作为元学习器。我们使用K折交叉验证来生成第二层模型的输入,然后训练第二层模型并进行预测。
logistic回归 python代码
好的,下面是一个简单的 logistic 回归的 Python 代码:
# 导入需要的库
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
# 读取数据
data = pd.read_csv("data.csv")
# 准备数据
X = data.iloc[:, :-1]
y = data.iloc[:, -1]
# 数据切分,70% 作为训练数据,30% 作为测试数据
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# logistic回归模型训练
lr = LogisticRegression()
lr.fit(X_train, y_train)
# 预测并计算准确率
y_pred = lr.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
请注意,这只是一个基础的示例,实际应用中可能需要更多的数据处理、特征工程、调参等操作。