【吴恩达课后编程作业】Course 2 第三周作业 的预测模块

在 model()中加以下两行代码,文件会保存在当前代码的目录

saver = tf.compat.v1.train.Saver()
saver.save(sess, 'model/my-model', global_step=epoch+1)
def model(X_train,Y_train,
          learning_rate=0.0001,num_epoches=1500,minibatch_size=32,
          print_cost=True,is_plot=True):
    """
    实现一个三层的Tensorflow神经网络:LINEAR->RELU->LINEAR->RELU->LINEAR->SOFTMAX

    参数:
        X_train - 训练集,维度为(输入大小(输入节点数量) = 12288, 样本数量 = 1080)
        Y_train - 训练集分类数量,维度为(输出大小(输出节点数量) = 6, 样本数量 = 1080)
        X_test - 测试集,维度为(输入大小(输入节点数量) = 12288, 样本数量 = 120)
        Y_test - 测试集分类数量,维度为(输出大小(输出节点数量) = 6, 样本数量 = 120)
        learning_rate - 学习速率
        num_epochs - 整个训练集的遍历次数
        mini_batch_size - 每个小批量数据集的大小
        print_cost - 是否打印成本,每100代打印一次
        is_plot - 是否绘制曲线图
    
    返回:
        parameters - 学习后的参数

    """
    ops.reset_default_graph()   #能够重新运行模型而不覆盖tf变量
    tf.compat.v1.set_random_seed(1)
    seed = 3
    (n_x, m) = X_train.shape    #获取输入节点数量和样本数
    n_y = Y_train.shape[0]      #获取输出节点数量
    costs = []                  #成本集

    #给X和Y创建placeholder
    X,Y = create_placeholders(n_x,n_y)

    #初始化参数
    parameters = initialize_parameters()

    #前向传播
    Z3 = forward_propagation(X,parameters)

    #计算成本
    cost = compute_cost(Z3,Y)

    #反向传播,使用Adam优化
    optimizer = tf.compat.v1.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)

    #初始化所有变量
    init = tf.global_variables_initializer()

    #保存模型
    saver = tf.compat.v1.train.Saver()
    
    #开始会话并计算
    with tf.compat.v1.Session() as sess:
        #初始化
        sess.run(init)

        #正常训练的循环
        for epoch in range(num_epoches):

            epoch_cost = 0  #每代的成本
            num_minibatches = int(m / minibatch_size)
            seed = seed + 1
            minibatches = tf_utils.random_mini_batches(X_train,Y_train,minibatch_size,seed)

            for minibatch in minibatches:

                #选择一个minibatch
                (minibatch_X,minibatch_Y) = minibatch

                #数据已经准备好了,开始运行session
                _,minibatch_cost = sess.run([optimizer,cost],feed_dict={X:minibatch_X,Y:minibatch_Y})

                #计算这个minibatch在这一代中所占的误差
                epoch_cost = epoch_cost + minibatch_cost / num_minibatches
                
            #记录并打印成本
            #记录成本
            if (epoch+1) % 5 == 0:
                costs.append(epoch_cost)
                #是否打印:
                if print_cost and (epoch+1) % 100 == 0:
                    print("epoch = " + str(epoch+1) + "    epoch_cost = " + str(epoch_cost))
                    saver.save(sess, 'model/my-model', global_step=epoch+1)
        
        #是否绘制图谱
        if is_plot:
            plt.plot(np.squeeze(costs))
            plt.ylabel('cost')
            plt.xlabel('iterations (per tens)')
            plt.title("Learning rate =" + str(learning_rate))
            plt.show()

        #保存学习后的参数
        parameters = sess.run(parameters)
        print("参数已经保存到session.")

        #计算当前的预测结果
        correct_prediction = tf.math.equal(tf.math.argmax(Z3),tf.math.argmax(Y))

        #计算准确率
        accuracy = tf.math.reduce_mean(tf.cast(correct_prediction,"float"))

        print("训练集的准确率: ",accuracy.eval({X:X_train,Y:Y_train}))
        #print("测试集的准确率:", accuracy.eval({X:X_test,Y:Y_test}))
        
        #return parameters

预测模块

import tf_utils
import tensorflow as tf
X_train_orig , Y_train_orig , X_test_orig , Y_test_orig , classes = tf_utils.load_dataset()


#每一列就是一个样本
X_test_flatten = X_test_orig.reshape(X_test_orig.shape[0],-1).T

#归一化数据
X_test = tf.cast(X_test_flatten / 255,tf.float32)

#转换为独热矩阵
Y_test = tf_utils.convert_to_one_hot(Y_test_orig,6)

print("测试集样本数 = " + str(X_test.shape[1]))
print("X_test.shape: " + str(X_test.shape))
print("Y_test.shape: " + str(Y_test.shape))

def forward_propagation(X,parameters):
    """
    实现一个模型的前向传播,模型结构为LINEAR->RELU->LINEAR->RELU->LINEAR->SOFTMAX

    参数:
        X - 输入数据的占位符,维度为(输入节点数量,样本数量)
        parameters - 包含了W和b参数的字典

    返回:
        Z3 - 最后一个LINEAR节点的输出

    """

    W1 = parameters['W1']
    b1 = parameters['b1']
    W2 = parameters['W2']
    b2 = parameters['b2']
    W3 = parameters['W3']
    b3 = parameters['b3']

    Z1 = tf.math.add(tf.linalg.matmul(W1,X),b1)
    A1 = tf.nn.relu(Z1)
    Z2 = tf.math.add(tf.linalg.matmul(W2,A1),b2)
    A2 = tf.nn.relu(Z2)
    Z3 = tf.math.add(tf.linalg.matmul(W3,A2),b3)

    return Z3


def load_model(filepath):
    with tf.compat.v1.Session() as sess:
        #import_meta_graph填的名字是meta文件名
        saver =tf.compat.v1.train.import_meta_graph(filepath)
        # 检查checkpoint,所以只填到checkpoint所在的路径下即可,不需要填checkpoint
        saver.restore(sess, tf.train.latest_checkpoint("model"))
        #print(sess.run('W1:0').shape)
        #print(sess.run('W2:0').shape)
        W1 = sess.run('W1:0')
        b1 = sess.run('b1:0')
        W2 = sess.run('W2:0')
        b2 = sess.run('b2:0')
        W3 = sess.run('W3:0')
        b3 = sess.run('b3:0')

        parameters = {'W1':W1,
                      'b1':b1,
                      'W2':W2,
                      'b2':b2,
                      'W3':W3,
                      'b3':b3}
        
        return parameters
            

parameters = load_model('model/my-model-1500.meta');
##print(parameters['W1'].shape)
##print(parameters['b1'].shape)
##print(parameters['W2'].shape)
##print(parameters['b2'].shape)
##print(parameters['W3'].shape)
##print(parameters['b3'].shape)

#前向计算
Z3 = forward_propagation(X_test,parameters)


#计算当前预测结果
correct_prediction = tf.math.equal(tf.math.argmax(Z3),tf.math.argmax(Y_test))

#计算准确率
accuracy = tf.math.reduce_mean(tf.cast(correct_prediction,"float"))

                            
with tf.compat.v1.Session() as sess:
    print("测试集的准确率: " + str(sess.run(accuracy)))
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值