首页 > 解决方案 > 识别数字或数学运算符应用程序

问题描述

我有一个问题,我找不到我的代码有什么问题。从开始。我有应用程序来识别数字和数学运算符,基本的 +、-、/、*。我有一个模型准备好创建一个图表。此图由 Android 应用程序导入。在我看来,它应该工作,但我不知道为什么它不是?


模型.py

import tensorflow as tf
import numpy as np
import _pickle as pickle
from matplotlib import pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data

# mnist_data = input_data.read_data_sets('MNIST_data', one_hot=True)

# read CROHME_test_data
with open("test.pickle", 'rb') as f:
    data = pickle.load(f)
# np.random.shuffle(data)
CROHME_test_data = {"features": np.array([d["features"] for d in data]), "labels": np.array([d["label"] for d in data])}

# read CROHME_train_data
with open("train.pickle", 'rb') as f:
    data = pickle.load(f)
# np.random.shuffle(data)
CROHME_train_data = {"features": np.array([d["features"] for d in data]),
                     "labels": np.array([d["label"] for d in data])}


# function for pulling batches from custom data
def next_batch(num, data):
    idx = np.arange(0, len(data["features"]))
    np.random.shuffle(idx)
    idx = idx[:num]
    features_shuffle = [data["features"][i] for i in idx]
    labels_shuffle = [data["labels"][i] for i in idx]
    return np.asarray(features_shuffle), np.asarray(labels_shuffle)


# Function to create a weight neuron using a random number. Training will assign a real weight later
def weight_variable(shape, name):
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial, name=name)


# Function to create a bias neuron. Bias of 0.1 will help to prevent any 1 neuron from being chosen too often
def biases_variable(shape, name):
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial, name=name)


# Function to create a convolutional neuron. Convolutes input from 4d to 2d. This helps streamline inputs
def conv_2d(x, W, name):
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME', name=name)


# Function to create a neuron to represent the max input. Helps to make the best prediction for what comes next
def max_pool(x, name):
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name=name)


labels_number = 14
# A way to input images (as 784 element arrays of pixel values 0 - 1)
x_input = tf.placeholder(dtype=tf.float32, shape=[None, 784], name='x_input')
# A way to input labels to show model what the correct answer is during training
y_input = tf.placeholder(dtype=tf.float32, shape=[None, labels_number], name='y_input')

# First convolutional layer - reshape/resize images
# A weight variable that examines batches of 5x5 pixels, returns 32 features (1 feature per bit value in 32 bit float)
W_conv1 = weight_variable([5, 5, 1, 32], 'W_conv1')
# Bias variable to add to each of the 32 features
b_conv1 = biases_variable([32], 'b_conv1')
# Reshape each input image into a 28 x 28 x 1 pixel matrix
x_image = tf.reshape(x_input, [-1, 28, 28, 1], name='x_image')
# Flattens filter (W_conv1) to [5 * 5 * 1, 32], multiplies by [None, 28, 28, 1] to associate each 5x5 batch with the
# 32 features, and adds biases
h_conv1 = tf.nn.relu(conv_2d(x_image, W_conv1, name='conv1') + b_conv1, name='h_conv1')
# Takes windows of size 2x2 and computes a reduction on the output of h_conv1 (computes max, used for better prediction)
# Images are reduced to size 14 x 14 for analysis
h_pool1 = max_pool(h_conv1, name='h_pool1')

# Second convolutional layer, reshape/resize images
# Does mostly the same as above but converts each 32 unit output tensor from layer 1 to a 64 feature tensor
W_conv2 = weight_variable([5, 5, 32, 64], 'W_conv2')
b_conv2 = biases_variable([64], 'b_conv2')
h_conv2 = tf.nn.relu(conv_2d(h_pool1, W_conv2, name='conv2') + b_conv2, name='h_conv2')
# Images at this point are reduced to size 7 x 7 for analysis
h_pool2 = max_pool(h_conv2, name='h_pool2')

# First dense layer, performing calculation based on previous layer output
# Each image is 7 x 7 at the end of the previous section and outputs 64 features, we want 32 x 32 neurons = 1024
W_dense1 = weight_variable([7 * 7 * 64, 1024], name='W_dense1')
# bias variable added to each output feature
b_dense1 = biases_variable([1024], name='b_dense1')
# Flatten each of the images into size [None, 7 x 7 x 64]
h_pool_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64], name='h_pool_flat')
# Multiply weights by the outputs of the flatten neuron and add biases
h_dense1 = tf.nn.relu(tf.matmul(h_pool_flat, W_dense1, name='matmul_dense1') + b_dense1, name='h_dense1')

# Dropout layer prevents overfitting or recognizing patterns where none exist
# Depending on what value we enter into keep_prob, it will apply or not apply dropout layer
keep_prob = tf.placeholder(dtype=tf.float32, name='keep_prob')
# Dropout layer will be applied during training but not testing or predicting
h_drop1 = tf.nn.dropout(h_dense1, keep_prob, name='h_drop1')

