首页 > 解决方案 > uTensor 模型输出不等于预期输出

问题描述

我目前正在做一个需要uTensor的项目。uTensor 似乎工作正常,但是我遇到了一个我(显然)无法解决的问题。

问题定义

我创建了一个简单的 python 脚本,它生成模型并将其保存到文件中。这个保存的模型稍后可以使用uTensor-cli转换为 C++ 代码。生成的 C++ 代码将在 ARM 开发板上运行。

一切运行良好,没有错误。但是,当我创建一个类似“xW+b”的模型时,devboard 上的模型输出总是等于某个静态值,这不等于 python 脚本中模型的输出。

问题是,当使用像“W+b”这样的简单模型(这里没有使用输入张量)时,ARM 开发板上的输出等于 python 脚本的输出。一切都按预期工作。

我的发现

当使用输入张量(没有大的只是一维数组,如 [1,0])时,与 python 脚本的输出相比,ARM 开发板总是输出一些奇怪的值。当不使用输入张量时,一切都按预期工作。

其他信息

因为还没有关于 uTensor 的 wiki,所以我使用了一个教程来了解 uTensor。我使用的教程可以在这里找到:https ://blog.hackster.io/simple-neural-network-on-mcus-a7cbd3dc108c 我写的代码是基于教程,不包含任何成本/损失函数并且不能“学习”任何东西。该代码仅用于调试。

问题

输入张量使应用程序输出意外值的原因是什么?我怎么可能解决这个问题?

代码和输出

Python 脚本

import tensorflow as tf
import numpy as np
from tensorflow.python.framework import graph_util as gu

def weightVariable(shape, name):
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial, name=name)

def createLayer(layerInput, inputSize, outputSize, layerNumber, dropout = -1):
    layerNumber = str(layerNumber)

    #Define weight and bias
    W_fc = weightVariable([inputSize, outputSize], 'W_fc' + layerNumber)

    #Formula Wx+b=y
    a_fc = tf.matmul(layerInput, W_fc, name='y_pred' + layerNumber)
    return a_fc

def saveGraph(saver, sess, y_pred):
    outNodes = [y_pred.op.name]
    subGraphDef = gu.remove_training_nodes(sess.graph_def)
    subGraphDef = gu.convert_variables_to_constants(sess, subGraphDef, outNodes)
    
    #Save the checkpoint
    ckptPath = saver.save(sess, "./chkps/model.ckpt")
    
    #Save the graph
    graphPath = tf.train.write_graph(subGraphDef, "./graph", "mlp.pb", as_text=False)
    
    #Print some usefull messages
    print("Saved checkpoint to: " + ckptPath)
    print("Saved graph to: " + graphPath)
    print("Output tensor: " + y_pred.op.name)
    
    def restoreGraph(saver, sess):
    tf.reset_default_graph()
    saver.restore(sess, "./chkps/model.ckpt")

def main():
    data = [
        [0,0],
        [0,1],
        [1,0],
        [1,1]
    ]
    labels = [
        [0],
        [1],
        [1],
        [0]
    ]
    inputSize = 2
    outputSize = 1

    #Placeholders for the input and output
    x_input = tf.placeholder(tf.float32, [None, inputSize], name='x_input')
    y_output = tf.placeholder(tf.float32, [None, outputSize], name='y_output')
    
    #Layers with relu activation
    inputLayer = createLayer(x_input, inputSize, outputSize, 0)
    
    #Start a session
    sess = tf.Session()
    saver = tf.train.Saver()
    
    #Run the session
    sess.run(tf.global_variables_initializer())
    feed_dict = {x_input: data, y_output: labels}
    sess.run(inputLayer, feed_dict=feed_dict)
    
    #Save the graph
    saveGraph(saver, sess, inputLayer)
    
    #Test the algorithm
    for i in range(0,4):
        testInput = [data[i]]
        output = sess.run(inputLayer, feed_dict={x_input: testInput})[0][0]
        print("Test output " + str(i) + ": " + str(output))
    
    #End the session
    sess.close()

#Execute the main function
main()

输出

Saved checkpoint to: ./chkps/model.ckpt
Saved graph to: ./graph/mlp.pb
Output tensor: y_pred0
Test output 0: 0.0
Test output 1: 0.0034507334
Test output 2: 0.07698402
Test output 3: 0.080434754

转换为 C++

utensor-cli convert graph/mlp.pb --output-nodes=y_pred0

C++ 代码

#include "models/mlp.hpp"
#include "tensor.hpp"
#include "mbed.h"
#include <stdio.h>

const int testData[4][2] = {{0,0},{0,1},{1,0},{1,1}};

Serial uart(USBTX, USBRX, 115200);

int main(void){
    printf("Compiled at: ");
    printf(__TIME__);
    printf("\n");
    
    for(int i = 0; i < 4; i++){
        //Create the context class. 
        Context ctx;
        Tensor *input_x = new WrappedRamTensor<int>({1, 2}, (int*) testData[i]);

        get_mlp_ctx(ctx, input_x);          //Pass the tensor to the context
        S_TENSOR pred_tensor = ctx.get("y_pred0:0");    //Get the output tensor
        ctx.eval();                 //Trigger the inference

        float prediction = *(pred_tensor->read<float>(0,0));    //Get the result
        printf("Test output %d: %f \r\n", i,  prediction);  //Print the result
        
    }

    printf("\n");
    return 0;
}

串行输出

Compiled at: (Compile time)
Test output 0: 0.000000 
Test output 1: 0.000000 
Test output 2: 0.000000 
Test output 3: 0.000000 

标签: pythonc++tensorflowmbed

解决方案


将 C++ 代码中的数据类型更改为 float 就可以了!我仍然不太确定我是怎么不考虑这个的。


推荐阅读