当前位置: 首页 > news >正文

线性回归模型进行特征重要性分析

目的

        线性回归是很常用的模型;在局部可解释性上也经常用到。

数据归一化

        归一化通常是为了确保不同特征之间的数值范围差异不会对线性模型的训练产生过大的影响。在某些情况下,特征归一化可以提高模型的性能,但并不是所有情况下都需要进行归一化。

        归一化的必要性取决于你的数据和所使用的算法。对于某些线性模型,比如线性回归和支持向量机,数据归一化是一个常见的实践,因为它们对特征的尺度敏感。

        但对于其他算法,如决策树和随机森林,通常不需要进行归一化。

        在实际应用中,建议根据你的数据和所选用的模型来决定是否进行归一化。如果你的数据特征具有不同的尺度,并且你使用的是那些对特征尺度敏感的线性模型,那么进行归一化可能会有所帮助。否则,你可以尝试在没有归一化的情况下训练模型,然后根据模型性能来决定是否需要进行归一化。

 对新数据进行归一化处理
new_data_sample_scaled = scaler.transform(new_data_sample)

# 使用模型进行预测
predicted_value = model.predict(new_data_sample_scaled)
这样就能确保在预测新数据时,特征的尺度与训练数据保持一致。

MinMaxScaler底层代码

class MinMaxScaler Found at: sklearn.preprocessing.data

class MinMaxScaler(BaseEstimator, TransformerMixin):

    def __init__(self, feature_range=(0, 1), copy=True):
        self.feature_range = feature_range
        self.copy = copy
    
    def _reset(self):
        """Reset internal data-dependent state of the scaler, if 
         necessary.

        __init__ parameters are not touched.
        """
    # Checking one attribute is enough, becase they are all set 
     together
    # in partial_fit
        if hasattr(self, 'scale_'):
            del self.scale_
            del self.min_
            del self.n_samples_seen_
            del self.data_min_
            del self.data_max_
            del self.data_range_
    
    def fit(self, X, y=None):
        """Compute the minimum and maximum to be used for later 
         scaling.

        Parameters
        ----------
        X : array-like, shape [n_samples, n_features]
            The data used to compute the per-feature minimum and 
             maximum
            used for later scaling along the features axis.
        """
        # Reset internal state before fitting
        self._reset()
        return self.partial_fit(X, y)
    
    def partial_fit(self, X, y=None):
        """Online computation of min and max on X for later scaling.
        All of X is processed as a single batch. This is intended for 
         cases
        when `fit` is not feasible due to very large number of 
         `n_samples`
        or because X is read from a continuous stream.

        Parameters
        ----------
        X : array-like, shape [n_samples, n_features]
            The data used to compute the mean and standard deviation
            used for later scaling along the features axis.

        y : Passthrough for ``Pipeline`` compatibility.
        """
        feature_range = self.feature_range
        if feature_range[0] >= feature_range[1]:
            raise ValueError(
                "Minimum of desired feature range must be smaller"
                " than maximum. Got %s." % 
                str(feature_range))
        if sparse.issparse(X):
            raise TypeError("MinMaxScaler does no support sparse 
             input. "
                "You may consider to use MaxAbsScaler instead.")
        X = check_array(X, copy=self.copy, warn_on_dtype=True, 
         estimator=self, dtype=FLOAT_DTYPES)
        data_min = np.min(X, axis=0)
        data_max = np.max(X, axis=0)
        # First pass
        if not hasattr(self, 'n_samples_seen_'):
            self.n_samples_seen_ = X.shape[0]
        else:
            data_min = np.minimum(self.data_min_, data_min)
            data_max = np.maximum(self.data_max_, data_max)
            self.n_samples_seen_ += X.shape[0] # Next steps
        data_range = data_max - data_min
        self.scale_ = (feature_range[1] - feature_range[0]) / 
         _handle_zeros_in_scale(data_range)
        self.min_ = feature_range[0] - data_min * self.scale_
        self.data_min_ = data_min
        self.data_max_ = data_max
        self.data_range_ = data_range
        return self
    
    def transform(self, X):
        """Scaling features of X according to feature_range.

        Parameters
        ----------
        X : array-like, shape [n_samples, n_features]
            Input data that will be transformed.
        """
        check_is_fitted(self, 'scale_')
        X = check_array(X, copy=self.copy, dtype=FLOAT_DTYPES)
        X *= self.scale_
        X += self.min_
        return X
    
    def inverse_transform(self, X):
        """Undo the scaling of X according to feature_range.

        Parameters
        ----------
        X : array-like, shape [n_samples, n_features]
            Input data that will be transformed. It cannot be sparse.
        """
        check_is_fitted(self, 'scale_')
        X = check_array(X, copy=self.copy, dtype=FLOAT_DTYPES)
        X -= self.min_
        X /= self.scale_
        return X


