【问题标题】:Why does numpy.corrcoef() returns nan?为什么 numpy.corrcoef() 返回 nan?
【发布时间】:2020-05-31 11:04:39
【问题描述】:

尝试建立回归模型,但遇到了一个我无法解决的问题。 已经用谷歌搜索并阅读了有关它的所有内容,但没有任何效果。有这个数据框:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 334195 entries, 0 to 334194
Data columns (total 12 columns):
type         334195 non-null int64
zipcode      334195 non-null int64
sqft         334195 non-null float64
lotsize      334195 non-null float64
beds         334195 non-null float64
baths        334195 non-null float64
year         334195 non-null float64
s_num        334195 non-null int64
s_rate       334195 non-null float64
s_dist       334195 non-null float64
crimes       334195 non-null float64
target       334195 non-null float64
dtypes: float64(9), int64(3)

尝试这样做:

data = pd.read_csv('data_prep_sale')
df = pd.DataFrame(data)

x = df.drop(['target'],axis=1)
y = pd.Series(df['target'])

trimmed_feature_names = []
for i in range(x.shape[1]):
    correlation = np.corrcoef(x.iloc[:,i],y)[0,1]
    if abs(correlation) > 0.5:
        feature_name = x.columns[i]
        print(feature_name, correlation)
        trimmed_feature_names.append(feature_name)

并继续为所有 x 获取此矩阵:

array([[ 1., nan],
       [nan, nan]])

这是一个数据样本:

type	zipcode	sqft	lotsize	beds	baths	year	s_num	s_rate	s_dist	crimes	target
4	28387	2900.0	0.0	4.0	3.5	2019.0	8	5.20	5.54	6.0	144.137931
4	99216	1947.0	5828.0	3.0	3.0	2019.0	3	4.00	1.33	3.1	159.219312
3	90049	3000.0	8626.0	3.0	2.0	1967.0	3	6.67	1.96	4.4	965.000000
1	75205	6457.0	8220.0	5.0	8.0	2006.0	4	9.25	0.75	4.6	370.915286

Link to the complete data file

请帮帮我!需要任何想法!

【问题讨论】:

  • 为了能够重现此问题,我们需要您与我们分享data_prep_sale.csv 文件吗?
  • 已添加问题的链接(不确定如何在此处正确共享文件)。
  • 你不能上传文件到 SO,我就是这个意思
  • 对不起,我是新来的。 SO是什么?
  • SO: 代表 Stack Overflow... 这完全没问题。我们在这里为您提供帮助:)

标签: python numpy correlation


【解决方案1】:

根据上传的文件,target 列中有一些inf 值...例如第 43、283、372 行...等。因此,要解决此问题,您必须删除所有 inf 行。此外,还有一种更好的方法可以找到target 与其他特征之间的相关性。两者都显示在以下代码中:

import numpy as np
import pandas as pd

data = pd.read_csv('data_prep_sale.csv')
df = pd.DataFrame(data)

# remove any (inf, -inf, nan) values
df = df.replace([np.inf, -np.inf], np.nan).dropna()

# find the correlation between target other features
print(df.corr()["target"])

从相关输出中可以看出,所有值都远低于0.5

【讨论】:

    猜你喜欢
    • 2017-05-10
    • 2010-11-28
    • 1970-01-01
    • 2015-05-20
    • 2021-06-25
    • 2020-01-07
    • 2011-10-23
    • 2017-03-26
    • 2021-06-18
    相关资源
    最近更新 更多