写出代码,并写出运行结果
时间: 2024-12-18 08:33:51 浏览: 5
为了完成这个任务,我们需要编写一个完整的Python脚本来实现以下步骤:
1. **加载数据**:使用`scikit-learn`加载MNIST数据集。
2. **预处理数据**:对数据进行归一化处理。
3. **构建BP神经网络**:使用`TensorFlow`或`Keras`构建一个简单的BP神经网络。
4. **训练模型**:使用训练集数据训练模型。
5. **评估模型**:使用测试集数据评估模型性能。
以下是完整的代码示例:
```python
import numpy as np
from sklearn.datasets import fetch_openml
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.utils import to_categorical
# 加载数据集
def load_dataset():
mnist = fetch_openml("mnist_784")
X = mnist['data']
Y = mnist['target']
# 转换数据类型
X = np.array(X, dtype=float)
Y = np.array(Y, dtype=int)
# 归一化处理
mms = MinMaxScaler()
X = mms.fit_transform(X)
# 划分训练集和测试集
x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=0.2, random_state=42)
# 将标签转换为one-hot编码
y_train = to_categorical(y_train, num_classes=10)
y_test = to_categorical(y_test, num_classes=10)
return x_train, x_test, y_train, y_test
# 构建BP神经网络
def build_model(input_shape):
model = Sequential([
Dense(128, activation='relu', input_shape=(input_shape,)),
Dense(64, activation='relu'),
Dense(10, activation='softmax')
])
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
return model
# 主函数
def main():
x_train, x_test, y_train, y_test = load_dataset()
input_shape = x_train.shape[1]
model = build_model(input_shape)
# 训练模型
history = model.fit(x_train, y_train, epochs=10, batch_size=32, validation_data=(x_test, y_test))
# 评估模型
test_loss, test_accuracy = model.evaluate(x_test, y_test)
print(f"Test accuracy: {test_accuracy:.4f}")
if __name__ == "__main__":
main()
```
### 运行结果
假设你在本地环境中运行上述代码,以下是可能的输出结果:
```
Downloading data from https://github.com/scikit-learn/scikit-learn/raw/main/sklearn/datasets/data/mnist_784.csv.gz
15575516/15575516 [==============================] - 0s 0us/step
(48000, 784) (12000, 784)
(48000, 10) (12000, 10)
Epoch 1/10
1500/1500 [==============================] - 5s 3ms/step - loss: 0.2890 - accuracy: 0.9148 - val_loss: 0.1251 - val_accuracy: 0.9625
Epoch 2/10
1500/1500 [==============================] - 4s 3ms/step - loss: 0.1148 - accuracy: 0.9669 - val_loss: 0.0961 - val_accuracy: 0.9708
Epoch 3/10
1500/1500 [==============================] - 4s 3ms/step - loss: 0.0853 - accuracy: 0.9746 - val_loss: 0.0817 - val_accuracy: 0.9742
Epoch 4/10
1500/1500 [==============================] - 4s 3ms/step - loss: 0.0707 - accuracy: 0.9792 - val_loss: 0.0754 - val_accuracy: 0.9775
Epoch 5/10
1500/1500 [==============================] - 4s 3ms/step - loss: 0.0593 - accuracy: 0.9827 - val_loss: 0.0716 - val_accuracy: 0.9792
Epoch 6/10
1500/1500 [==============================] - 4s 3ms/step - loss: 0.0514 - accuracy: 0.9854 - val_loss: 0.0714 - val_accuracy: 0.9783
Epoch 7/10
1500/1500 [==============================] - 4s 3ms/step - loss: 0.0449 - accuracy: 0.9877 - val_loss: 0.0727 - val_accuracy: 0.9775
Epoch 8/10
1500/1500 [==============================] - 4s 3ms/step - loss: 0.0405 - accuracy: 0.9894 - val_loss: 0.0726 - val_accuracy: 0.9775
Epoch 9/10
1500/1500 [==============================] - 4s 3ms/step - loss: 0.0366 - accuracy: 0.9909 - val_loss: 0.0735 - val_accuracy: 0.9783
Epoch 10/10
1500/1500 [==============================] - 4s 3ms/step - loss: 0.0335 - accuracy: 0.9919 - val_loss: 0.0753 - val_accuracy: 0.9775
375/375 [==============================] - 1s 2ms/step - loss: 0.0753 - accuracy: 0.9775
Test accuracy: 0.9775
```
### 解释
- **数据加载和预处理**:我们使用`fetch_openml`加载MNIST数据集,并对其进行归一化处理。
- **模型构建**:使用`Sequential`模型构建一个简单的BP神经网络,包含一个输入层(784个节点)、一个隐藏层(128个节点)和一个输出层(10个节点)。
- **模型训练**:使用训练集数据训练模型,共训练10个epoch。
- **模型评估**:使用测试集数据评估模型的准确率。
希望这段代码和解释对你有所帮助!如果有任何问题,请随时提问。
阅读全文