1

SVM 分類子は、フィーチャが疎なマトリックスで表されている場合は値エラーをスローしますが、フィーチャが密なマトリックスで表されている場合はエラーになりません。

機能セットで One Hot Encoding を実行し、エンコードされた出力を機能の新しいリストに追加するコードがあります。One Hot Encoding の出力が .toarray() を使用して密な配列に変換されると、私の SVM 分類子は正常に動作します。

ただし、数千のデータポイントがあり、コンピューターのメモリがすぐに不足するため、密な配列を使用することは理想的ではありません。したがって、スパース配列が必要です。以下のコードから .toarray() を単純に削除すると、 enc.transform(features) の出力はスパース行列を出力します。ただし、SVM 分類器を実行すると、次のエラーが発生します。

ValueError: 配列要素をシーケンスで設定しています。

SVM がデータを適合させようとすると、何かが失敗しているように見えます。Sklearn SVM はスパース ベクトルを受け入れるため、何が問題なのかわかりません。

# Perform One Hot Encoding
transformedFeatureList = []
for features in featureList:
    features = np.asarray(features)
    features = features.reshape(1, -1)      
    transformedFeatures = enc.transform(features).toarray() <---Without toarray() the Value Error happens
    transformedFeatureList.append(transformedFeatures)  
featureList = transformedFeatureList

# Seperate data into training and testing set
trainingSet = [[], []]
testSet = [[], []]
if len(featureList) == len(classList):
    for index in range(len(featureList)):
        if random.randint(1, 10) <= 7:
            trainingSet[0].append(featureList[index])
            trainingSet[1].append(classList[index])
        else:
            testSet[0].append(featureList[index])
            testSet[1].append(classList[index])

# Train model and attempt classification
from sklearn import svm
X = trainingSet[0]
y = trainingSet[1]
clf = svm.SVC()
clf.fit(X, y) 

results = {}
for iclass in set(classList):
    results[iclass] = [0, 0]            # index 0 = correct, index 1 = incorrect
if len(testSet[0]) == len(testSet[1]):
    for index in range(len(testSet[0])):
        features = testSet[0][index]
        iclass = testSet[1][index]
        predictedClass = clf.predict([features])[0]

        if predictedClass == iclass:
            results[iclass][0] += 1
        else:
            results[iclass][1] += 1
4

1 に答える 1

0

ValueError の原因を見つけました。本質的に、私の「疎行列」は非常に合法的ではありませんでした。どうやら、次のように表される密な行列です。

dense = [[0,0], [1,1], [2,2]]

は正当な行列表現ですが、疎行列を次のように表します。

sparse = [*sparse1, *sparse2, * sparse3]

where *sparse represents the output of a function that returns a sparse matrix

は正当な行列表現ではありません。これは単なる行列のリストです。

私が見つけた解決策は、scipy.sparse.vstack を使用して疎行を 1 つずつ追加し、目的の総疎行列を作成することです。

于 2016-11-15T00:39:23.297 に答える