
正文
java算法如何实现代码 java算法总结
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
如何用70行Java代码实现神经网络算法
如何用70行Java代码实现神经网络算法
import java.util.Random;
public class BpDeep{
public double[][] layer;//神经网络各层节点
public double[][] layerErr;//神经网络各节点误差
public double[][][] layer_weight;//各层节点权重
public double[][][] layer_weight_delta;//各层节点权重动量
public double mobp;//动量系数
public double rate;//学习系数
public BpDeep(int[] layernum, double rate, double mobp){
this.mobp = mobp;
this.rate = rate;
layer = new double[layernum.length][];
layerErr = new double[layernum.length][];
layer_weight = new double[layernum.length][][];
layer_weight_delta = new double[layernum.length][][];
Random random = new Random();
for(int l=0;llayernum.length;l++){
layer[l]=new double[layernum[l]];
layerErr[l]=new double[layernum[l]];
if(l+1layernum.length){
layer_weight[l]=new double[layernum[l]+1][layernum[l+1]];
layer_weight_delta[l]=new double[layernum[l]+1][layernum[l+1]];
for(int j=0;jlayernum[l]+1;j++)
for(int i=0;ilayernum[l+1];i++)
layer_weight[l][j][i]=random.nextDouble();//随机初始化权重
}
}
}
//逐层向前计算输出
public double[] computeOut(double[] in){
for(int l=1;llayer.length;l++){
for(int j=0;jlayer[l].length;j++){
double z=layer_weight[l-1][layer[l-1].length][j];
for(int i=0;ilayer[l-1].length;i++){
layer[l-1][i]=l==1?in[i]:layer[l-1][i];
z+=layer_weight[l-1][i][j]*layer[l-1][i];
}
layer[l][j]=1/(1+Math.exp(-z));
}
}
return layer[layer.length-1];
}
//逐层反向计算误差并修改权重
public void updateWeight(double[] tar){
int l=layer.length-1;
for(int j=0;jlayerErr[l].length;j++)
layerErr[l][j]=layer[l][j]*(1-layer[l][j])*(tar[j]-layer[l][j]);
while(l--0){
for(int j=0;jlayerErr[l].length;j++){
double z = 0.0;
for(int i=0;ilayerErr[l+1].length;i++){
z=z+l0?layerErr[l+1][i]*layer_weight[l][j][i]:0;
layer_weight_delta[l][j][i]= mobp*layer_weight_delta[l][j][i]+rate*layerErr[l+1][i]*layer[l][j];//隐含层动量调整
layer_weight[l][j][i]+=layer_weight_delta[l][j][i];//隐含层权重调整
if(j==layerErr[l].length-1){
layer_weight_delta[l][j+1][i]= mobp*layer_weight_delta[l][j+1][i]+rate*layerErr[l+1][i];//截距动量调整
layer_weight[l][j+1][i]+=layer_weight_delta[l][j+1][i];//截距权重调整
}
}
layerErr[l][j]=z*layer[l][j]*(1-layer[l][j]);//记录误差
}
}
}
public void train(double[] in, double[] tar){
double[] out = computeOut(in);
updateWeight(tar);
}
}
相关问答
Q1: 如何用JAVA实现快速排序算法?
本人特地给你编的代码\x0d\x0a亲测\x0d\x0a\x0d\x0apublicclassQuickSort{\x0d\x0a\x0d\x0apublicstaticintPartition(inta[],intp,intr){\x0d\x0aintx=a[r-1];\x0d\x0ainti=p-1;\x0d\x0ainttemp;\x0d\x0afor(intj=p;jif(a[j-1]//swap(a[j-1],a[i-1]);\x0d\x0ai++;\x0d\x0atemp=a[j-1];\x0d\x0aa[j-1]=a[i-1];\x0d\x0aa[i-1]=temp;\x0d\x0a\x0d\x0a}\x0d\x0a}\x0d\x0a//swap(a[r-1,a[i+1-1]);\x0d\x0atemp=a[r-1];\x0d\x0aa[r-1]=a[i+1-1];\x0d\x0aa[i+1-1]=temp;\x0d\x0a\x0d\x0areturni+1;\x0d\x0a\x0d\x0a}\x0d\x0a\x0d\x0apublicstaticvoidQuickSort(inta[],intp,intr){\x0d\x0a\x0d\x0aif(p
Q2: 如何用Java写出泰森多边形算法代码???我找了好多资源表示无解呀?
package com.wangyin.seapay.loginkgo;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.process.Process;
import org.geotools.process.ProcessException;
import org.geotools.process.ProcessFactory;
import org.geotools.process.spatialstatistics.core.Params;
import org.geotools.process.spatialstatistics.enumeration.ThiessenAttributeMode;
import org.geotools.process.spatialstatistics.operations.ThiessenPolygonOperation;
import org.geotools.text.Text;
import org.geotools.util.NullProgressListener;
import org.geotools.util.logging.Logging;
import org.opengis.util.ProgressListener;
import com.vividsolutions.jts.geom.Geometry;
/**
* Created by hanxiaofei on 2018/4/11.
*/
public class ThiessenPolygonProcess extends AbstractStatisticsProcess {
protected static final Logger LOGGER = Logging.getLogger(ThiessenPolygonProcess.class);
private boolean started = false;
public ThiessenPolygonProcess(ProcessFactory factory) {
super(factory);
}
public ProcessFactory getFactory() {
return factory;
}
public static SimpleFeatureCollection process(SimpleFeatureCollection inputFeatures,
ThiessenAttributeMode attributes, Geometry clipArea, ProgressListener monitor) {
MapString, Object map = new HashMapString, Object();
map.put(ThiessenPolygonProcessFactory.inputFeatures.key, inputFeatures);
map.put(ThiessenPolygonProcessFactory.attributes.key, attributes);
map.put(ThiessenPolygonProcessFactory.clipArea.key, clipArea);
Process process = new ThiessenPolygonProcess(null);
MapString, Object resultMap;
try {
resultMap = process.execute(map, monitor);
return (SimpleFeatureCollection) resultMap
.get(ThiessenPolygonProcessFactory.RESULT.key);
} catch (ProcessException e) {
LOGGER.log(Level.FINER, e.getMessage(), e);
}
return null;
}
@Override
public MapString, Object execute(MapString, Object input, ProgressListener monitor)
throws ProcessException {
if (started)
throw new IllegalStateException("Process can only be run once");
started = true;
if (monitor == null)
monitor = new NullProgressListener();
try {
monitor.started();
monitor.setTask(Text.text("Grabbing arguments"));
monitor.progress(10.0f);
SimpleFeatureCollection inputFeatures = (SimpleFeatureCollection) Params.getValue(
input, ThiessenPolygonProcessFactory.inputFeatures, null);
if (inputFeatures == null) {
throw new NullPointerException("inputFeatures parameter required");
}
ThiessenAttributeMode attributes = (ThiessenAttributeMode) Params.getValue(input,
ThiessenPolygonProcessFactory.attributes,
ThiessenPolygonProcessFactory.attributes.sample);
Geometry clipArea = (Geometry) Params.getValue(input,
ThiessenPolygonProcessFactory.clipArea, null);
monitor.setTask(Text.text("Processing ..."));
monitor.progress(25.0f);
if (monitor.isCanceled()) {
return null; // user has canceled this operation
}
// start process
ThiessenPolygonOperation operation = new ThiessenPolygonOperation();
operation.setAttributeMode(attributes);
if (clipArea != null) {
operation.setClipArea(clipArea);
}
SimpleFeatureCollection resultFc = operation.execute(inputFeatures);
// end process
monitor.setTask(Text.text("Encoding result"));
monitor.progress(90.0f);
MapString, Object resultMap = new HashMapString, Object();
resultMap.put(ThiessenPolygonProcessFactory.RESULT.key, resultFc);
monitor.complete(); // same as 100.0f
return resultMap;
} catch (Exception eek) {
monitor.exceptionOccurred(eek);
return null;
} finally {
monitor.dispose();
}
}
}
Q3: 用JAVA语言在网页里实现加减乘除算法的源代码要怎么写吖?!
public class Excer{
public static void main(String args[])
{
Excer ex=new Excer();
int x=0;
int y=0;
ex.math(x,y);
}
void math(int x,int y){
MyMath mm = new MyMath();
System.out.println("x="+x+" ,y="+y);
System.out.println("x+y="+mm.plus(x,y));
System.out.println("x-y="+mm.minus(x,y));
System.out.println("x*y="+mm.multi(x,y));
System.out.println("x/y="+mm.div(x,y));
}
}
class MyMath
{
int plus(int a,int b)
{
return(a+b);
}
int minus(int a,int b)
{
return(a-b);
}
int multi(int a,int b)
{
return(a*b);
}
float div(int a,int b)
{
return ((float)a/b);
}
}
Q4: JAVA 实现算法
package huda.laogao.ON_20121216;
import java.util.*;
public class GetEquation {
ArrayListInteger params = null;// 进行加减java算法如何实现代码的数java算法如何实现代码,长度设为n
int result = 0;// 结果
public GetEquation(ArrayListInteger params, int result) {
this.params = params;
this.result = result;
}
public void run() {
int size = params.size();
if (size == 1) {
if (params.get(0) == result)
System.out.println(result + "=" + result);
else
System.out.println("Invalid");
return;
}
int[][] matrix = getMatrix(size - 1);
int m = matrix.length;// 行数
int count = 0;// 记录符合结果的组合数
for (int i = 0; i m; i++) {
int now = params.get(0);// 进行加减的结果java算法如何实现代码,初始为第一个值
// 从第二个数开始进行加或减java算法如何实现代码,加的话就相当于该数乘上1,然后加到结果上,
// 减的就相当于该数乘上-1,然后加到结果上
for (int j = 1; j size; j++) {
now += matrix[i][j - 1] * params.get(j);
}
// System.out.println(now);
// 判断结果
if (now == result) {
count++;// 组合数加1
System.out.print(params.get(0));
for (int j = 1; j size; j++) {
if (matrix[i][j - 1] == 1)
System.out.print("+" + params.get(j));
else
System.out.print("-" + params.get(j));
}// for j
System.out.println("=" + result);
}// if
}// for i
if (count == 0)
System.out.println("Invalid");
}
public int[][] getMatrix(int n) {
int m = (int) Math.pow(2, n);
int matrix[][] = new int[m][n];
for (int i = 0; i n; i++) {
int num = (int) Math.pow(2, i + 1);
// 总共分 2^(i+1)块,如i=0,即该矩阵的第一列,可分为2块,上一块取1,下一块取-1
int size = (int) Math.pow(2, n - i - 1);
// 每块的大小为2^(n-i-1),如n=3,i=0,每块的大小为4,即前4个为1,后4个为-1
int flag = 1;// 先为+
for (int j = 0; j num; j++) {
for (int k = 0; k size; k++) {
matrix[k + j * size][i] = flag;
}
flag *= -1;
}
}
return matrix;
}
public void print(int[][] matrix) {
for (int i = 0; i matrix.length; i++) {
for (int j = 0; j matrix[i].length; j++) {
System.out.print(matrix[i][j] + "\t");
}
System.out.println();
}
}
public static void main(String args[]) {
ArrayListInteger params = new ArrayListInteger();
params.add(1);
params.add(2);
params.add(3);
params.add(4);
int result = 10;
GetEquation ge = new GetEquation(params, result);
ge.run();
}
}
运行结果为:1+2+3+4=10
注:难点为获取加减矩阵,可辅助print()函数帮助理解
望采纳
Q5: 如何用Java实现遗传算法?
通过遗传算法走迷宫。虽然图1和图2均成功走出迷宫,但是图1比图2的路径长的多,且复杂,遗传算法可以计算出有多少种可能性,并选择其中最简洁的作为运算结果。
示例图1:
示例图2:
实现代码:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
/**
* 用遗传算法走迷宫
*
* @author Orisun
*
*/
public class GA {
int gene_len; // 基因长度
int chrom_len; // 染色体长度
int population; // 种群大小
double cross_ratio; // 交叉率
double muta_ratio; // 变异率
int iter_limit; // 最多进化的代数
Listboolean[] individuals; // 存储当代种群的染色体
Labyrinth labyrinth;
int width; //迷宫一行有多少个格子
int height; //迷宫有多少行
public class BI {
double fitness;
boolean[] indv;
public BI(double f, boolean[] ind) {
fitness = f;
indv = ind;
}
public double getFitness() {
return fitness;
}
public boolean[] getIndv() {
return indv;
}
}
ListBI best_individual; // 存储每一代中最优秀的个体
public GA(Labyrinth labyrinth) {
this.labyrinth=labyrinth;
this.width = labyrinth.map[0].length;
this.height = labyrinth.map.length;
chrom_len = 4 * (width+height);
gene_len = 2;
population = 20;
cross_ratio = 0.83;
muta_ratio = 0.002;
iter_limit = 300;
individuals = new ArrayListboolean[](population);
best_individual = new ArrayListBI(iter_limit);
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public double getCross_ratio() {
return cross_ratio;
}
public ListBI getBest_individual() {
return best_individual;
}
public Labyrinth getLabyrinth() {
return labyrinth;
}
public void setLabyrinth(Labyrinth labyrinth) {
this.labyrinth = labyrinth;
}
public void setChrom_len(int chrom_len) {
this.chrom_len = chrom_len;
}
public void setPopulation(int population) {
this.population = population;
}
public void setCross_ratio(double cross_ratio) {
this.cross_ratio = cross_ratio;
}
public void setMuta_ratio(double muta_ratio) {
this.muta_ratio = muta_ratio;
}
public void setIter_limit(int iter_limit) {
this.iter_limit = iter_limit;
}
// 初始化种群
public void initPopulation() {
Random r = new Random(System.currentTimeMillis());
for (int i = 0; i population; i++) {
int len = gene_len * chrom_len;
boolean[] ind = new boolean[len];
for (int j = 0; j len; j++)
ind[j] = r.nextBoolean();
individuals.add(ind);
}
}
// 交叉
public void cross(boolean[] arr1, boolean[] arr2) {
Random r = new Random(System.currentTimeMillis());
int length = arr1.length;
int slice = 0;
do {
slice = r.nextInt(length);
} while (slice == 0);
if (slice length / 2) {
for (int i = 0; i slice; i++) {
boolean tmp = arr1[i];
arr1[i] = arr2[i];
arr2[i] = tmp;
}
} else {
for (int i = slice; i length; i++) {
boolean tmp = arr1[i];
arr1[i] = arr2[i];
arr2[i] = tmp;
}
}
}
// 变异
public void mutation(boolean[] individual) {
int length = individual.length;
Random r = new Random(System.currentTimeMillis());
individual[r.nextInt(length)] ^= false;
}
// 轮盘法选择下一代,并返回当代最高的适应度值
public double selection() {
boolean[][] next_generation = new boolean[population][]; // 下一代
int length = gene_len * chrom_len;
for (int i = 0; i population; i++)
next_generation[i] = new boolean[length];
double[] cumulation = new double[population];
int best_index = 0;
double max_fitness = getFitness(individuals.get(best_index));
cumulation[0] = max_fitness;
for (int i = 1; i population; i++) {
double fit = getFitness(individuals.get(i));
cumulation[i] = cumulation[i - 1] + fit;
// 寻找当代的最优个体
if (fit max_fitness) {
best_index = i;
max_fitness = fit;
}
}
Random rand = new Random(System.currentTimeMillis());
for (int i = 0; i population; i++)
next_generation[i] = individuals.get(findByHalf(cumulation,
rand.nextDouble() * cumulation[population - 1]));
// 把当代的最优个体及其适应度放到best_individual中
BI bi = new BI(max_fitness, individuals.get(best_index));
// printPath(individuals.get(best_index));
//System.out.println(max_fitness);
best_individual.add(bi);
// 新一代作为当前代
for (int i = 0; i population; i++)
individuals.set(i, next_generation[i]);
return max_fitness;
}
// 折半查找
public int findByHalf(double[] arr, double find) {
if (find 0 || find == 0 || find arr[arr.length - 1])
return -1;
int min = 0;
int max = arr.length - 1;
int medium = min;
do {
if (medium == (min + max) / 2)
break;
medium = (min + max) / 2;
if (arr[medium] find)
min = medium;
else if (arr[medium] find)
max = medium;
else
return medium;
} while (min max);
return max;
}
// 计算适应度
public double getFitness(boolean[] individual) {
int length = individual.length;
// 记录当前的位置,入口点是(1,0)
int x = 1;
int y = 0;
// 根据染色体中基因的指导向前走
for (int i = 0; i length; i++) {
boolean b1 = individual[i];
boolean b2 = individual[++i];
// 00向左走
if (b1 == false b2 == false) {
if (x 0 labyrinth.map[y][x - 1] == true) {
x--;
}
}
// 01向右走
else if (b1 == false b2 == true) {
if (x + 1 width labyrinth.map[y][x + 1] == true) {
x++;
}
}
// 10向上走
else if (b1 == true b2 == false) {
if (y 0 labyrinth.map[y - 1][x] == true) {
y--;
}
}
// 11向下走
else if (b1 == true b2 == true) {
if (y + 1 height labyrinth.map[y + 1][x] == true) {
y++;
}
}
}
int n = Math.abs(x - labyrinth.x_end) + Math.abs(y -labyrinth.y_end) + 1;
// if(n==1)
// printPath(individual);
return 1.0 / n;
}
// 运行遗传算法
public boolean run() {
// 初始化种群
initPopulation();
Random rand = new Random(System.currentTimeMillis());
boolean success = false;
while (iter_limit-- 0) {
// 打乱种群的顺序
Collections.shuffle(individuals);
for (int i = 0; i population - 1; i += 2) {
// 交叉
if (rand.nextDouble() cross_ratio) {
cross(individuals.get(i), individuals.get(i + 1));
}
// 变异
if (rand.nextDouble() muta_ratio) {
mutation(individuals.get(i));
}
}
// 种群更替
if (selection() == 1) {
success = true;
break;
}
}
return success;
}
// public static void main(String[] args) {
// GA ga = new GA(8, 8);
// if (!ga.run()) {
// System.out.println("没有找到走出迷宫的路径.");
// } else {
// int gen = ga.best_individual.size();
// boolean[] individual = ga.best_individual.get(gen - 1).indv;
// System.out.println(ga.getPath(individual));
// }
// }
// 根据染色体打印走法
public String getPath(boolean[] individual) {
int length = individual.length;
int x = 1;
int y = 0;
LinkedListString stack=new LinkedListString();
for (int i = 0; i length; i++) {
boolean b1 = individual[i];
boolean b2 = individual[++i];
if (b1 == false b2 == false) {
if (x 0 labyrinth.map[y][x - 1] == true) {
x--;
if(!stack.isEmpty() stack.peek()=="右")
stack.poll();
else
stack.push("左");
}
} else if (b1 == false b2 == true) {
if (x + 1 width labyrinth.map[y][x + 1] == true) {
x++;
if(!stack.isEmpty() stack.peek()=="左")
stack.poll();
else
stack.push("右");
}
} else if (b1 == true b2 == false) {
if (y 0 labyrinth.map[y - 1][x] == true) {
y--;
if(!stack.isEmpty() stack.peek()=="下")
stack.poll();
else
stack.push("上");
}
} else if (b1 == true b2 == true) {
if (y + 1 height labyrinth.map[y + 1][x] == true) {
y++;
if(!stack.isEmpty() stack.peek()=="上")
stack.poll();
else
stack.push("下");
}
}
}
StringBuilder sb=new StringBuilder(length/4);
IteratorString iter=stack.descendingIterator();
while(iter.hasNext())
sb.append(iter.next());
return sb.toString();
}
}
java算法如何实现代码的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于java算法总结、java算法如何实现代码的信息别忘了在本站进行查找喔。







