0

我想从 iris 数据集中得到协方差,https://www.kaggle.com/jchen2186/machine-learning-with-iris-dataset/data

我正在使用 numpy,函数 -> np.cov(iris)

with open("Iris.csv") as iris:
    reader = csv.reader(iris)
    data = []
    next(reader)
    for row in reader:
        data.append(row)

for i in data:
    i.pop(0)
    i.pop(4)

iris = np.array(data)
np.cov(iris)

我得到这个错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-bfb836354075> in <module>
----> 1 np.cov(iris)

D:\Anaconda\lib\site-packages\numpy\lib\function_base.py in cov(m, y, rowvar, bias, ddof, fweights, aweights)
   2300             w *= aweights
   2301 
-> 2302     avg, w_sum = average(X, axis=1, weights=w, returned=True)
   2303     w_sum = w_sum[0]
   2304 

D:\Anaconda\lib\site-packages\numpy\lib\function_base.py in average(a, axis, weights, returned)
    354 
    355     if weights is None:
--> 356         avg = a.mean(axis)
    357         scl = avg.dtype.type(a.size/avg.size)
    358     else:

D:\Anaconda\lib\site-packages\numpy\core\_methods.py in _mean(a, axis, dtype, out, keepdims)
     73             is_float16_result = True
     74 
---> 75     ret = umr_sum(arr, axis, dtype, out, keepdims)
     76     if isinstance(ret, mu.ndarray):
     77         ret = um.true_divide(

TypeError: cannot perform reduce with flexible type

没看懂什么意思。。

4

1 回答 1

0

所以,如果你想修改你的代码,你可以通过阅读Iris.csvwithpandas.read_csv函数来尝试。然后选择您选择的适当列。

但是,这里有一些命令可以简化这项任务。他们使用scikit-learnnumpy加载 iris 数据集,获取 X 和 y 并获取协方差矩阵:

from sklearn.datasets import load_iris
import numpy as np

data = load_iris()
X = data['data']
y = data['target']

np.cov(X)

希望这有帮助。

于 2019-04-04T07:17:29.273 回答