почему confusion_matrix отличается, когда я выполняю его снова? - PullRequest
0 голосов
/ 27 мая 2019

Интересно, почему confusion_matrix изменяется, когда я выполняю его во второй раз, и можно ли его избежать. Точнее, я получил [[53445 597] [958 5000]] в первый раз, однако, я получаю [[52556 1486] [805 5153]] при повторном выполнении.

# get the data from dataset and split into training-set and test-set
mnist = fetch_openml('mnist_784')
X, y = mnist['data'], mnist['target']
X_train, X_test, y_train, y_test = X[:60000], X[60000:], y[:60000], y[60000:]
# make the data random
shuffle_index = np.random.permutation(60000)
X_train, y_train = X_train[shuffle_index], y_train[shuffle_index]  
# true for all y_train='2', false for all others
y_train_2 = (y_train == '2')    
y_test_2 = (y_test == '2')

# train the data with a label of T/F depends on whether the data is 2
# I use the random_state as 0, so it will not change, am I right?
sgd_clf = SGDClassifier(random_state=0)
sgd_clf.fit(X_train, y_train_2)

# get the confusion_matrix
y_train_pred = cross_val_predict(sgd_clf, X_train, y_train_2, cv=3)
print('confusion_matrix is', confusion_matrix(y_train_2, y_train_pred))

1 Ответ

1 голос
/ 27 мая 2019

Вы используете разные данные для каждого прогона (shuffle_index) - поэтому нет никаких оснований для того, чтобы прогон ML и результирующая матрица путаницы были в точности одинаковыми - хотя результаты должны быть близкими, если алгоритм выполняет хорошую работу.

Чтобы избавиться от случайности, либо укажите индексы:

shuffle_index = np.arange(60000) #Rather "not_shuffled_index"

, либо используйте то же начальное число:

np.random.seed(1) #Or any number
shuffle_index = np.random.permutation(60000) #Will be the same for a given seed
...