How to use MATLAB's neural network code in Android app

Source: Internet
Author: User
Tags network function

The whole process can be divided into such a few steps:
    1. First, you have to write a complete neural network in MATLAB.
      1. Get samples
      2. Sample Import
      3. Neural Network Modeling
      4. Neural network Training
      5. Neural Network Testing (optimization modeling)
    2. Then you have to rewrite a neural network in MATLAB, and the special point of the second neural network is
      1. First, the neural network must be written as a function, with a few details.
      2. Save the training Results Net network of the first neural network to a mat file
      3. Data that needs to be used but cannot be written directly to the code is also saved to a mat file (such as data normalization parameters)
      4. Then import the above mat files into the function, which is basically a complete neural network model.
      5. Coupled with a neural network calculation statement, and return the result, this function completes the
    3. Then this MATLAB neural network function is packaged, the result of packaging is a jar package
      1. There are a few issues to be aware of in this piece of packaging
        1. Configure several environment variables
        2. JDK version can not be too high, it is compatible with the MATLAB version, the current my matlab2015 corresponds to the jdk7,8 can not
    4. The jar package is then imported into the Andorid project along with another jar package and added as an external dependency
    5. Finally, in the Android project, write a function that calls the jar-package interface code, passing in the input variable, returning the result of the calculation
    6. Run the test at the end, and you'll find it's an error, yes, it won't work, but it can be run in Java Engineering
      1. Why not?
      2. What other solutions are there?
1. Write a complete neural network in MATLAB1.1. Get the sample and don't say it. 1.2. Sample ImportHow to import data, general Matlab has a common data storage format, that is the mat format, but I do not know how to write this format when I found that there is a way to import the TXT data into the after I chose it, because this format is also very convenient for me to use the Android output, In other words, it is a more general Information Interchange format, the specific operation method is very simple:
    1. You save the data in TXT in this format: Each row is separated by a carriage return, and each column is separated by a space
    2. Then you load this file in MATLAB, you can get a matrix of the data
The code is as follows:
ALLDATA = Load (' alldata.txt '); alldata = AllData (:,:);
1.3.1.4. 1.5. These processes are modified in code or relatively simple(although I was reading a little difficult ...) ), slightly mentioning the following:
    1. (Directly to the MATLAB30 example of the source package into the work path, copy the code inside is more convenient)
    2. Output data requires a matrix conversion
    3. Normalized processing data is one step more process, very simple (although do not know the principle)
    4. Use the NEWFF tool function to build a neural network, use a toolbox inside matlab (actually a library function) to model, train, and calculate, without having to write your own logic code
    5. Parameter configuration is not particularly understood
    6. At the end of the picture, it's not difficult to make a good change of tune.
    7. The transformation of the Matrix in the middle of the feeling is not very familiar with, you can see the variable state in the workspace, or step by step to print the results of some variables to see
