from tensorflow.examples.tutorials.mnist import input_data改进代码
时间: 2023-11-23 10:04:29 浏览: 111
The `input_data` module has been deprecated since TensorFlow 1.14. You can use the `tf.keras.datasets` module to load the MNIST dataset instead. Here's an example code:
```python
import tensorflow as tf
from tensorflow import keras
# Load MNIST dataset
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
# Normalize pixel values
x_train = x_train / 255.0
x_test = x_test / 255.0
# Define the model
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation='relu'),
keras.layers.Dense(10, activation='softmax')
])
# Compile the model
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# Train the model
model.fit(x_train, y_train, epochs=5)
# Evaluate the model
test_loss, test_acc = model.evaluate(x_test, y_test)
print('Test accuracy:', test_acc)
```
This code loads the MNIST dataset using `keras.datasets.mnist.load_data()`, normalizes the pixel values to the range [0, 1], defines a simple neural network with two dense layers, compiles the model using the Adam optimizer and sparse categorical cross-entropy loss, trains the model for 5 epochs, and evaluates the model on the test set.
阅读全文