会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132453个问题
JAVA 全系列/第五阶段:JavaWeb开发/Ajax技术详解(旧) 31651楼
JAVA 全系列/第五阶段:JavaWeb开发/Ajax技术详解(旧) 31653楼

flask项目.zip

老师,我用的是pycharm,
代码可以运行,但是结果错误,找不到相应的网页,说我输入错误


Python 全系列/第十阶段:Flask百战电商后台项目/Flask百战电商后台项目 31655楼
Python 全系列/第二阶段:Python 深入与提高/文件处理 31656楼
Python 全系列/第十五阶段:Python 爬虫开发/爬虫反反爬- 31658楼

#手写数字识别

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

#数据加载
mnist = input_data.read_data_sets('data/mnist',one_hot=True)

#手写数字识别的数据集主要包含三个部分:训练集(5.5万行,mnist.train)、测试集(1万行,mnist.test)、验证集(0.5万行,)
#手写数字图片大小是28*28*1的像素的图片(黑白),也就是每个图片有784维的特征描述

train_img = mnist.train.images
train_label = mnist.train.labels
test_img = mnist.test.images
test_label = mnist.test.labels
train_sample_number = mnist.train.num_examples
#print(train_sample_number)#可以通过这个打印下数据集有多少行样本

learn_rate_base = 0.01


#每次迭代的训练样本数据
batch_size = 64
#展示信息的间隔大小
display_step = 1

#输入的样本维度大小信息
input_dim = train_img.shape[1]
#输入的维度大小信息
n_classes = train_label.shape[1]

#模型构建
#1.设置数据输入的占位符
x = tf.placeholder(tf.float32,shape=[None,input_dim],name='x')
y = tf.placeholder(tf.float32,shape=[None,n_classes],name='y')
learn_rate =tf.placeholder(tf.float32,name='learn_rate')

def lean_rate_func(epoch):
    """
    根据给定的迭代批次,更新产生一个学习率的值
    :param epoch:
    :return:
    """
    return learn_rate_base*(0.9**epoch)



def get_variable(name,shape,dtype=tf.float32,initializer=tf.truncated_normal_initializer(mean=0,stddev=0.1)):
    #返回一个对应的filter
    return tf.get_variable(name,shape,dtype,initializer)
#构建网络
def le_net(x,y):
    #1、输入层
    with tf.variable_scope('input'):
        #将输入的x的格式转换为规定的格式 我们用的是lenet所以Lenet输入层一开始的格式是28*28*1
        #[None,input_diml]转换为[None,height,weight,channels] 即[-1,28,28,1]
        net = tf.reshape(x,shape=[-1,28,28,1])
    #2、卷积层
    with tf.variable_scope('conv1'):

        tf.nn.conv2d(input=net,filter=get_variable('w',[5,5,1,32]),strides=[1,1,1,1],padding='SAME')
        #加一个偏置系数 由于[5,5,1,20]中的输出通道数的维数为20,所以偏置项设为20维
        net = tf.nn.bias_add(net,get_variable('b',[32]))
        #激励
        net = tf.nn.relu(net)
    #3、池化
    with tf.variable_scope('pool3'):
        net = tf.nn.max_pool(input=net,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')

    #4、卷积
    with tf.variable_scope('conv4'):
        net = tf.nn.conv2d(input=net,filter=get_variable('w',[5,5,32,64]),strides=[1,1,1,1],padding='SAME')
        net = tf.nn.bias_add(net,get_variable('b',[64]))
        net = tf.nn.relu(net)
    #5池化
    with tf.variable_scope('pool5'):
        net = tf.nn.max_pool(input=net,ksize=[1,2,2,1],strides=[1,2,2,1],padding='VALID')

    #6全连接
    with tf.variable_scope('fc6'):
        #28*28经过两次池化 变成了7*7(28-》14-》7)
        net = tf.reshape(net,shape=[-1,7*7*64])
        net = tf.add(tf.matmul(net,get_variable('w',[7*7*64,1024])),get_variable('b',[1024]))
        net = tf.nn.relu(net)

    #7全连接
    with tf.variable_scope('fc7'):
        net = tf.add(tf.matmul(net,get_variable('w',[1024,n_classes])),get_variable('b',[n_classes]))
        act = tf.nn.softmax(net)

    return act

#接下来的就是与训练有关的代码了
#构建网络
act = le_net(x,y)
#构建模型的损失函数
#softmax_cross_entropy_with_logits:计算softmax中每个样本的交叉熵,logits指定预测值,labels指定实际值
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=act,labels=y))

