# 从零开始学习Java神经网络、自然语言处理和语音识别，附详解和简易版GPT，语音识别完整代码示例解析

## 二、实现简单神经网络

public class Neuron {
private double output; //神经元的输出值
private double error; //神经元的误差
//计算神经元的输出值
public double calculateOutput(double[] inputs, double[] weights) {
double sum = 0;
for (int i = 0; i < inputs.length; i++) {
sum += inputs[i] * weights[i];
}
output = sigmoid(sum);
return output;
}
//计算sigmoid函数
private double sigmoid(double x) {
return 1 / (1 + Math.exp(-x));
}
//设置神经元的误差
public void setError(double error) {
this.error = error;
}
//获取神经元的误差
public double getError() {
return error;
}
//获取神经元的输出值
public double getOutput() {
return output;
}
}


public class NetworkLayer {
private int numberOfNeurons; //神经网络层的神经元数量
private Neuron[] neurons; //神经网络层的神经元数组
//初始化神经网络层
public NetworkLayer(int numberOfNeurons, int numberOfInputsPerNeuron) {
this.numberOfNeurons = numberOfNeurons;
neurons = new Neuron[numberOfNeurons];
for (int i = 0; i < numberOfNeurons; i++) {
neurons[i] = new Neuron();
}
}
//计算神经网络层的输出值
public double[] calculateLayerOutput(double[] inputs) {
double[] outputs = new double[numberOfNeurons];
for (int i = 0; i < numberOfNeurons; i++) {
outputs[i] = neurons[i].calculateOutput(inputs, weights[i]);
}
return outputs;
}
//计算隐藏层的误差
public void calculateHiddenLayerError(NetworkLayer outputLayer, double[] outputError) {
double[] error = new double[numberOfNeurons];
for (int i = 0; i < numberOfNeurons; i++) {
double sum = 0;
for (int j = 0; j < outputLayer.getNumberOfNeurons(); j++) {
sum += outputError[j] * outputLayer.getNeurons()[j].getWeights()[i];
}
error[i] = neurons[i].getOutput() * (1 - neurons[i].getOutput()) * sum;
}
for (int i = 0; i < numberOfNeurons; i++) {
neurons[i].setError(error[i]);
}
//更新神经元的权重值
public void updateWeights(double[] inputs, double learningRate) {
for (int i = 0; i < numberOfNeurons; i++) {
double[] weights = neurons[i].getWeights();
for (int j = 0; j < inputs.length; j++) {
weights[j] += learningRate * neurons[i].getError() * inputs[j];
}
}
}
//获取神经元的数量
public int getNumberOfNeurons() {
return numberOfNeurons;
}
//获取神经元数组
public Neuron[] getNeurons() {
return neurons;
}
}


public class NeuralNetwork {
private NetworkLayer inputLayer;
private NetworkLayer hiddenLayer;
private NetworkLayer outputLayer;
//初始化神经网络
public NeuralNetwork() {
inputLayer = new NetworkLayer(3, 4);
hiddenLayer = new NetworkLayer(4, 3);
outputLayer = new NetworkLayer(1, 4);
}
//计算神经网络的输出值
public double calculateOutput(double[] inputs) {
double[] hiddenLayerOutput = hiddenLayer.calculateLayerOutput(inputs);
return outputLayer.calculateLayerOutput(hiddenLayerOutput)[0];
}
//训练神经网络
public void train(double[][] inputs, double[] outputs, double learningRate, int epochs) {
for (int epoch = 0; epoch < epochs; epoch++) {
double error = 0;
for (int i = 0; i < inputs.length; i++) {
double[] hiddenLayerOutput = hiddenLayer.calculateLayerOutput(inputs[i]);
double[] outputLayerOutput = outputLayer.calculateLayerOutput(hiddenLayerOutput);
double outputError = outputs[i] - outputLayerOutput[0];
outputLayer.getNeurons()[0].setError(outputError);
hiddenLayer.calculateHiddenLayerError(outputLayer, outputLayer.getNeurons()[0].getWeights());
hiddenLayer.updateWeights(inputs[i], learningRate);
outputLayer.updateWeights(hiddenLayerOutput, learningRate);
error += Math.pow(outputError, 2);
}
error /= inputs.length;
System.out.println("Epoch " + epoch + " Error: " + error);
}
}
}


## 三、Java自然语言处理示例代码（简易版GPT）

CoreNLP示例

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import edu.stanford.nlp.ling.CoreAnnotations;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.pipeline.StanfordCoreNLP;
import edu.stanford.nlp.util.CoreMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import edu.stanford.nlp.ling.CoreAnnotations;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.pipeline.Annotation;
import edu.stanford.nlp.pipeline.StanfordCoreNLP;
import edu.stanford.nlp.util.CoreMap;
public class NLPExample {
public static void main(String[] args) {
// 要处理的文本
String text = "我有一只名叫小陈的猫。她喜欢在csdn发博客。";
// 提取名词短语
List<String> nounPhrases = extractNounPhrases(text);
// 输出结果
System.out.println(nounPhrases);
}
public static List<String> extractNounPhrases(String text) {
List<String> nounPhrases = new ArrayList<String>();
// 创建Stanford CoreNLP对象
Properties props = new Properties();
props.setProperty("annotators", "tokenize, ssplit, pos");
StanfordCoreNLP pipeline = new StanfordCoreNLP(props);
// 对文本进行注释
Annotation document = new Annotation(text);
pipeline.annotate(document);
// 获取句子列表
List<CoreMap> sentences = document.get(CoreAnnotations.SentencesAnnotation.class);
// 遍历每个句子，提取名词短语
for (CoreMap sentence : sentences) {
String sentenceText = sentence.get(CoreAnnotations.TextAnnotation.class);
List<CoreLabel> tokens = sentence.get(CoreAnnotations.TokensAnnotation.class);
for (int i = 0; i < tokens.size(); i++) {
CoreLabel token = tokens.get(i);
String pos = token.get(CoreAnnotations.PartOfSpeechAnnotation.class);
// 如果当前标记是一个名词，则收集它的名词短语
if (pos.startsWith("NN")) {
String nounPhrase = token.get(CoreAnnotations.TextAnnotation.class);
int j = i + 1;
while (j < tokens.size()) {
CoreLabel nextToken = tokens.get(j);
String nextPos = nextToken.get(CoreAnnotations.PartOfSpeechAnnotation.class);
if (nextPos.startsWith("NN")) {
nounPhrase += " " + nextToken.get(CoreAnnotations.TextAnnotation.class);
j++;
} else {
break;
}
}
}
}
}
return nounPhrases;
}
}


## 四、Java简易版语音识别示例代码

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import edu.cmu.sphinx.api.Configuration;
import edu.cmu.sphinx.api.LiveSpeechRecognizer;
public class SpeechRecognition {
public static void main(String[] args) throws Exception {
// 配置语音识别引擎
Configuration configuration = new Configuration();
// 设置语音识别引擎使用的语言模型文件和字典文件
configuration.setAcousticModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us");
configuration.setDictionaryPath("resource:/edu/cmu/sphinx/models/en-us/cmudict-en-us.dict");
// 创建语音识别器
LiveSpeechRecognizer recognizer = new LiveSpeechRecognizer(configuration);
// 开始语音识别
recognizer.startRecognition(true);
// 获取识别结果
while (true) {
String result = recognizer.getResult().getHypothesis();
System.out.println("识别结果：" + result);
}
// 停止语音识别
recognizer.stopRecognition();
}
// 读取音频文件
public static AudioInputStream getAudioInputStream(String filename) throws IOException {
File file = new File(filename);
InputStream inputStream = new FileInputStream(file);
return AudioSystem.getAudioInputStream(inputStream);
}
// 保存音频文件
public static void saveAudioFile(AudioInputStream audioInputStream, String filename, AudioFileFormat.Type fileType) throws IOException {
File file = new File(filename);
AudioSystem.write(audioInputStream, fileType, file);
}
}


## 五、结论

|
23小时前
|

Java多线程基础-11：工厂模式及代码案例之线程池（二）

11 0
|
23小时前
|

Java多线程基础-11：工厂模式及代码案例之线程池（一）

13 2
|
23小时前
|
Java 调度
Java多线程基础-10：代码案例之定时器（二）
Java 多线程基础中，定时器（Timer）的实现通常使用 PriorityBlockingQueue 和 wait/notify 机制来管理任务。
8 0
|
1天前
|

Java多线程基础-10：代码案例之定时器（一）
Timer 是 Java 中的一个定时器类，用于在指定延迟后执行指定的任务。它常用于实现定时任务，例如在网络通信中设置超时或定期清理数据。Timer 的核心方法是 schedule()，它可以安排任务在延迟一段时间后执行。
12 1
|
1天前
|

Java多线程基础-9：代码案例之阻塞队列（二）
Java多线程基础教程系列中，介绍了如何实现一个简单的阻塞队列（非泛型版本）。
10 0
|
1天前
|

Java多线程基础-9：代码案例之阻塞队列（一）

15 0
|
2天前
|

【5月更文挑战第16天】🏆本文收录于「滚雪球学Java」专栏，专业攻坚指数级提升，希望能够助你一臂之力，帮你早日登顶实现财富自由🚀；同时，欢迎大家关注&&收藏&&订阅！持续更新中，up！up！up！！
15 2
|
3天前
|
Java API
Java Lambda表达式：简化代码、提升效率
【5月更文挑战第25天】本文将深入探讨Java中的Lambda表达式，解析它的概念、语法结构以及在实际编程中的应用。我们将通过实例来展示Lambda表达式如何帮助我们编写更简洁、更高效的代码，并讨论其对Java开发的影响和价值。
8 2
|
5天前
|
SQL Java 数据处理

21 0
|
5天前
|
Java
【JAVA学习之路 | 进阶篇】Record(记录)与密封类(sealed)
【JAVA学习之路 | 进阶篇】Record(记录)与密封类(sealed)
13 1