神经网络C语言实现
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
#i n c l u d e"" #include <>
const double e = ;
//设置一个神经网络
//有一个隐藏层(含有两个节点)
//输出层有一个节点
//输入数据是二维(两个节点)
//一个样本数据为:x = , 标签为
//初始权值输入节点1到隐藏层:,
//输入节点2到隐藏层:,
//隐藏层到输出层初始权值为:,
//学习速率为1
double changeWeightFromHiddenToOutput(double cost,double output,double hiddenLayerCode)
{
double result=0;
result = cost*output*(1-output)*hiddenLayerCode;
return result;
}
double changeWeightFromInputToHidden(double cost,double output,double weightOfHiddenCodeToOutput,double weightOfHiddenCode,double inputNum)
double result=0;
result = cost*output*(1-output)*weightOfHiddenCodeToOutput*weightOfHiddenC ode*(1-weightOfHiddenCode)*inputNum;
return result;
}
double sigmoidFunction(double x)
{
double result=0;
result = 1/(1+pow(e,-x));
return result;
}
double costFunction(double originalSignal,double outputOfOurCalculation)
{
//此处采取的损失函数是最小二乘法
double cost=0;
cost = (1/*(originalSignal-outputOfOurCalculation)*(originalSignal-outpu tOfOurCalculation);
return cost;
double upDateWeightFunction(double originalValue,double gradient) {
double updatedWeight=originalValue;
updatedWeight = updatedWeight - fabs(gradient);
return updatedWeight;
}
int main(void)
{
double weightFromInputToHidden[][2]={,,,};
double weightFromHiddenToOutput[]={,};
double firstHiddenCode,secondHiddenCode,outputCode;
double inputValue[] ={,};
double originalSignal = ;
double cost=0;
double weightChangeNum=0;
double addWeightSum = 0;
firstHiddenCode = 0;
secondHiddenCode = 0;
outputCode = 0;
//前向传播
addWeightSum = weightFromInputToHidden[0][0]*inputValue[0] +
weightFromInputToHidden[1][0]*inputValue[1];
firstHiddenCode = sigmoidFunction(addWeightSum);
addWeightSum = weightFromInputToHidden[0][1]*inputValue[0] + weightFromInputToHidden[1][1]*inputValue[1];
secondHiddenCode = sigmoidFunction(addWeightSum);
addWeightSum = weightFromHiddenToOutput[0]*firstHiddenCode + weightFromHiddenToOutput[1]*secondHiddenCode;
outputCode = sigmoidFunction(addWeightSum);
//计算误差
cost = costFunction(originalSignal,outputCode);
printf("\n\n(0)firNode:[%f] secNode:[%f] outNode:[%f] cost:%f",firstHiddenCode,secondHiddenCode,outputCode,cost);
printf("\n\n\t\t输入到隐藏层的权值:\t\t");
for(int i=0;i<2;i++)
{
printf("\n\t\t");
for(int j=0;j<2;j++)
printf(" %lf ",weightFromInputToHidden[i][j]);
}
printf("\n\n\t\t隐藏层到输出的权值:\n\t\t");
for(i=0;i<2;i++)
{