# #使用梯度下降求解
# #使用梯度下降,最小化误差
# #leaning_rate:要注意,不要过大,过大可能不收敛,过小收敛速度慢
# train = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost)

#我们这里不用梯度下降,用Adam,Adam优化方式较多
train = tf.train.AdamOptimizer(learning_rate=learn_rate_base).minimize(cost)

#得到预测的类别是那一个
#tf.argmax:对矩阵按行或列计算最大值对应的下标,和numpy中的一样
#tf.equal:是对比这两个矩阵或者向量的相等的元素,如果是相等的那就返回True,反之返回False,返回的值的矩阵的维度和A一样
pred = tf.equal(tf.argmax(act,axis=1),tf.argmax(y,axis=1))

#正确率(True转换为1,False转换为0)
acc = tf.reduce_mean(tf.cast(pred,tf.float32))

#初始化
init = tf.global_variables_initializer()

with tf.Session()as sess:
    #进行数据初始化
    sess.run(init)

    #模型的保存、持久化
    saver = tf.train.Saver()
    epoch = 0
    while True:
        avg_cost = 0
        #计算出总的批次
        total_batch=int(train_sample_number/batch_size)
        #迭代更新
        total_batch=10
        for i in range(total_batch):
            #获取x和y
            batch_xs,batch_ys = mnist.train.next_batch(batch_size)
            feeds = {x:batch_xs,y:batch_ys,learn_rate:lean_rate_func(epoch)}
            #模型训练
            sess.run(train,feed_dict=feeds)
            #获取损失函数
            avg_cost+=sess.run(cost,feed_dict=feeds)
        #重新计算平均损失(相当于计算每个样本的损失值)
        avg_cost = avg_cost/total_batch

        #显示误差率和训练集的正确率以及测试集的正确率
        if(epoch+1)%display_step==0:
            print("批次:%03d 损失函数值:%.9f"%(epoch,avg_cost))
            feeds = {x:batch_xs,y:batch_ys,learn_rate:lean_rate_func(epoch)}
            train_acc = sess.run(acc,feed_dict=feeds)
            print("训练集准确率:%.3f"%train_acc)

            feeds = {x:test_img,y:test_label}
            test_acc = sess.run(acc,feed_dict=feeds)
            print('测试准确率:%.3f'%test_acc)

            if train_acc > 0.9 and test_acc > 0.9:
                saver.save(sess,'./mnist/model')
                break
        epoch+=1
#模型可视化输出
writer = tf.summary.FileWriter('./mnist/graph',tf.get_default_graph())
#获取当前默认计算图。
writer.close()

image.png为什么我这里维度不匹配呀,老师,我真的想不明白我错在哪?

Python 全系列/第二十四阶段:人工智能基础_深度学习理论和实战(旧)/Keras框架 31659楼

python实战 (3).zip

老师这个前端的scope这个定义没有使用

Python 全系列/第十阶段:Flask百战电商后台项目/Flask百战电商后台项目 31660楼
JAVA 全系列/第一阶段:JAVA 快速入门/JAVA入门和背景知识 31661楼
JAVA 全系列/第一阶段:JAVA 快速入门/JAVA入门和背景知识 31662楼
Python 全系列/第一阶段:Python入门/面向对象 31664楼
JAVA 全系列/第十一阶段:消息中间件与高并发处理/RabbitMQ(旧) 31665楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637