clc;clear; % Import 300 sets of data AllData = Load (' alldata.txt '); alldata = AllData (:,:);  % input Output data input = AllData (:, 2:33); o Utputtemp = AllData (:, 1);% output data needs to be disposed of outputs = zeros (300,2);% pre-allocated memory for i=1:300    Switch outputtemp (i)   & nbsp     Case 0            output (i,:) = [1 0];% means that if the data result is 0, then the status of the output layer is [1 0], or the first output node represents the nbsp       Case 1 can directly identify data with decimal position             output (i,:) = [0 1];    Enden d % randomly extracts 280 sets of data as training data, 20 sets of data as the predictive data K = rand (1,300); [M,n] = sort (k),  input_train = input (n (1:280),:) '; output_train = output (n (1:280),:) ';  input_test = input (n ( 281:300),:) '; output_test = output (n (281:300),:) ';  % input and output data for normalization [INPUTN,INPUTPS] = Mapminmax (Input_train); [ OUTPUTN,OUTPUTPS] = Mapminmax (output_train),  % network structure build 32-6-2NET=NEWFF (inputn,outputn,6),  % network parameter configuration (number of iterations, Learning rate, target) net.trainparam.epochs=100;net.trainparam.lr=0.1;net.trainparam.goal=0.0004; % network training Net=train (NET, Inputn,outPUTN);  %BP Network forecast% Predictive data normalized inputn_test=mapminmax (' Apply ', INPUT_TEST,INPUTPS);  % Network Predictive output An=sim (net,inputn_ test);  % network output inverse normalization bpoutput=mapminmax (' reverse ', AN,OUTPUTPS);  % result Analysis figure (1) plot (bpoutput, ': og ') hold Onplot (output_test, '-* '); Legend (' Predictive output ', ' expected output ') title (' BP Network predictive output ', ' fontsize ', ' n ') ylabel (' function output ', ' fontsize ', 12) Xlabel (' sample ', ' FontSize ', 12)% predictive error error=bpoutput-output_test; figure (2) plot (Error, '-* ') title (' BP Network prediction error ', ' FontSize ', Ylabel (' Error ', ' fontsize ', ') xlabel (' sample ', ' fontsize ', ')  figure (3) plot ((Output_test-bpoutput). Bpoutput, '-* '); title (' Neural Network prediction error percentage ')  errorsum = SUM (ABS (Error))
2. Rewrite the neural network in MATLAB to prepare for exporting the jar package 2.1. First, the neural network must be written as a functionThe process of writing a function in MATLAB is like this
  1. Right-click New function in Workspace, rename and open, that's it
  2. the function in MATLAB is a bit special, here is hot to talk about
    1. the whole function has one end of two fixed statements, the head begins with a function, and then: the return value = Functions name (function parameter), tail is end, although at the beginning to see not fit, But the habit is very well understood, and other languages are almost the
      1. return value can be no, that is, the direct function name (function parameter)
      2. The return value can have more than one argument can have multiple, their form is this: function [X,Y,Z]=SPH Ere (Theta,phi,rho)
      3. Note that the function type is not declared in MATLAB, so there are a lot of times when you write a function, you start with a check on the input parameters
    2. and then the following is the official note, One is a summary, followed by a detailed explanation, these things will be displayed in the preview of the
    3. next is the function body, you can do a variety of things, logical statements, call other functions
    4. finally before end you need to define the return value, matlab in this piece is a bit special, You do not have to specify which variable to return, because you have a return value variable in the first statement, so as long as you have this variable in your function content, the last time you execute to end will automatically return the state
    5. -----Call function------
    6. The
    7. call function is the same as the first sentence of the function declaration: [Output Parameter table]= function name (input parameter table)
    8. when calling a function, the order of input and output parameters should be the same as the function definition, and the number must not be more than the function is set to, and may be less than
    9. The
    10. why can be less than, because within the function can be obtained through Nargin () and nargout () the user specified number of input and output parameters when the function is invoked. So if the function has an if else for different cases with less input than the output, it can automatically adapt to
  3. So here, my output is an int, the input is a row matrix, or an array, and my function begins with this:
    function output = Annforecastthi (input_test)
2.2. Then in order not to train the neural network in this function (because the MATLAB setting is unable to export the training function as a jar package), we need to save the trained net in the previous neural network to the mat file and export it directly here.
  1. It is very easy to save the trained net in the previous neural network as a mat file. Right-click Net variable in workspace immediately after operation, save as Mat file.
  2. and then import a little bit of trouble
    1. actually the load mat file has two ways, one is the command line, and the other is the function mode. I looked it up. There is no difference in functionality between the two ways, but it is recommended to function in a function, and the form of the command line will be much simpler
    2. to import a struct (normalized parameter) as an example:
      1. command-line mode: load inputps
      2. function mode:
    3. while importing NET data is a bit cumbersome:
      1. command-line mode: annnet ;
      2. function mode: (after adding a sentence to transform the structure into a network format)
  3. Here you need to import three mat files, one net and two normalization parameters (to be used for inverse normalization)
2.3. Finally, the second neural network model, which is the neural network function, completes the calculation result.Output=find (Bpoutput (:, 1) ==max (Bpoutput (:, 1)));The whole function is this:

function output = Annforecastthi (input_test)%annforecast% input line matrix of length 32, output is 1 or 2 A = Load (' Annnet.mat ');B = FieldNames (A);net = A. (B{1});NET = Network (NET); C = Load (' Anninputps.mat ');D = FieldNames (C);Inputps = C. (D{1}); E = Load (' Annoutputps.mat ');F = FieldNames (E);Outputps = E. (F{1}); %BP Prediction Data normalization of network forecastInputn_test=mapminmax (' Apply ', Input_test ', Inputps); % Network Predictive outputAn=sim (net,inputn_test); % Network output Inverse normalizationBpoutput=mapminmax (' Reverse ', An,outputps); % result analysis% based on network output find out what kind of data it belongs toOutput=find (Bpoutput (:, 1) ==max (Bpoutput (:, 1))); End

---to be continued

How to use MATLAB's neural network code in Android apps

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.