使用c ++的神经网络中的单神经元

时间:2016-08-09 12:18:17

标签: c++ neural-network

我正在尝试用类似于这个图像的c ++编写一个简单的神经元函数。我使用sigmoid函数作为激活函数。 enter image description here

这是我的c ++神经元功能

#include<math.h>

double neuron(double layer_inputs[],int iter)
{

  // Feed forwarding single neuron
    double network=0;
    double bias=1;
    double activation;

    //get number of elements in the layer
    const int num=sizeof(layer_inputs)/sizeof(layer_inputs[0]);
    double weight[num];

    for ( int i = 0; i < num; i++ )
    {
        if(iter==0)
        {
        //first time assigning random weights
            weight[i]=rand();
        }

        //feed forwarding summation
        network=network+(layer_inputs[i]*weight[i]+bias);


    }

    activation= 1.0 / (1.0 + exp(-network)); //sigmoid activation function

return activation;
}

问题是我不知道我的代码中是否出现任何逻辑错误。 iter是迭代变量,用于检查神经元是否第一次激活。我的神经网络中的神经元是否正确无误。

编辑:

尽管不是来自程序或定量背景,但我对编程,神经网络和人工智能非常着迷。我曾在caret R中使用内置函数但为了更多的理解,我想从头开始创建一个简单的神经网络。我从互联网上学到了大部分基础知识,并且我在这里发布了我的代码,因为我确信我做了一些不合逻辑的但正在执行的脚本。

#include<iostream>
#include <math.h>//pow, exp
#include "sqrtnn.h" //neuron()


int main()
{

    double input[]= {1,4,9,16,25,36,49,64,81,100};
    double output[]= {1,2,3,4,5,6,7,8,9,10};
    //number of layers
    double layer=3;
    double output_network[10];
    double error[10];
    double learning_rate=0.02;
    //number of iterations
    int iter=10;
    int input_num=sizeof(input)/sizeof(input[0]);
    std::cout<<"Simple  neural network for solving square root\n \nINPUT -> OUTPUT\n\n";
    for ( int i = 0; i < iter; i++ )
    {
        for ( int j = 0; j < input_num; j++ )
        {
            for ( int k = 0; k < layer; k++ )
            {
                //feed forwarding
                output_network[j] =neuron(input,i) ; //sigmoid activation function

                //back propogation
                error[j]=1/2*pow(output[j]-output_network[j],2);//error function
                std::cout<<input[j]<<" -> "<< output[j]<<"= "<< error[j] <<"\n";


            }
        }
    }


    return 0;
}

2 个答案:

答案 0 :(得分:2)

您正在编写C代码,而不是C ++。 C数组不知道自己的大小。使用std::vector<double> layer_inputs,您可以拨打layer_inputs.size()

代码中的其他C位:在需要之前不要声明变量;你太早宣布activation了。事实上,我根本不会定义它 - 只是return 1.0 / (1.0 + exp(-network));

答案 1 :(得分:0)

这里是问题,只是将double input[10]转换为double input[],因为它不是c ++也不在输出数组上执行此操作,并且它不是训练神经网络模型,因为实际的(就绪的女仆输入/输出)提供并且double learning_rate = 0.02;被声明在任何地方都不使用。

相关问题