数据分箱

n_bins = [5]
kb = KBinsDiscretizer(n_bins=n_bins, encode = 'ordinal')
kb.fit(X[selected_features])
X_train=kb.transform(X_train[selected_features])
from sklearn.preprocessing import KBinsDiscretizer
import joblib

# 创建 KBinsDiscretizer 实例并进行分箱
est = KBinsDiscretizer(n_bins=3, encode='ordinal', strategy='uniform')
X_binned = est.fit_transform(X)

# 保存 KBinsDiscretizer 参数到文件
joblib.dump(est, 'kbins_discretizer.pkl')

# 加载 KBinsDiscretizer 参数
loaded_estimator = joblib.load('kbins_discretizer.pkl')

# 使用加载的参数进行分箱
X_binned_loaded = loaded_estimator.transform(X)

from sklearn.preprocessing import KBinsDiscretizer

def save_kbins_discretizer_params(estimator, filename):
    params = {
        'n_bins': estimator.n_bins,
        'encode': estimator.encode,
        'strategy': estimator.strategy,
        # 其他可能的参数
    }
    
    with open(filename, 'w') as f:
        for key, value in params.items():
            f.write(f"{key}: {value}\n")

# 创建 KBinsDiscretizer 实例并进行分箱
est = KBinsDiscretizer(n_bins=3, encode='ordinal', strategy='uniform')

# 保存 KBinsDiscretizer 参数到文本文件
save_kbins_discretizer_params(est, 'kbins_discretizer_params.txt')

 KBinsDiscretizer 的源代码


KBinsDiscretizer 的源代码参数包括:

n_bins:指定要创建的箱的数量。
encode:指定编码的方法。可以是'onehot'、'onehot-dense'、'ordinal'中的一个。
strategy:指定分箱的策略。可以是'uniform'、'quantile'、'kmeans'中的一个。
dtype:指定输出数组的数据类型。
bin_edges_:一个属性,它包含每个特征的箱的边界。
以下是 KBinsDiscretizer 类的源代码参数的简要说明:

n_bins:用于指定要创建的箱的数量。默认值为5。
encode:指定编码的方法。可选值包括:
'onehot':使用一热编码。
'onehot-dense':使用密集矩阵的一热编码。
'ordinal':使用整数标签编码。默认为 'onehot'。
strategy:指定分箱的策略。可选值包括:
'uniform':将箱的宽度保持相等。
'quantile':将箱的数量保持不变,但是每个箱内的样本数量大致相等。
'kmeans':将箱的数量保持不变,但是使用 k-means 聚类来确定箱的边界。默认为 'quantile'。
dtype:指定输出数组的数据类型。默认为 np.float64。
bin_edges_:一个属性,它包含每个特征的箱的边界。这是一个列表,其中每个元素都是一个数组,表示相应特征的箱的边界。
您可以在 sklearn/preprocessing/_discretization.py 中找到 KBinsDiscretizer 类的完整源代码,以查看详细的参数和实现细节。

相关文章:

  • 阶段六-Day02-Maven
  • GEO生信数据挖掘(七)差异基因分析
  • 数据结构八大排序Java源码
  • 从基础到卷积神经网络(第12天)
  • k8s - Flannel
  • scapy构造ND报文
  • 服务运营 |摘要:学术+业界-近期前沿运筹医疗合作精选
  • Python学习 day03(注意事项)
  • JVM 性能调优参数
  • uniapp编译到小程序Component is not found in path “components/energy/illumination“
  • element树形控件编辑节点组装节点
  • 上海-华为全联接大会|竹云受邀参加华为云ROMAConnect行业生态联盟成立联合发布会
  • django: You may need to add ‘localhost‘ to ALLOWED_HOSTS
  • k8s使用
  • pycharm远程调试运行程序出现No such file or directory:解决办法
  • c语言练习86:移除元素
  • Java版分布式微服务云开发架构 Spring Cloud+Spring Boot+Mybatis 电子招标采购系统功能清单
  • VueRouter与expres/koa中间件的关联
  • [Mono Depth/3DOD]单目3D检测基础
  • 【科学文献计量】利用pybibx分析Scopus文献数据集(EDA,N-Grams,Cluster,Network analysis,NLP)
  • 江西暴雨强对流明显,专家:落雨区高度重叠,地质灾害风险高
  • 西南大学教授、重庆健美运动奠基人之一李启圣逝世
  • 股价两天涨超30%,中航成飞:不存在应披露而未披露的重大事项
  • 上市不足一年,吉利汽车拟私有化极氪并合并:整合资源,杜绝重复投入
  • 外交部:中方和欧洲议会决定同步全面取消对相互交往的限制
  • 媒体:南京秦淮区卫健委回应一医院涉嫌违规提供试管婴儿服务