# Readout layer used to format output
# Weight variable takes inputs from each of the 1024 neurons from before and outputs an array of 14 elements
W_readout1 = weight_variable([1024, labels_number], name='W_readout1')
# Apply bias to each of the 14 outputs
b_readout1 = biases_variable([labels_number], name='b_readout1')
# Perform final calculation by multiplying each of the neurons from dropout layer by weights and adding biases
y_readout1 = tf.add(tf.matmul(h_drop1, W_readout1, name='matmul_readout1'), b_readout1, name='y_readout1')

# Softmax cross entropy loss function compares expected answers (labels) vs actual answers (logits)
cross_entropy_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_input, logits=y_readout1))
# Adam optimizer aims to minimize loss
train_step = tf.train.AdamOptimizer(0.0001).minimize(cross_entropy_loss)
# Compare actual vs expected outputs to see if highest number is at the same index, true if they match and false if not
correct_prediction = tf.equal(tf.argmax(y_input, 1), tf.argmax(y_readout1, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

# Used to save the graph and weights
saver = tf.train.Saver()

# Run in with statement so session only exists within it
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    # Save the graph shape and node names to pbtxt file
    tf.train.write_graph(sess.graph_def, '.', 'advanced_mnist.pbtxt', False)

    # Train the model, running through data 20000 times in batches of 50
    # Print out step # and accuracy every 100 steps and final accuracy at the end of training
    # Train by running train_step and apply dropout by setting keep_prob to 0.5
    for i in range(1000):
        batch = next_batch(50, CROHME_train_data)
        if i % 100 == 0:
            train_accuracy = accuracy.eval(feed_dict={x_input: batch[0], y_input: batch[1], keep_prob: 1.0})
            print("step %d, training accuracy %g" % (i, train_accuracy))
        train_step.run(feed_dict={x_input: batch[0], y_input: batch[1], keep_prob: 0.5})
    print("test accuracy %g" % accuracy.eval(feed_dict={x_input: CROHME_test_data["features"],
                                                        y_input: CROHME_test_data["labels"], keep_prob: 1.0}))

    # Save the session with graph shape and node weights
    saver.save(sess, './advanced_mnist.ckpt')

    # Make a prediction of random image
    img_num = np.random.randint(0, len(CROHME_test_data["features"]))
    print("expected :", CROHME_test_data["labels"][img_num])

    print("predicted :",
          sess.run(y_readout1, feed_dict={x_input: [CROHME_test_data["features"][img_num]], keep_prob: 1.0}))

    for j in range(28):
        print(CROHME_test_data["features"][img_num][j * 28:(j + 1) * 28])

    # this code can be used for image displaying
    first_image = CROHME_test_data["features"][img_num]
    first_image = np.array(first_image, dtype='float')
    pixels = first_image.reshape((28, 28))
    plt.imshow(pixels, cmap='gray')
    plt.show()

图.py

import tensorflow as tf
from tensorflow.python.tools import freeze_graph, optimize_for_inference_lib

# Saving the graph as a pb file taking data from pbtxt and ckpt files and providing a few operations
freeze_graph.freeze_graph('advanced_mnist.pbtxt',
                          '',
                          True,
                          'advanced_mnist.ckpt',
                          'y_readout1',
                          'save/restore_all',
                          'save/Const:0',
                          'frozen_advanced_mnist.pb',
                          True,
                          '')

# Read the data form the frozen graph pb file
input_graph_def = tf.GraphDef()
with tf.gfile.Open('frozen_advanced_mnist.pb', 'rb') as f:
    data = f.read()
    input_graph_def.ParseFromString(data)

# Optimize the graph with input and output nodes
output_graph_def = optimize_for_inference_lib.optimize_for_inference(
    input_graph_def,
    ['x_input', 'keep_prob'],
    ['y_readout1'],
    tf.float32.as_datatype_enum)

# Save the optimized graph to the optimized pb file
f = tf.gfile.FastGFile('optimized_advanced_mnist.pb', 'w')
f.write(output_graph_def.SerializeToString())

主要活动

package com.example.owl.advanced_mnist_android;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import org.tensorflow.contrib.android.TensorFlowInferenceInterface;

public class MainActivity extends AppCompatActivity {

    ImageView imageView;
    TextView resultsTextView;

    static {
        System.loadLibrary("tensorflow_inference");
    }
    private static final String MODEL_FILE = "file:///android_asset/optimized_advanced_mnist.pb";
    private static final String INPUT_NODE = "x_input";
    private static final int[] INPUT_SIZE = {1, 784};
    private static final String KEEP_PROB = "keep_prob";
    private static final int[] KEEP_PROB_SIZE = {1};
    private static final String OUTPUT_NODE = "y_readout1";
    private TensorFlowInferenceInterface inferenceInterface;

    private int imageIndex = 10;
    private int[] imageResourceIDs = {
            R.drawable.digit0,
            R.drawable.digit1,
            R.drawable.digit2,
            R.drawable.digit3,
            R.drawable.digit4,
            R.drawable.digit5,
            R.drawable.digit6,
            R.drawable.digit7,
            R.drawable.digit8,
            R.drawable.digit9,
            R.drawable.rsz_przechwytywanie,
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageView = (ImageView) findViewById(R.id.image_view);
        resultsTextView = (TextView) findViewById(R.id.results_text_view);

        inferenceInterface = new TensorFlowInferenceInterface();
        inferenceInterface.initializeTensorFlow(getAssets(), MODEL_FILE);
    }

    public void loadImageAction(View view) {
        imageIndex = (imageIndex == 10) ? 0 : imageIndex + 1 ;
        imageView.setImageResource(imageResourceIDs[imageIndex]);
    }

    public void predictDigitAction(View view) {
        float[] pixelBuffer = convertImage();
        float[] results = predictDigit(pixelBuffer);
        formatResults(results);
    }

    private void formatResults(float[] results) {
        float max = 0;
        float secondMax = 0;
        int maxIndex = 0;
        int secondMaxIndex = 0;
        for (int i = 0; i < 15; i++) {
            if (results[i] > max) {
                secondMax = max;
                secondMaxIndex = maxIndex;
                max = results[i];
                maxIndex = i;
            } else if (results[i] < max && results[i] > secondMax) {
                secondMax = results[i];
                secondMaxIndex = i;
            }
        }
        String output = "Model predicts: " + String.valueOf(maxIndex) +
                ", second choice: " + String.valueOf(secondMaxIndex);
        resultsTextView.setText(output);
    }

    private float[] predictDigit(float[] pixelBuffer) {
        inferenceInterface.fillNodeFloat(INPUT_NODE, INPUT_SIZE, pixelBuffer);
        inferenceInterface.fillNodeFloat(KEEP_PROB, KEEP_PROB_SIZE, new float[] {0.5f});
        inferenceInterface.runInference(new String[] {OUTPUT_NODE});
        float[] outputs = new float[14];
        inferenceInterface.readNodeFloat(OUTPUT_NODE, outputs);
        return outputs;
    }

    private float[] convertImage() {
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), imageResourceIDs[imageIndex]);
        Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, 28, 28, true);
        imageView.setImageBitmap(scaledBitmap);
        int[] intArray = new int[784];
        float[] floatArray = new float[784];
        scaledBitmap.getPixels(intArray, 0, 28, 0, 0, 28, 28);
        for (int i = 0; i < 784; i++) {
            floatArray[i] = intArray[i] / -16777216;
        }
        return floatArray;
    }

}

