0

ここでワインデータセットを分類しようとしました- http://archive.ics.uci.edu/ml/datasets/Wine+Quality ロジスティック回帰を使用して (メソッド ='bfgs' および l1 ノルムを使用)、特異値行列をキャッチしましたerror(raise LinAlgError('Singular matrix'), フルランクにもかかわらず [np.linalg.matrix_rank(data[train_cols].values) を使用してテストしました] .

これが、一部の機能が他の機能の線形結合である可能性があるという結論に達した方法です。これに向けて、グリッド検索/LinearSVC の使用を実験しました。コードと data-set とともに、以下のエラーが表示されます。

x_train_new[0] と x_train の行を比較すると、6/7 の機能のみが実際に「独立」していることがわかります (したがって、どの列が冗長であるかを取得できます)。

    # Train & test DATA CREATION
    from sklearn.svm import LinearSVC
    import numpy, random
    import pandas as pd
    df = pd.read_csv("https://github.com/ekta1007/Predicting_wine_quality/blob/master/wine_red_dataset.csv")
#,skiprows=0, sep=',')


    df=df.dropna(axis=1,how='any') # also tried how='all' - still get NaN errors as below
    header=list(df.columns.values) # or df.columns
    X = df[df.columns - [header[-1]]] # header[-1] = ['quality'] - this is to make the code genric enough
    Y = df[header[-1]] # df['quality']
    rows = random.sample(df.index, int(len(df)*0.7)) # indexing the rows that will be picked in the train set
    x_train, y_train = X.ix[rows],Y.ix[rows] # Fetching the data frame using indexes
    x_test,y_test  = X.drop(rows),Y.drop(rows)


# Training the classifier using C-Support Vector Classification.
clf = LinearSVC(C=0.01, penalty="l1", dual=False) #,tol=0.0001,fit_intercept=True, intercept_scaling=1)
clf.fit(x_train, y_train)
x_train_new = clf.fit_transform(x_train, y_train)
#print x_train_new #works
clf.predict(x_test) # does NOT work and gives NaN errors for some x_tests


clf.score(x_test, y_test) # Does NOT work
clf.coef_ # Works, but I am not sure, if this is OK, given huge NaN's - or does the coef's get impacted ?

clf.predict(x_train)
552   NaN
209   NaN
427   NaN
288   NaN
175   NaN
427   NaN
748     7
552   NaN
429   NaN
[... and MORE]
Name: quality, Length: 1119

clf.predict(x_test)
76    NaN
287   NaN
420     7
812   NaN
443     7
420     7
430   NaN
373     5
624     5
[..and More]
Name: quality, Length: 480

奇妙なことに、clf.predict(x_train) を実行すると、まだいくつかの NaN が表示されます。何が間違っているのでしょうか?これを使用してモデルをトレーニングした後、これは発生しないはずですよね?

このスレッドによると、csv ファイルに null がないことも確認しました(ただし、「品質」のラベルを 5 および 7 ラベルのみに変更しました (range(3,10) から) How to fix "NaN or infinity" issue for sparse Pythonの行列?

また、x_test と y_test/train のデータ型は次のとおりです...

x_test
<class 'pandas.core.frame.DataFrame'>
Int64Index: 480 entries, 1 to 1596
Data columns:
alcohol                 480  non-null values
chlorides               480  non-null values
citric acid             480  non-null values
density                 480  non-null values
fixed acidity           480  non-null values
free sulfur dioxide     480  non-null values
pH                      480  non-null values
residual sugar          480  non-null values
sulphates               480  non-null values
total sulfur dioxide    480  non-null values
volatile acidity        480  non-null values
dtypes: float64(11)

y_test
1     5
10    5
18    5
21    5
30    5
31    7
36    7
40    5
50    5
52    7
53    5
55    5
57    5
60    5
61    5
[..And MORE]
Name: quality, Length: 480

そして最後に..

clf.score(x_test, y_test)

Traceback (most recent call last):
  File "<pyshell#31>", line 1, in <module>
    clf.score(x_test, y_test)
  File "C:\Python27\lib\site-packages\sklearn\base.py", line 279, in score
    return accuracy_score(y, self.predict(X))
  File "C:\Python27\lib\site-packages\sklearn\metrics\metrics.py", line 742, in accuracy_score
    y_true, y_pred = check_arrays(y_true, y_pred)
  File "C:\Python27\Lib\site-packages\sklearn\utils\validation.py", line 215, in check_arrays
  File "C:\Python27\Lib\site-packages\sklearn\utils\validation.py", line 18, in _assert_all_finite
ValueError: Array contains NaN or infinity.


#I also explicitly checked for NaN's as here -:
for i in df.columns:
    df[i].isnull()

ヒント :私のユース ケースを考慮して、LinearSVC の使用に関する私の思考プロセスが正しいかどうか、または Grid-search を使用する必要があるかどうかについても言及してください。

免責事項: このコードの一部は、StackOverflow およびその他のソースからの同様のコンテキストでの提案に基づいて構築されています。私の実際の使用例は、この方法が私のシナリオに適しているかどうかにアクセスしようとしているだけです。それで全部です。

4

1 に答える 1

2

これはうまくいきました。実際に変更する必要があったのは、 x_test* .values * を残りの pandas Dataframes(x_train, y_train, y_test) と共に使用することだけでした。指摘したように、唯一の理由は pandas df と scikit-learn (numpy 配列を使用) の間の非互換性でした

 #changing your Pandas Dataframe elegantly to work with scikit-learn by transformation to  numpy arrays
>>> type(x_test)
<class 'pandas.core.frame.DataFrame'>
>>> type(x_test.values)
<type 'numpy.ndarray'>

このハックは、この投稿http://python.dzone.com/articles/python-making-scikit-learn-andと @AndreasMueller から来ています - 彼は矛盾を指摘しました。

于 2014-01-28T15:49:55.243 に答える