神经网络数学相关算法java实现

  • Post author:
  • Post category:java




神经网络数学相关算法java实现

最近一直在学神经网络,算法基本已经理解了,于是想用java来实现一下,首先创建一个类Array,三个字段,如图
在这里插入图片描述

在写代码之前要先了解一下矩阵是如何相乘的,其实就是矩阵1的行和矩阵2的列逐项相乘然后求和,例如

[[1 , 2 , 3],

[4 , 5 , 6]]

x

[[1 , 3],

[2 , 4 ],

[3 , 6]]

运算结果是

[[1×1+2×2+3×3 ,1×3+2×4+3×6 ],

[4×1+5×2+6×3 , 4×3+5×4+6×6]]

这就是矩阵乘法的原理,下面我们来使用java实现一下这个算法(shape方法是返回矩阵的维度,push方法是向矩阵尾部增加一个数的方法)

// 矩阵点乘
public Array dot(Array arr) throws Exception {
	// 判断两个矩阵是否能够相乘
	int target_w = arr.shape()[0] ;
	int target_h = arr.shape()[1] ;
	if(this.w != target_h) {
		throw new Exception("矩阵无法相乘");
	}
	// 当前对象的矩阵数据
	double[] source = this.data ;
	// 目标对象的矩阵数据
	double[] target = arr.getData() ;
	// 创建相乘后的矩阵
	Array result = new Array(target_w) ;
	for(int i = 0 , len = this.h * target_w ; i < len ; i++) {
		int temp_w = i%target_w ;
		int temp_h = i/target_w ;
		// 计算1矩阵i行和2矩阵j列的乘积
		double d = 0 ;
		for(int j = 0 ; j < this.w ; j++) {
			d += source[temp_h*this.w+j]*target[temp_w+j*target_w] ;
		}
		result.push(temp_w , temp_h , d);
	}
	return result ;
}

下面来实现sigmoid激活函数,公式很简单 1 / 1+exp(-x)

// 求激活函数sigmoid的输出
public Array sigmoid() {
	Array result = new Array(this.w) ;
	double[] target = this.data ;
	for (int i = 0 , len = this.w*this.h ; i<len ; i++) {
		result.push(i%this.w, i/this.w, 1 / (1 + Math.pow(Math.E, -data[i]))); 
	}
	return result ;
}

下面是矩阵转置方法,原理就是按顺序把i列变成i行

// 计算矩阵的反转矩阵
public Array T() {
	Array result = new Array(this.h) ;
	for(int i = 0 ; i < this.w ; i++) {
		for(int j = 0 ; j < this.h ; j++) {
			result.push(j, i, this.data[j*this.w+i]);
		}
	}
	return result ;
}

完整的代码就不再这里粘贴了,全部在我的github上

git地址

,git上这个项目实现了整个神经网络,还提供了我花了很长时间准备的验证码数据集,准确率可达到99.99%以上



版权声明:本文为weixin_43999566原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。