一切看起来都很好,但我有一个错误:

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.owl.advanced_mnist_android, PID: 6855
                  java.lang.IllegalStateException: Could not execute method for android:onClick
                      at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
                      at android.view.View.performClick(View.java:6891)
                      at android.widget.TextView.performClick(TextView.java:12651)
                      at android.view.View$PerformClick.run(View.java:26083)
                      at android.os.Handler.handleCallback(Handler.java:789)
                      at android.os.Handler.dispatchMessage(Handler.java:98)
                      at android.os.Looper.loop(Looper.java:164)
                      at android.app.ActivityThread.main(ActivityThread.java:6938)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
                   Caused by: java.lang.reflect.InvocationTargetException
                      at java.lang.reflect.Method.invoke(Native Method)
                      at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
                      at android.view.View.performClick(View.java:6891) 
                      at android.widget.TextView.performClick(TextView.java:12651) 
                      at android.view.View$PerformClick.run(View.java:26083) 
                      at android.os.Handler.handleCallback(Handler.java:789) 
                      at android.os.Handler.dispatchMessage(Handler.java:98) 
                      at android.os.Looper.loop(Looper.java:164) 
                      at android.app.ActivityThread.main(ActivityThread.java:6938) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374) 
                   Caused by: java.lang.IllegalArgumentException: No Operation named [x_input] in the Graph
                      at org.tensorflow.Session$Runner.operationByName(Session.java:297)
                      at org.tensorflow.Session$Runner.feed(Session.java:115)
                      at org.tensorflow.contrib.android.TensorFlowInferenceInterface.addFeed(TensorFlowInferenceInterface.java:437)
                      at org.tensorflow.contrib.android.TensorFlowInferenceInterface.fillNodeFloat(TensorFlowInferenceInterface.java:186)
                      at com.example.owl.advanced_mnist_android.MainActivity.predictDigit(MainActivity.java:89)
                      at com.example.owl.advanced_mnist_android.MainActivity.predictDigitAction(MainActivity.java:63)
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
                      at android.view.View.performClick(View.java:6891) 
                      at android.widget.TextView.performClick(TextView.java:12651) 
                      at android.view.View$PerformClick.run(View.java:26083) 
                      at android.os.Handler.handleCallback(Handler.java:789) 
                      at android.os.Handler.dispatchMessage(Handler.java:98) 
                      at android.os.Looper.loop(Looper.java:164) 
                      at android.app.ActivityThread.main(ActivityThread.java:6938) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374) 

标签: javaandroidpythontensorflowneural-network

解决方案


推荐阅读