Skip to content

Commit

Permalink
HiddenMarkovModel构造时备份参数 fix #1530
Browse files Browse the repository at this point in the history
  • Loading branch information
hankcs committed Aug 15, 2020
1 parent cb2d20f commit ef44aad
Showing 1 changed file with 29 additions and 3 deletions.
32 changes: 29 additions & 3 deletions src/main/java/com/hankcs/hanlp/model/hmm/HiddenMarkovModel.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

import com.hankcs.hanlp.utility.MathUtility;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
Expand Down Expand Up @@ -44,9 +45,9 @@ public abstract class HiddenMarkovModel
*/
public HiddenMarkovModel(float[] start_probability, float[][] transition_probability, float[][] emission_probability)
{
this.start_probability = start_probability;
this.transition_probability = transition_probability;
this.emission_probability = emission_probability;
this.start_probability = (float[]) deepCopy(start_probability);
this.transition_probability = (float[][]) deepCopy(transition_probability);
this.emission_probability = (float[][]) deepCopy(emission_probability);
}

/**
Expand Down Expand Up @@ -298,4 +299,29 @@ protected static boolean similar(float[] A, float[] B)
if (Math.abs(A[i] - B[i]) > eta) return false;
return true;
}

protected static Object deepCopy(Object object)
{
if (object == null)
{
return null;
}
try
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(object);
oos.flush();
oos.close();
bos.close();

byte[] byteData = bos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(byteData);
return new ObjectInputStream(bais).readObject();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
}

0 comments on commit ef44aad

Please sign in to comment.