2

これから説明する問題で数日前から立ち往生しています。私は深層学習に関する Daniel Nouri のチュートリアルに従っています: http://danielnouri.org/notes/category/deep-learning/そして彼の例を分類データセットに適応させようとしました。ここでの問題は、データセットを回帰問題として扱うと正しく機能しますが、分類を実行しようとすると失敗することです。再現可能な例を2つ書いてみました。

1) 回帰 (うまくいきます)

import lasagne
from sklearn import datasets
import numpy as np
from lasagne import layers
from lasagne.updates import nesterov_momentum
from nolearn.lasagne import NeuralNet
from sklearn.preprocessing import StandardScaler

iris = datasets.load_iris()
X = iris.data[iris.target<2]  # we only take the first two features.
Y = iris.target[iris.target<2]
stdscaler = StandardScaler(copy=True, with_mean=True, with_std=True)
X = stdscaler.fit_transform(X).astype(np.float32)
y = np.asmatrix((Y-0.5)*2).T.astype(np.float32)

print X.shape, type(X)
print y.shape, type(y)

net1 = NeuralNet(
    layers=[  # three layers: one hidden layer
        ('input', layers.InputLayer),
        ('hidden', layers.DenseLayer),
        ('output', layers.DenseLayer),
        ],
    # layer parameters:
    input_shape=(None, 4),  # 96x96 input pixels per batch
    hidden_num_units=10,  # number of units in hidden layer
    output_nonlinearity=None,  # output layer uses identity function
    output_num_units=1,  # 1 target value

    # optimization method:
    update=nesterov_momentum,
    update_learning_rate=0.01,
    update_momentum=0.9,

    regression=True,  # flag to indicate we're dealing with regression problem
    max_epochs=400,  # we want to train this many epochs
    verbose=1,
    )

net1.fit(X, y)

2)分類(行列の次元のエラーが発生します。下に貼り付けます)

import lasagne
from sklearn import datasets
import numpy as np
from lasagne import layers
from lasagne.nonlinearities import softmax
from lasagne.updates import nesterov_momentum
from nolearn.lasagne import NeuralNet
from sklearn.preprocessing import StandardScaler

iris = datasets.load_iris()
X = iris.data[iris.target<2]  # we only take the first two features.
Y = iris.target[iris.target<2]
stdscaler = StandardScaler(copy=True, with_mean=True, with_std=True)
X = stdscaler.fit_transform(X).astype(np.float32)
y = np.asmatrix((Y-0.5)*2).T.astype(np.int32)

print X.shape, type(X)
print y.shape, type(y)

net1 = NeuralNet(
    layers=[  # three layers: one hidden layer
        ('input', layers.InputLayer),
        ('hidden', layers.DenseLayer),
        ('output', layers.DenseLayer),
        ],
    # layer parameters:
    input_shape=(None, 4),  # 96x96 input pixels per batch
    hidden_num_units=10,  # number of units in hidden layer
    output_nonlinearity=softmax,  # output layer uses identity function
    output_num_units=1,  # 1 target value

    # optimization method:
    update=nesterov_momentum,
    update_learning_rate=0.01,
    update_momentum=0.9,

    regression=False,  # flag to indicate we're dealing with classification problem
    max_epochs=400,  # we want to train this many epochs
    verbose=1,
    )

net1.fit(X, y)

コード 2 で得られる失敗した出力。

(100, 4) <type 'numpy.ndarray'>
(100, 1) <type 'numpy.ndarray'>
  input                 (None, 4)               produces       4 outputs
  hidden                (None, 10)              produces      10 outputs
  output                (None, 1)               produces       1 outputs
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-13-184a45e5abaa> in <module>()
     40     )
     41 
---> 42 net1.fit(X, y)

/Users/ivanvallesperez/anaconda/lib/python2.7/site-packages/nolearn/lasagne/base.pyc in fit(self, X, y)
    291 
    292         try:
--> 293             self.train_loop(X, y)
    294         except KeyboardInterrupt:
    295             pass

