Существует другой способ делать «случайные» упорядоченные числа с LFSR, взгляните на:
http://en.wikipedia.org/wiki/Linear_feedback_shift_register
с помощью этой методики вы можете получить упорядоченное случайное число по индексу и убедиться, что значения не дублируются.
Но это не истинные случайные числа, потому что случайная генерация детерминирована [/. g4]
Но в зависимости от вашего случая вы можете использовать эту технику, уменьшая количество обработки при генерации случайных чисел при использовании тасования.
Здесь алгоритм LFSR в java (я взял его где-то, я не remeber):
public final class LFSR {
private static final int M = 15;
// hard-coded for 15-bits
private static final int[] TAPS = {14, 15};
private final boolean[] bits = new boolean[M + 1];
public LFSR() {
this((int)System.currentTimeMillis());
}
public LFSR(int seed) {
for(int i = 0; i < M; i++) {
bits[i] = (((1 << i) & seed) >>> i) == 1;
}
}
/* generate a random int uniformly on the interval [-2^31 + 1, 2^31 - 1] */
public short nextShort() {
//printBits();
// calculate the integer value from the registers
short next = 0;
for(int i = 0; i < M; i++) {
next |= (bits[i] ? 1 : 0) << i;
}
// allow for zero without allowing for -2^31
if (next < 0) next++;
// calculate the last register from all the preceding
bits[M] = false;
for(int i = 0; i < TAPS.length; i++) {
bits[M] ^= bits[M - TAPS[i]];
}
// shift all the registers
for(int i = 0; i < M; i++) {
bits[i] = bits[i + 1];
}
return next;
}
/** returns random double uniformly over [0, 1) */
public double nextDouble() {
return ((nextShort() / (Integer.MAX_VALUE + 1.0)) + 1.0) / 2.0;
}
/** returns random boolean */
public boolean nextBoolean() {
return nextShort() >= 0;
}
public void printBits() {
System.out.print(bits[M] ? 1 : 0);
System.out.print(" -> ");
for(int i = M - 1; i >= 0; i--) {
System.out.print(bits[i] ? 1 : 0);
}
System.out.println();
}
public static void main(String[] args) {
LFSR rng = new LFSR();
Vector vec = new Vector();
for(int i = 0; i <= 32766; i++) {
short next = rng.nextShort();
// just testing/asserting to make
// sure the number doesn't repeat on a given list
if (vec.contains(next))
throw new RuntimeException("Index repeat: " + i);
vec.add(next);
System.out.println(next);
}
}
}
Вы не тренируете ансамбль ; Вы просто тренируете список из нескольких моделей, не комбинируя их никоим образом, что определенно не является ансамблем.
Учитывая это, ошибка, которую вы получаете, не является неожиданной, так как confusionMatrix
ожидает одно предсказание (что было бы в случае, если у вас действительно был ансамбль), а не многократное.
Сохранение вашего списка для простоты только для ваших первых 4 моделей и незначительное изменение вашего определения fits_predicts
, чтобы оно давало фрейм данных, то есть:
models <- c("glm", "lda", "naive_bayes", "svmLinear")
fits_predicts <- as.data.frame( sapply(fits, function(fits){ predict(fits,mnist_27$test)
}))
# rest of your code as-is
, вот как вы можете получить путаницу Матрицы для каждой из ваших моделей :
cm <- lapply(fits_predicts, function(fits_predicts){confusionMatrix(fits_predicts,reference=(mnist_27$test$y))
})
, что дает
> cm
$glm
Confusion Matrix and Statistics
Reference
Prediction 2 7
2 82 26
7 24 68
Accuracy : 0.75
95% CI : (0.684, 0.8084)
No Information Rate : 0.53
P-Value [Acc > NIR] : 1.266e-10
Kappa : 0.4976
Mcnemar's Test P-Value : 0.8875
Sensitivity : 0.7736
Specificity : 0.7234
Pos Pred Value : 0.7593
Neg Pred Value : 0.7391
Prevalence : 0.5300
Detection Rate : 0.4100
Detection Prevalence : 0.5400
Balanced Accuracy : 0.7485
'Positive' Class : 2
$lda
Confusion Matrix and Statistics
Reference
Prediction 2 7
2 82 26
7 24 68
Accuracy : 0.75
95% CI : (0.684, 0.8084)
No Information Rate : 0.53
P-Value [Acc > NIR] : 1.266e-10
Kappa : 0.4976
Mcnemar's Test P-Value : 0.8875
Sensitivity : 0.7736
Specificity : 0.7234
Pos Pred Value : 0.7593
Neg Pred Value : 0.7391
Prevalence : 0.5300
Detection Rate : 0.4100
Detection Prevalence : 0.5400
Balanced Accuracy : 0.7485
'Positive' Class : 2
$naive_bayes
Confusion Matrix and Statistics
Reference
Prediction 2 7
2 88 23
7 18 71
Accuracy : 0.795
95% CI : (0.7323, 0.8487)
No Information Rate : 0.53
P-Value [Acc > NIR] : 5.821e-15
Kappa : 0.5873
Mcnemar's Test P-Value : 0.5322
Sensitivity : 0.8302
Specificity : 0.7553
Pos Pred Value : 0.7928
Neg Pred Value : 0.7978
Prevalence : 0.5300
Detection Rate : 0.4400
Detection Prevalence : 0.5550
Balanced Accuracy : 0.7928
'Positive' Class : 2
$svmLinear
Confusion Matrix and Statistics
Reference
Prediction 2 7
2 81 24
7 25 70
Accuracy : 0.755
95% CI : (0.6894, 0.8129)
No Information Rate : 0.53
P-Value [Acc > NIR] : 4.656e-11
Kappa : 0.5085
Mcnemar's Test P-Value : 1
Sensitivity : 0.7642
Specificity : 0.7447
Pos Pred Value : 0.7714
Neg Pred Value : 0.7368
Prevalence : 0.5300
Detection Rate : 0.4050
Detection Prevalence : 0.5250
Balanced Accuracy : 0.7544
'Positive' Class : 2
И вы также можете получить доступ к отдельным матрицам путаницы для модели, например для lda
:
> cm['lda']
$lda
Confusion Matrix and Statistics
Reference
Prediction 2 7
2 82 26
7 24 68
Accuracy : 0.75
95% CI : (0.684, 0.8084)
No Information Rate : 0.53
P-Value [Acc > NIR] : 1.266e-10
Kappa : 0.4976
Mcnemar's Test P-Value : 0.8875
Sensitivity : 0.7736
Specificity : 0.7234
Pos Pred Value : 0.7593
Neg Pred Value : 0.7391
Prevalence : 0.5300
Detection Rate : 0.4100
Detection Prevalence : 0.5400
Balanced Accuracy : 0.7485
'Positive' Class : 2