使用mutual_info回归进行特征选择时的重塑错误

2024-04-15

我正在尝试使用mutual_info_regression 和 SelectKBest 包装器进行一些功能选择。然而,我不断遇到一个错误,表明我的功能列表需要重新整形为二维数组,不太确定为什么我不断收到此消息 -

#feature selection before linear regression benchmark test
import sklearn
from sklearn.feature_selection import mutual_info_regression, SelectKBest
features = list(housing_data[housing_data.columns.difference(['sale_price'])])
target = 'sale_price'
new = SelectKBest(mutual_info_regression, k=20).fit_transform(features, target)

这是我的回溯:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-18-8c778124066c> in <module>()
      3 features = list(housing_data[housing_data.columns.difference(['sale_price'])])
      4 target = 'sale_price'
----> 5 new = SelectKBest(mutual_info_regression, k=20).fit_transform(features, target)

/usr/local/lib/python3.6/dist-packages/sklearn/base.py in fit_transform(self, X, y, **fit_params)
    463         else:
    464             # fit method of arity 2 (supervised transformation)
--> 465             return self.fit(X, y, **fit_params).transform(X)
    466 
    467 

/usr/local/lib/python3.6/dist-packages/sklearn/feature_selection/univariate_selection.py in fit(self, X, y)
    339         self : object
    340         """
--> 341         X, y = check_X_y(X, y, ['csr', 'csc'], multi_output=True)
    342 
    343         if not callable(self.score_func):

/usr/local/lib/python3.6/dist-packages/sklearn/utils/validation.py in check_X_y(X, y, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, multi_output, ensure_min_samples, ensure_min_features, y_numeric, warn_on_dtype, estimator)
    754                     ensure_min_features=ensure_min_features,
    755                     warn_on_dtype=warn_on_dtype,
--> 756                     estimator=estimator)
    757     if multi_output:
    758         y = check_array(y, 'csr', force_all_finite=True, ensure_2d=False,

/usr/local/lib/python3.6/dist-packages/sklearn/utils/validation.py in check_array(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, warn_on_dtype, estimator)
    550                     "Reshape your data either using array.reshape(-1, 1) if "
    551                     "your data has a single feature or array.reshape(1, -1) "
--> 552                     "if it contains a single sample.".format(array))
    553 
    554         # in the future np.flexible dtypes will be handled like object dtypes

ValueError: Expected 2D array, got 1D array instead:
array=['APPBBL' 'APPDate' 'Address' 'AreaSource' 'AssessLand' 'AssessTot' 'BBL'
 'BldgArea' 'BldgClass' 'BldgDepth' 'BldgFront' 'BoroCode' 'Borough'
 'BsmtCode' 'BuiltFAR' 'CB2010' 'CD' 'CT2010' 'ComArea' 'CommFAR'
 'CondoNo' 'Council' 'EDesigNum' 'Easements' 'ExemptLand' 'ExemptTot'
 'Ext' 'FIRM07_FLA' 'FacilFAR' 'FactryArea' 'FireComp' 'GarageArea'
 'HealthArea' 'HealthCent' 'HistDist' 'IrrLotCode' 'LandUse' 'Landmark'
 'LotArea' 'LotDepth' 'LotFront' 'LotType' 'LtdHeight' 'MAPPLUTO_F'
 'NumBldgs' 'NumFloors' 'OfficeArea' 'OtherArea' 'Overlay1' 'Overlay2'
 'OwnerName' 'OwnerType' 'PFIRM15_FL' 'PLUTOMapID' 'PolicePrct' 'ProxCode'
 'ResArea' 'ResidFAR' 'RetailArea' 'SHAPE_Area' 'SHAPE_Leng' 'SPDist1'
 'SPDist2' 'SPDist3' 'Sanborn' 'SanitBoro' 'SanitDistr' 'SanitSub'
 'SchoolDist' 'SplitZone' 'StrgeArea' 'TaxMap' 'Tract2010' 'UnitsRes'
 'UnitsTotal' 'Unnamed: 0' 'Version' 'XCoord' 'YCoord' 'YearAlter1'
 'YearAlter2' 'YearBuilt' 'ZMCode' 'ZipCode' 'ZoneDist1' 'ZoneDist2'
 'ZoneDist3' 'ZoneDist4' 'ZoneMap' 'address' 'apartment_number' 'block'
 'borough' 'building_class' 'building_class_at_sale'
 'building_class_category' 'commercial_units' 'easement' 'gross_sqft'
 'land_sqft' 'lot' 'neighborhood' 'price_range' 'residential_units'
 'sale_date' 'tax_class' 'tax_class_at_sale' 'total_units' 'year_built'
 'year_of_sale' 'zip_code'].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

这是我的数据示例:

housing_data = pd.DataFrame({'Unnamed: 0': {0: 1, 1: 2, 2: 3, 3: 4}, 'borough': {0: 3, 1: 3, 2: 3, 3: 3}, 'neighborhood': {0: 'DOWNTOWN-METROTECH', 1: 'DOWNTOWN-FULTON FERRY', 2: 'BROOKLYN HEIGHTS', 3: 'MILL BASIN'}, 'building_class_category': {0: '28  COMMERCIAL CONDOS', 1: '29  COMMERCIAL GARAGES', 2: '21  OFFICE BUILDINGS', 3: '22  STORE BUILDINGS'}, 'tax_class': {0: '4', 1: '4', 2: '4', 3: '4'}, 'block': {0: 140, 1: 54, 2: 204, 3: 8470}, 'lot': {0: 1001, 1: 1, 2: 1, 3: 55}, 'easement': {0: nan, 1: nan, 2: nan, 3: nan}, 'building_class': {0: 'R5', 1: 'G7', 2: 'O6', 3: 'K6'}, 'address': {0: '330 JAY STREET', 1: '85 JAY STREET', 2: '29 COLUMBIA HEIGHTS', 3: '5120 AVENUE U'}, 'apartment_number': {0: 'COURT', 1: nan, 2: nan, 3: nan}, 'zip_code': {0: 11201, 1: 11201, 2: 11201, 3: 11234}, 'residential_units': {0: 0, 1: 0, 2: 0, 3: 0}, 'commercial_units': {0: 1, 1: 0, 2: 0, 3: 123}, 'total_units': {0: 1, 1: 0, 2: 0, 3: 123}, 'land_sqft': {0: 0.0, 1: 134988.0, 2: 32000.0, 3: 905000.0}, 'gross_sqft': {0: 0.0, 1: 0.0, 2: 304650.0, 3: 2548000.0}, 'year_built': {0: 2002, 1: 0, 2: 1924, 3: 1970}, 'tax_class_at_sale': {0: 4, 1: 4, 2: 4, 3: 4}, 'building_class_at_sale': {0: 'R5', 1: 'G7', 2: 'O6', 3: 'K6'}, 'sale_price': {0: 499401179.0, 1: 345000000.0, 2: 340000000.0, 3: 276947000.0}, 'sale_date': {0: '2008-04-23', 1: '2016-12-20', 2: '2016-08-03', 3: '2012-11-28'}, 'year_of_sale': {0: 2008, 1: 2016, 2: 2016, 3: 2012}, 'Borough': {0: nan, 1: 'BK', 2: 'BK', 3: 'BK'}, 'CD': {0: nan, 1: 302.0, 2: 302.0, 3: 318.0}, 'CT2010': {0: nan, 1: 21.0, 2: 1.0, 3: 698.0}, 'CB2010': {0: nan, 1: 3017.0, 2: 1003.0, 3: 2005.0}, 'SchoolDist': {0: nan, 1: 13.0, 2: 13.0, 3: 22.0}, 'Council': {0: nan, 1: 33.0, 2: 33.0, 3: 46.0}, 'ZipCode': {0: nan, 1: 11201.0, 2: 11201.0, 3: 11234.0}, 'FireComp': {0: nan, 1: 'L118', 2: 'E205', 3: 'E323'}, 'PolicePrct': {0: nan, 1: 84.0, 2: 84.0, 3: 63.0}, 'HealthCent': {0: nan, 1: 36.0, 2: 38.0, 3: 35.0}, 'HealthArea': {0: nan, 1: 1000.0, 2: 2300.0, 3: 8822.0}, 'SanitBoro': {0: nan, 1: 3.0, 2: 3.0, 3: 3.0}, 'SanitDistr': {0: nan, 1: 2.0, 2: 2.0, 3: 18.0}, 'SanitSub': {0: nan, 1: '1B', 2: '1A', 3: '4E'}, 'Address': {0: nan, 1: '87 JAY STREET', 2: '29 COLUMBIA HEIGHTS', 3: '5120 AVENUE U'}, 'ZoneDist1': {0: nan, 1: 'M1-2/R8', 2: 'M2-1', 3: 'M3-1'}, 'ZoneDist2': {0: nan, 1: nan, 2: nan, 3: nan}, 'ZoneDist3': {0: nan, 1: nan, 2: nan, 3: nan}, 'ZoneDist4': {0: nan, 1: nan, 2: nan, 3: nan}, 'Overlay1': {0: nan, 1: nan, 2: nan, 3: nan}, 'Overlay2': {0: nan, 1: nan, 2: nan, 3: nan}, 'SPDist1': {0: nan, 1: 'MX-2', 2: nan, 3: nan}, 'SPDist2': {0: nan, 1: nan, 2: nan, 3: nan}, 'SPDist3': {0: nan, 1: nan, 2: nan, 3: nan}, 'LtdHeight': {0: nan, 1: nan, 2: nan, 3: nan}, 'SplitZone': {0: nan, 1: 'N', 2: 'N', 3: 'N'}, 'BldgClass': {0: nan, 1: 'G7', 2: 'O6', 3: 'K6'}, 'LandUse': {0: nan, 1: 10.0, 2: 5.0, 3: 5.0}, 'Easements': {0: nan, 1: 0.0, 2: 0.0, 3: 1.0}, 'OwnerType': {0: nan, 1: 'P', 2: nan, 3: nan}, 'OwnerName': {0: nan, 1: '85 JAY STREET BROOKLY', 2: '25-30 COLUMBIA HEIGHT', 3: 'BROOKLYN KINGS PLAZA'}, 'LotArea': {0: nan, 1: 134988.0, 2: 32000.0, 3: 905000.0}, 'BldgArea': {0: nan, 1: 0.0, 2: 304650.0, 3: 2548000.0}, 'ComArea': {0: nan, 1: 0.0, 2: 304650.0, 3: 2548000.0}, 'ResArea': {0: nan, 1: 0.0, 2: 0.0, 3: 0.0}, 'OfficeArea': {0: nan, 1: 0.0, 2: 264750.0, 3: 0.0}, 'RetailArea': {0: nan, 1: 0.0, 2: 0.0, 3: 1263000.0}, 'GarageArea': {0: nan, 1: 0.0, 2: 0.0, 3: 1285000.0}, 'StrgeArea': {0: nan, 1: 0.0, 2: 0.0, 3: 0.0}, 'FactryArea': {0: nan, 1: 0.0, 2: 0.0, 3: 0.0}, 'OtherArea': {0: nan, 1: 0.0, 2: 39900.0, 3: 0.0}, 'AreaSource': {0: nan, 1: 7.0, 2: 2.0, 3: 2.0}, 'NumBldgs': {0: nan, 1: 0.0, 2: 1.0, 3: 4.0}, 'NumFloors': {0: nan, 1: 0.0, 2: 13.0, 3: 2.0}, 'UnitsRes': {0: nan, 1: 0.0, 2: 0.0, 3: 0.0}, 'UnitsTotal': {0: nan, 1: 0.0, 2: 0.0, 3: 123.0}, 'LotFront': {0: nan, 1: 490.5, 2: 92.42, 3: 930.0}, 'LotDepth': {0: nan, 1: 275.33, 2: 335.92, 3: 859.0}, 'BldgFront': {0: nan, 1: 0.0, 2: 335.0, 3: 0.0}, 'BldgDepth': {0: nan, 1: 0.0, 2: 92.0, 3: 0.0}, 'Ext': {0: nan, 1: nan, 2: nan, 3: nan}, 'ProxCode': {0: nan, 1: 0.0, 2: 0.0, 3: 0.0}, 'IrrLotCode': {0: nan, 1: 'N', 2: 'Y', 3: 'Y'}, 'LotType': {0: nan, 1: 5.0, 2: 3.0, 3: 3.0}, 'BsmtCode': {0: nan, 1: 5.0, 2: 5.0, 3: 5.0}, 'AssessLand': {0: nan, 1: 1571850.0, 2: 1548000.0, 3: 36532350.0}, 'AssessTot': {0: nan, 1: 1571850.0, 2: 25463250.0, 3: 149792400.0}, 'ExemptLand': {0: nan, 1: 1571850.0, 2: 0.0, 3: 0.0}, 'ExemptTot': {0: nan, 1: 1571850.0, 2: 0.0, 3: 0.0}, 'YearBuilt': {0: nan, 1: 0.0, 2: 1924.0, 3: 1970.0}, 'YearAlter1': {0: nan, 1: 0.0, 2: 1980.0, 3: 0.0}, 'YearAlter2': {0: nan, 1: 0.0, 2: 0.0, 3: 0.0}, 'HistDist': {0: nan, 1: nan, 2: nan, 3: nan}, 'Landmark': {0: nan, 1: nan, 2: nan, 3: nan}, 'BuiltFAR': {0: nan, 1: 0.0, 2: 9.52, 3: 2.82}, 'ResidFAR': {0: nan, 1: 7.2, 2: 0.0, 3: 0.0}, 'CommFAR': {0: nan, 1: 2.0, 2: 2.0, 3: 2.0}, 'FacilFAR': {0: nan, 1: 6.5, 2: 0.0, 3: 0.0}, 'BoroCode': {0: nan, 1: 3.0, 2: 3.0, 3: 3.0}, 'BBL': {0: nan, 1: 3000540001.0, 2: 3002040001.0, 3: 3084700055.0}, 'CondoNo': {0: nan, 1: 0.0, 2: 0.0, 3: 0.0}, 'Tract2010': {0: nan, 1: 21.0, 2: 1.0, 3: 698.0}, 'XCoord': {0: nan, 1: 988208.0, 2: 985952.0, 3: 1006597.0}, 'YCoord': {0: nan, 1: 195011.0, 2: 195007.0, 3: 161424.0}, 'ZoneMap': {0: nan, 1: '12d', 2: '12d', 3: '23b'}, 'ZMCode': {0: nan, 1: nan, 2: nan, 3: nan}, 'Sanborn': {0: nan, 1: '302 016', 2: '302 004', 3: '319 077'}, 'TaxMap': {0: nan, 1: 30101.0, 2: 30106.0, 3: 32502.0}, 'EDesigNum': {0: nan, 1: nan, 2: nan, 3: nan}, 'APPBBL': {0: nan, 1: 3000540001.0, 2: 0.0, 3: 0.0}, 'APPDate': {0: nan, 1: '12/06/2002', 2: nan, 3: nan}, 'PLUTOMapID': {0: nan, 1: 1.0, 2: 1.0, 3: 1.0}, 'FIRM07_FLA': {0: nan, 1: nan, 2: nan, 3: 1.0}, 'PFIRM15_FL': {0: nan, 1: nan, 2: nan, 3: 1.0}, 'Version': {0: nan, 1: '17V1.1', 2: '17V1.1', 3: '17V1.1'}, 'MAPPLUTO_F': {0: nan, 1: 0.0, 2: 0.0, 3: 0.0}, 'SHAPE_Leng': {0: nan, 1: 1559.88914353, 2: 890.718521021, 3: 3729.78685686}, 'SHAPE_Area': {0: nan, 1: 140131.577176, 2: 34656.4472405, 3: 797554.847834}, 'price_range': {0: nan, 1: nan, 2: nan, 3: nan}})

转换器需要一个形状为 (n x m) 的 2D 数组,其中 n 是样本数,m 是特征数,如果您查看以下形状features我想它会显示:(m,).

重塑数组

一般来说,对于形状的特征数组(n,),您可以按照错误代码的建议进行操作并调用.reshape(-1,1)在你的特征数组上,-1让它infer https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html附加维度:数组的形状将是(n,m),其中对于 1 个特征案例m = 1.

Sklearn 变压器

综上所述,我认为您的代码和理解存在其他错误。

我会打印features进行筛选并检查它是否是您想要的,看起来您正在打印list所有列名称,除了sale_price。 我不熟悉选择KBest https://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.SelectKBest.html#sklearn.feature_selection.SelectKBest.fit_transform但它需要一个(n,m)特征array不是特征的列名称列表。

此外,target不应该是目标列的名称,而是形状数组(n,),其中它的值是训练实例的观察到的目标值。

我建议在编写代码时检查文档(之前引用过),以确保使用正确的参数并按预期使用该函数。

提取特征

您的数据似乎采用奇怪的格式(字典嵌套在 pandas DF 中)。然而,这是我如何从pd.DataFrame与 SKlearn 框架中的函数一起使用。

housing_data = pd.DataFrame({'age': [1,5,1,10], 'size':[0,1,2,0], 
                             'price':[190,100,50,100]
                            })

feature_arr = housing_data.drop('price', axis=1).values
target_values = housing_data['price']

Print feature_arr希望您能看到您的问题。通常你必须预处理 https://scikit-learn.org/stable/modules/preprocessing.html例如,删除 NaN 值或执行特征缩放。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用mutual_info回归进行特征选择时的重塑错误 的相关文章

  • 将预训练的手套词嵌入与 scikit-learn 结合使用

    我已经使用 keras 来使用预先训练的词嵌入 但我不太确定如何在 scikit learn 模型上执行此操作 我也需要在 sklearn 中执行此操作 因为我正在使用vecstack集成 keras 序列模型和 sklearn 模型 这就
  • API网关+Lambda+Python:处理异常

    我正在非代理模式下从 API Gateway 调用基于 Python 的 AWS Lambda 方法 我应该如何正确处理异常 以便使用部分异常设置适当的 HTTP 状态代码以及 JSON 正文 作为示例 我有以下处理程序 def my ha
  • 通过 rpy 将 SPSS 文件(.sav)导入 pandas 时如何保留标签?

    我正在寻找使用 SPSS 文件 sav pandas 在没有 SPSS 程序的情况下 典型文件转换为 csv 后的样子如下 在调查前两行的含义时 我不知道 SPSS 似乎第一行包含Labels 而第二行包含VarNames 当我将文件带入
  • 用定点迭代求解该方程

    我怎样才能解这个方程 x3 x 1 0 使用定点迭代 有没有定点迭代我可以在网上找到代码 尤其是Python 吗 Using scipy optimize fixed point http docs scipy org doc scipy
  • 使用正则表达式检查整个字符串

    我正在尝试检查字符串是否是数字 因此正则表达式 d 似乎不错 然而 由于某种原因 该正则表达式也适合 78 46 92 168 8000 这是我不想要的 一些代码 class Foo rex re compile d def bar sel
  • pybind11:如何将 c++ 和 python 代码打包到一个包中?

    我正在尝试使用 CMake 和 pybind 11 将现有的 Python 代码和新的 C 11 代码打包在一起 我认为我缺少一些可以添加到 CMake 脚本中的简单内容 但在任何地方都找不到它 pybind11 示例只有 C 代码和没有P
  • Python 排列(包括子字符串)

    我遇到过这个帖子 如何在Python中生成列表的所有排列 https stackoverflow com questions 104420 how to generate all permutations of a list in pyth
  • 如何在 Django 1.4 中自定义管理过滤器

    我是 Python 和 Django 开发的新手 我从社区提供的易于阅读的示例中学到了很多东西 但最近我想为 Django 附带的管理控制台实现一个自定义的管理过滤器 我进行了很多搜索 只发现了一些过时的方法来完成它 例如 Django 1
  • 有效地写入 pandas 中的多个相邻列

    使用 numpy ndarray 可以一次写入多个列 而无需先进行复制 只要它们相邻 如果我想写入数组的前三列 我会写 a 0 0 3 1 2 3 this is very fast a is a numpy ndarray 我希望在 pa
  • 更新或插入 MySQL Python

    如果记录已存在 我需要更新一行 如果不存在 我需要创建一个新记录 我理解 ON DUPLICATE KEY 将使用 MYSQLdb 完成此操作 但是我无法使其正常工作 我的代码如下 cursor database cursor cursor
  • Tkinter:通过多处理启动进程会创建不需要的新窗口

    我计划围绕数值模拟编写一个小型 GUI 这就是我现在使用 Tkinter 的原因 模拟应在单独的进程中从 GUI 启动 为了玩一下 我定义了一个函数 random process 来生成成对的 randn 数字 这应该是一个真正的模拟过程
  • 如何避免在matplotlib中调用latex(输出到pgf)

    我使用 matplotlib 及其 pgf 后端来生成包含在 LaTeX 投影仪文档中的绘图 当我使用未定义的乳胶命令时 我遇到了麻烦 但对于我的应用程序 我不需要 matplotlib 来使用 Latex 生成标签或注释 我只想要正确的
  • Pandas 使用什么规则来生成视图和副本?

    我对 Pandas 在决定数据帧中的选择是原始数据帧的副本或原始数据帧的视图时使用的规则感到困惑 例如 如果我有 df pd DataFrame np random randn 8 8 columns list ABCDEFGH index
  • Google App Engine self.redirect() POST 方法

    在 GAE Python 中 使用 webApp 框架 调用 self redirect some url 通过 GET 方法将用户重定向到该 URL 是否也可以通过带有一些参数的 POST 方法进行 重定向 如果可以的话 怎样做 Than
  • Django admin.py 未知命令:'collectstatic'

    我已经从 django 1 2 7 升级到 django 1 5 1我正在使用 python 2 6 6当我尝试跑步时python manage py collectstatic i get 未知命令 collectstatic 从我的设置
  • 使用条件在 pandas 数据框中生成新列

    我有一个 pandas 数据框 如下所示 portion used 0 1 1 0 1 2 0 3 2 3 0 0 3 4 0 8 我想根据以下内容创建一个新专栏used列 以便df看起来像这样 portion used alert 0 1
  • 为什么我可以使用 tsql 连接到 Azure MS SQL,但不能使用 pymssql?

    我今天在哪里 TDSVER 7 3 tsql H example database windows net U me D ExampleDB p 1433 P notreallymypassword 这不会 gt gt gt import
  • 在 python 中使用 re.sub 将字母变成大写?

    在许多编程语言中 以下内容 find foo a z bar并替换为GOO U 1GAR 将导致整个匹配项变为大写 我似乎无法在 python 中找到等效项 它存在吗 您可以将函数传递给re sub http docs python org
  • 捕获 SQLAlchemy 异常

    我可以使用什么捕获 SQLAlechmy 异常的上层异常 gt gt gt from sqlalchemy import exc gt gt gt dir exc ArgumentError CircularDependencyError
  • Pandas:如何删除以 nan 作为列名的多个列?

    根据标题 这是一个可重现的示例 raw data x this that this that this np nan np nan np nan np nan np nan np nan y np nan np nan np nan np

随机推荐