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

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

最近一直在学神经网络,算法基本已经理解了,于是想用java来实现一下,首先创建一个类Array,三个字段,如图在这里插入图片描述
在写代码之前要先了解一下矩阵是如何相乘的,其实就是矩阵1的行和矩阵2的列逐项相乘然后求和,例如
[[1 , 2 , 3],
[4 , 5 , 6]]
x
[[1 , 3],
[2 , 4 ],
[3 , 6]]
运算结果是
[[1x1+2x2+3x3 ,1x3+2x4+3x6 ],
[4x1+5x2+6x3 , 4x3+5x4+6x6]]

这就是矩阵乘法的原理,下面我们来使用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%以上

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值