为什么flask python文件app.py中的函数make_response的参数rv等于零?

时间:2017-08-04 03:06:15

标签: python html flask tensorflow anaconda

我正在尝试从烧瓶网站获取一些输入数字,然后将这些数字插入神经网络,该网络将输出存储在字典中。然后,我有一个结果页面,其中包含一个包含所有输出的表格 以下是所有相关的烧瓶代码:

@app.route('/ConvNet', methods=["GET", "POST"])

def ConvNet():
    return render_template("ConvNet.html")

@app.route('/ConvNetForm', methods=["GET", "POST"])

def ConvNetForm():
    if request.form == "POST":
         #hyperparameters
        learning_rate = request.form['learning_rate']
        training_iters= request.form['training_iters']
        batch_size= request.form['batch_size']
        display_step = request.form['display_step']

        #network parameters
        #28 * 28 image
        n_input = 784
        n_classes = 10
        dropout = 0.75

        x = tf.placeholder(tf.float32,[None, n_input])
        y = tf.placeholder(tf.float32,[None, n_classes])
        keep_prob = tf.placeholder(tf.float32)

        def conv2d(x, W, b, strides=1):
            x = tf.nn.conv2d(x,W,strides=[1, strides, strides, 1], padding = 'SAME')
            x = tf.nn.bias_add(x, b)
            return tf.nn.relu(x)

        def maxpool2d(x, k=2):
            return tf.nn.max_pool(x, ksize=[1,k,k,1], strides=[1,k,k,1], padding='SAME')

        #create model
        def conv_net(x, weights, biases, dropout):
            #reshape input
            x = tf.reshape(x, shape=[-1, 28, 28, 1])

            #convolutional layer
            conv1 = conv2d(x, weights['wc1'], biases['bc1'])
            #maxpooling
            conv1 = maxpool2d(conv1, k=2)

            conv2 = conv2d( conv1, weights['wc2'], biases['bc2'])
            conv2 = maxpool2d(conv2, k=2)

            fc1 = tf.reshape(conv2, [-1, weights['wd1'].get_shape().as_list()[0]])
            fc1 = tf.add(tf.matmul(fc1, weights['wd1']), biases['bd1'])
            fc1 = tf.nn.relu(fc1)
            #apply dropout
            fc1 = tf.nn.dropout(fc1, dropout)

            #outpout, class predication
            out = tf.add(tf.matmul(fc1, weights['out']), biases['out'])
            return out

        #create weights
        weights = {
                'wc1': tf.Variable(tf.random_normal([5,5,1,32])),
                'wc2': tf.Variable(tf.random_normal([5,5,32,64])),
                'wd1': tf.Variable(tf.random_normal([7*7*64, 1024])),
                'out': tf.Variable(tf.random_normal([1024, n_classes]))
        }

        biases = {
                'bc1': tf.Variable(tf.random_normal([32])),
                'bc2': tf.Variable(tf.random_normal([64])),
                'bd1': tf.Variable(tf.random_normal([1024])),
                'out': tf.Variable(tf.random_normal([n_classes]))
          }

        #construct model
        pred = conv_net(x, weights, biases, keep_prob)

        #define optimizer and loss
        cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = pred,labels = y))
        optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)

        #Evaluate model
        correct_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
        accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))

        #initializing the variables
        init = tf.global_variables_initializer()

        style.use('fivethirtyeight')

        #Creating Graph
        #fig = plt.figure(edgecolor='c')
        #ax1=fig.add_subplot(1,1,1)

        ConvResult=dict()
        # Launch the graph
        with tf.Session() as sess:
            sess.run(init)
            step = 1
            # Keep training until reach max iterations
            while step * batch_size < training_iters:
                images_seen = step * batch_size
                batch_x, batch_y = mnist.train.next_batch(batch_size)
                # Run optimization op (backprop)
                sess.run(optimizer, feed_dict={x: batch_x, y: batch_y,
                                               keep_prob: dropout})
                if step % display_step == 0:
                    # Calculate batch loss and accuracy
                    loss, acc = sess.run([cost, accuracy], feed_dict={x: batch_x,
                                                                      y: batch_y,
                                                                      keep_prob: 1.})
                    print("Iter " + str(images_seen) + ", Minibatch Loss= " + \
                          "{:.6f}".format(loss) + ", Training Accuracy= " + \
                          "{:.5f}".format(acc))
                    ConvResult[images_seen] = acc
                step += 1
            print("Optimization Finished!")

            # Calculate accuracy for 256 mnist test images
            print("Testing Accuracy:", \
                sess.run(accuracy, feed_dict={x: mnist.test.images[:256],
                                              y: mnist.test.labels[:256],
                                              keep_prob: 1.}))
        return render_template("ConvNetForm.html", ConvResult=ConvResult)

以下是所有相关的html代码:(模板)

{% extends "header.html" %}
{% block body %}
<h1 class="text-center">Convolutional Neural Network Site</h1>
<div class="title">
    <h3>Post Hyper Parameter Values</h3>
</div>
<div id="content">
    <form method="post" action="{{ url_for('ConvNetForm')}}">
        <label for="learning_rate">Please enter a value for the hyper parameter learning rate:</label>
        <input type="number" name="learning_rate" value="0.001" step="0.001" min="0"max="1"/><br />
        <label for="training_iters">Please enter a value for the hyper parameter training iterations:</label>
        <input type="number" name="training_iters" value="200000" min="1000" max="500000"/><br />
        <label for="batch_size">Please enter a value for the hyper parameter batch size:</label>
        <input type="number" name="batch_size" value="128" min="1" max="1000"/><br />
        <label for="display_step">Please enter a value for the hyper parameter display step:</label>
        <input type="number" name="display_step" value="10" min="1" max="100"/><br />
        <input type="submit" />
        <input type="reset" />
    </form>
</div>
{% endblock %}

结果模板中的相关代码:

{% extends "header.html" %}
{% block body %}

<h1 class="text-center">Results of Convolutional Neural Network</h1>
<table>
{% for key, value in ConvResult.iteritems() %}
    <tr>
        <th> {{ key }} </th>
        <td> {{ value }} </td>
    </tr>
{% endfor %}
</table>
{% endblock %}

此外,计算机上的实际错误是值错误:视图功能未返回响应。

1 个答案:

答案 0 :(得分:0)

您应该更改允许仅在表单上发布的方法,甚至不要在convnet函数中提及方法。