欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

逻辑回归_处理不均衡的数据

程序员文章站 2022-05-26 19:08:26
...

逻辑回归_处理不均衡的数据
class_weight=“balanced” 参数 根军样本出现的评论自动给 样本设置 权重

# 处理不均衡的数据
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn import datasets
from sklearn.preprocessing import StandardScaler
​
iris = datasets.load_iris()
# 移走40个数据,使数据不均衡
features = iris.data[40:, :]
target = iris.target[40:]
target
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2,
       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])
# 打标签 
target = np.where((target == 0), 0, 1)
target
# 标准化数据
scaler = StandardScaler()
features_standardized = scaler.fit_transform(features)
# class_weight="balanced"  参数  根军样本出现的评论自动给 样本设置 权重
logistic_regression = LogisticRegression(random_state=0, class_weight="balanced")
model = logistic_regression.fit(features_standardized, target)