tensorflow之MNIST手写数据集准确度训练

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

# number 1 to 10 data
mnist = input_data.read_data_sets('MNIST_DATA', one_hot=True)           #如果第一次运行没有数据包将会在网上下载

def add_layer(inputs, in_size, out_size, activation_function=None):
    # add one more layer and return he output of this layer
            Weights = tf.Variable(tf.random_normal([in_size, out_size]))
            biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)
            Wx_plus_b = tf.matmul(inputs, Weights) + biases     #矩阵相乘
            if activation_function is None:
                outputs = Wx_plus_b
            else:
                outputs = activation_function(Wx_plus_b)
            return outputs

def compute_accuracy(v_xs, v_ys):
    global prediction
    y_pre = sess.run(prediction,feed_dict={xs:v_xs})
    correct_prediction = tf.equal(tf.argmax(y_pre, 1), tf.argmax(v_ys,1 ))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    result = sess.run(accuracy, feed_dict={xs: v_xs, ys:v_ys})
    return result

# define placeholder for inputs to network
xs = tf.placeholder(tf.float32, [None, 784])     #[None, 784]None表示任意个例子以及每个例子784大小 28*28
ys = tf.placeholder(tf.float32, [None, 10])


prediction = add_layer(xs, 784, 10, activation_function=tf.nn.softmax)          #此处激励方程一般用作分类

# the error between prediction and real data
cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction),reduction_indices=[1])) #配合上句食用的softmax分类算法效果好,原理难目前可以不理解
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

sess = tf.Session()
# important step
sess.run(tf.initialize_all_variables())

for i in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)       #提取一部分xs和ys的sample,从下载好的数据集提取出来100个,批处理
    sess.run(train_step,feed_dict={xs:batch_xs, ys:batch_ys})
    if i%50==0:
        print(compute_accuracy(mnist.test.images, mnist.test.labels))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,让我们开始吧! 首先,我们需要导入必要的库:TensorFlow 2.0, NumPy和Matplotlib。 ```python import tensorflow as tf import numpy as np import matplotlib.pyplot as plt ``` 接下来,我们将加载MNIST数据集并将其分为训练集、验证集和测试集。由于我们使用的是TensorFlow 2.0,因此可以使用Keras API中的mnist.load_data()函数轻松地加载数据集。 ```python (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data() ``` 我们现在可以将训练集进一步拆分为训练集和验证集。 ```python # 计算训练集和验证集的大小 train_size = int(0.6 * len(x_train)) val_size = int(0.2 * len(x_train)) # 拆分训练集和验证集 x_val = x_train[train_size:train_size+val_size] y_val = y_train[train_size:train_size+val_size] x_train = x_train[:train_size] y_train = y_train[:train_size] ``` 接下来,我们需要对数据进行一些预处理。首先,我们将像素值缩放到0到1的范围内。然后,我们将每个图像转换为一维张量,这样我们可以将它们馈送到我们的神经网络中。 ```python # 将像素值缩放到0到1的范围内 x_train = x_train.astype('float32') / 255.0 x_val = x_val.astype('float32') / 255.0 x_test = x_test.astype('float32') / 255.0 # 将每个图像转换为一维张量 x_train = x_train.reshape((len(x_train), np.prod(x_train.shape[1:]))) x_val = x_val.reshape((len(x_val), np.prod(x_val.shape[1:]))) x_test = x_test.reshape((len(x_test), np.prod(x_test.shape[1:]))) ``` 现在我们可以开始构建我们的神经网络模型。我们将使用Keras API中的Sequential模型,并添加三个密集层。我们还将使用ReLU激活函数和Dropout正则化。 ```python model = tf.keras.models.Sequential([ tf.keras.layers.Dense(512, activation='relu', input_shape=(784,)), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(256, activation='relu'), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(10, activation='softmax') ]) ``` 现在,我们需要编译模型并指定我们的损失函数、优化器和评估指标。 ```python model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy']) ``` 接下来,我们可以训练我们的模型。我们将训练模型20个epoch,并使用验证集来监控模型的性能。 ```python history = model.fit(x_train, y_train, validation_data=(x_val, y_val), epochs=20, batch_size=128) ``` 我们可以使用Matplotlib绘制训练和验证的准确度和损失曲线。 ```python # 绘制训练和验证的准确度曲线 acc = history.history['accuracy'] val_acc = history.history['val_accuracy'] epochs = range(1, len(acc) + 1) plt.plot(epochs, acc, 'bo', label='Training accuracy') plt.plot(epochs, val_acc, 'b', label='Validation accuracy') plt.title('Training and validation accuracy') plt.legend() plt.show() # 绘制训练和验证的损失曲线 loss = history.history['loss'] val_loss = history.history['val_loss'] plt.plot(epochs, loss, 'bo', label='Training loss') plt.plot(epochs, val_loss, 'b', label='Validation loss') plt.title('Training and validation loss') plt.legend() plt.show() ``` 我们可以看到,该模型在训练集和验证集上的准确度都有很好的表现,而且没有出现过拟合的情况。 现在我们可以对测试集进行评估。 ```python test_loss, test_acc = model.evaluate(x_test, y_test) print('Test accuracy:', test_acc) ``` 最后,我们可以保存我们的模型,以便以后使用。我们将使用Keras API中的model.save()函数来保存模型。 ```python model.save('mnist_model.h5') ``` 现在,我们可以使用我们的模型来预测新数据。例如,我们可以手写一个数字,将其转换为一维张量,并使用我们的模型来预测它。 ```python # 加载模型 model = tf.keras.models.load_model('mnist_model.h5') # 手写数字 digit = np.array([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值