/Users/ivanvallesperez/anaconda/lib/python2.7/site-packages/nolearn/lasagne/base.pyc in train_loop(self, X, y)
    298     def train_loop(self, X, y):
    299         X_train, X_valid, y_train, y_valid = self.train_test_split(
--> 300             X, y, self.eval_size)
    301 
    302         on_epoch_finished = self.on_epoch_finished

/Users/ivanvallesperez/anaconda/lib/python2.7/site-packages/nolearn/lasagne/base.pyc in train_test_split(self, X, y, eval_size)
    399                 kf = KFold(y.shape[0], round(1. / eval_size))
    400             else:
--> 401                 kf = StratifiedKFold(y, round(1. / eval_size))
    402 
    403             train_indices, valid_indices = next(iter(kf))

/Users/ivanvallesperez/anaconda/lib/python2.7/site-packages/sklearn/cross_validation.pyc in __init__(self, y, n_folds, shuffle, random_state)
    531         for test_fold_idx, per_label_splits in enumerate(zip(*per_label_cvs)):
    532             for label, (_, test_split) in zip(unique_labels, per_label_splits):
--> 533                 label_test_folds = test_folds[y == label]
    534                 # the test split can be too big because we used
    535                 # KFold(max(c, self.n_folds), self.n_folds) instead of

IndexError: too many indices for array

ここで何が起こっているのですか?私は何か悪いことをしていますか?私はすべてを試しましたが、何が起こっているのか理解できません。

今日、次のコマンドを使用してラザニアと依存関係を更新したことに注意してください。pip install -r https://raw.githubusercontent.com/dnouri/kfkd-tutorial/master/requirements.txt

前もって感謝します

編集

その後の変更を実行することで機能するようになりましたが、まだ疑問があります。

  • Y を 0/1 の値を持つ 1 次元ベクトルとして次のように定義しましたy = Y.astype(np.int32)

  • output_num_units=1パラメータをに変更するoutput_num_units=2必要がありましたが、2 項分類の問題を扱っているため、この多層パーセプトロンの出力ニューロンは 2 つではなく 1 つだけである必要があると考えているため、それを理解しているかどうかはよくわかりません。違う?

また、コスト関数を ROC-AUC に変更しようとしました。objective_loss_functionデフォルトで定義されているパラメーターがあることは知っていobjective_loss_function=lasagne.objectives.categorical_crossentropyますが、ROC AUC をカテゴリークロスエントロピーの代わりにコスト関数として使用するにはどうすればよいですか?

ありがとう

4

1 に答える 1

2

分類を行う場合、nolearn では、output_num_unitsいくつのクラスがあるかを示します。1 つの出力ユニットのみで 2 つのクラス分類を実装することは可能ですが、nolearn ではそのような方法で特殊化されていません。たとえば、[1] から次のようになります。

    if not self.regression:
        predict = predict_proba.argmax(axis=1)

クラスの数に関係なく、予測が常に argmax であることに注意してください (2 つのクラスの分類には 1 つではなく 2 つの出力があることを意味します)。

したがって、変更は正しいです:output_num_unitsは、2 つある場合でも、常にクラスの数である必要Yがあり、たとえば、ベクトルに形状のあるカテゴリごとのビット。(num_samples)(num_samples, 1)(num_samples, num_categories)

他の質問に答えると、ラザニアには目的がないように見えるROC-AUCので、それを実装する必要があります。たとえば、Lasagne では、リストや ndarray ではなく、theano テンソルを引数として受け取る目的関数が必要なため、scikit-learn からの実装を使用できないことに注意してください。目的関数が Lasagne でどのように実装されているかを確認するには、既存の目的関数を参照してください [2]。それらの多くは theano 内のものを参照しており、[3] でそれらの実装を見ることができます (binary_crossentropy目的関数の良い例である に自動スクロールします)。

[1] https://github.com/dnouri/nolearn/blob/master/nolearn/lasagne/base.py#L414

[2] https://github.com/Lasagne/Lasagne/blob/master/lasagne/objectives.py

[3] https://github.com/Theano/Theano/blob/master/theano/tensor/nnet/nnet.py#L1809

于 2015-11-22T05:29:56.420 に答える