3

リスト内のすべてのアイテム間のピアソン相関相関を計算しようとしています。data[0]とdata[1]、data[0]とdata[2]、data[1]とdata[2]の相関関係を取得しようとしています。

import scipy
from scipy import stats

data = [[1, 2, 4], [9, 5, 1], [8, 3, 3]]

def pearson(x, y):
    series1 = data[x]
    series2 = data[y]
    if x != y:
        return scipy.stats.pearsonr(series1, series2)

h = [pearson(x,y) for x,y in range(0, len(data))]

これにより、のエラーが返さTypeError: 'int' object is not iterablehます。誰かがここでエラーを説明できますか?ありがとう。

4

3 に答える 3

3

rangeは、タプルを返すように使用しようとしているときに、int値のリストを返します。代わりにitertools.combinationsを試してください。

import scipy
from scipy import stats
from itertools import combinations

data = [[1, 2, 4], [9, 5, 1], [8, 3, 3]]

def pearson(x, y):
    series1 = data[x]
    series2 = data[y]
    if x != y:
        return scipy.stats.pearsonr(series1, series2)

h = [pearson(x,y) for x,y in combinations(len(data), 2)]

または@Mariusが提案したように:

h = [stats.pearsonr(data[x], data[y]) for x,y in combinations(len(data), 2)]
于 2012-11-07T03:20:01.837 に答える
0

range()関数は、反復ごとにintのみを提供し、値のペアにintを割り当てることはできません。

その範囲内のintの可能性のすべての可能なペアを通過したい場合は、試すことができます

import itertools

h = [pearson(x,y) for x,y in itertools.product(range(len(data)), repeat=2)]

これにより、指定された範囲内のすべての可能性が2つの要素のタプルに結合されます

定義した関数を使用すると、x==yの場合はNone値になることに注意してください。使用できる問題を修正するには:

import itertools

h = [pearson(x,y) for x,y in itertools.permutations(range(len(data)), 2)]
于 2012-11-07T03:36:20.130 に答える
0

使ってみませんかnumpy.corrcoef

import numpy as np
data = [[1, 2, 4], [9, 5, 1], [8, 3, 3]]  

結果:

>>> np.corrcoef(data)
array([[ 1.        , -0.98198051, -0.75592895],
       [-0.98198051,  1.        ,  0.8660254 ],
       [-0.75592895,  0.8660254 ,  1.        ]])
于 2012-11-07T03:32:28.503 に答える