```
Пример с использованием Keras и TensorFlow
Подготовка данных
```python
import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras.utils import to_categorical
# Загрузка данных MNIST
(X_train, y_train), (X_test, y_test) = mnist.load_data()
X_train = X_train.reshape((X_train.shape[0], 28, 28, 1)).astype('float32') / 255
X_test = X_test.reshape((X_test.shape[0], 28, 28, 1)).astype('float32') / 255
# Преобразование меток в категориальный формат
y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)
```
Построение моделей
```python
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
def create_model():
model = Sequential([
Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
MaxPooling2D((2, 2)),
Conv2D(64, (3, 3), activation='relu'),
MaxPooling2D((2, 2)),
Flatten(),
Dense(64, activation='relu'),
Dense(10, activation='softmax')
])
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
return model
# Создание и обучение нескольких моделей
models = [create_model() for _ in range(3)]
for model in models:
model.fit(X_train, y_train, epochs=5, batch_size=64, validation_split=0.1)
```
Ансамблирование моделей
```python
import numpy as np
def ensemble_predict(models, X):
predictions = [model.predict(X) for model in models]
return np.mean(predictions, axis=0)
# Прогнозирование и оценка точности
y_pred = ensemble_predict(models, X_test)
y_pred_classes = np.argmax(y_pred, axis=1)
y_test_classes = np.argmax(y_test, axis=1)
accuracy = np.mean(y_pred_classes == y_test_classes)
print(f'Точность ансамблевой модели: {accuracy:.4f}')
```
Пояснение: