#!/usr/bin/env python
# 匯入mnist資料庫
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
import tensorflow as tf
import os
# 定義輸入變數
x = tf.placeholder(tf.float32, [None, 784])
# 定義引數
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
# 定義激勵函式
y = tf.nn.softmax(tf.matmul(x, W) + b)
# 定義輸出變數
y_ = tf.placeholder(tf.float32, [None, 10])
# 定義成本函式
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
# 定義優化函式
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
# 初始化變數
init = tf.global_variables_initializer()
# 定義會話
sess = tf.Session()
# 執行初始化
sess.run(init)
# 定義模型儲存物件
saver = tf.train.Saver()
tf.add_to_collection('x', x)
tf.add_to_collection('y', y)
# 迴圈訓練1000次
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_:batch_ys})
print("訓練完成!")
# 建立模型儲存目錄
model_dir = "mnist_1"
model_name = "ckp"
if not os.path.exists(model_dir):
os.mkdir(model_dir)
# 儲存模型
saver.save(sess, os.path.join(model_dir, model_name))
print("儲存模型成功!")