code
stringlengths
67
466k
docstring
stringlengths
1
13.2k
private String getCacheManagerName(String beanName) { if (beanName.length() > CACHE_MANAGER_SUFFIX.length() && StringUtils.endsWithIgnoreCase(beanName, CACHE_MANAGER_SUFFIX)) { return beanName.substring(0, beanName.length() - CACHE_MANAGER_SUFFIX.length()); } return beanName; }
Get the name of a {@link CacheManager} based on its {@code beanName}. @param beanName the name of the {@link CacheManager} bean @return a name for the given cache manager
public static void removeDuplicatesFromOutputDirectory(File outputDirectory, File originDirectory) { if (originDirectory.isDirectory()) { for (String name : originDirectory.list()) { File targetFile = new File(outputDirectory, name); if (targetFile.exists() && targetFile.canWrite()) { if (!targetFile.isDirectory()) { targetFile.delete(); } else { FileUtils.removeDuplicatesFromOutputDirectory(targetFile, new File(originDirectory, name)); } } } } }
Utility to remove duplicate files from an "output" directory if they already exist in an "origin". Recursively scans the origin directory looking for files (not directories) that exist in both places and deleting the copy. @param outputDirectory the output directory @param originDirectory the origin directory
public <T> BindResult<T> bind(String name, Class<T> target) { return bind(name, Bindable.of(target)); }
Bind the specified target {@link Class} using this binder's {@link ConfigurationPropertySource property sources}. @param name the configuration property name to bind @param target the target class @param <T> the bound type @return the binding result (never {@code null}) @see #bind(ConfigurationPropertyName, Bindable, BindHandler)
public <T> BindResult<T> bind(String name, Bindable<T> target) { return bind(ConfigurationPropertyName.of(name), target, null); }
Bind the specified target {@link Bindable} using this binder's {@link ConfigurationPropertySource property sources}. @param name the configuration property name to bind @param target the target bindable @param <T> the bound type @return the binding result (never {@code null}) @see #bind(ConfigurationPropertyName, Bindable, BindHandler)
public <T> BindResult<T> bind(String name, Bindable<T> target, BindHandler handler) { return bind(ConfigurationPropertyName.of(name), target, handler); }
Bind the specified target {@link Bindable} using this binder's {@link ConfigurationPropertySource property sources}. @param name the configuration property name to bind @param target the target bindable @param handler the bind handler (may be {@code null}) @param <T> the bound type @return the binding result (never {@code null})
public <T> BindResult<T> bind(ConfigurationPropertyName name, Bindable<T> target, BindHandler handler) { Assert.notNull(name, "Name must not be null"); Assert.notNull(target, "Target must not be null"); handler = (handler != null) ? handler : BindHandler.DEFAULT; Context context = new Context(); T bound = bind(name, target, handler, context, false); return BindResult.of(bound); }
Bind the specified target {@link Bindable} using this binder's {@link ConfigurationPropertySource property sources}. @param name the configuration property name to bind @param target the target bindable @param handler the bind handler (may be {@code null}) @param <T> the bound type @return the binding result (never {@code null})
public static Binder get(Environment environment) { return new Binder(ConfigurationPropertySources.get(environment), new PropertySourcesPlaceholdersResolver(environment)); }
Create a new {@link Binder} instance from the specified environment. @param environment the environment source (must have attached {@link ConfigurationPropertySources}) @return a {@link Binder} instance
public SQLDialect determineSqlDialect(DataSource dataSource) { if (this.sqlDialect != null) { return this.sqlDialect; } return SqlDialectLookup.getDialect(dataSource); }
Determine the {@link SQLDialect} to use based on this configuration and the primary {@link DataSource}. @param dataSource the data source @return the {@code SQLDialect} to use for that {@link DataSource}
@SuppressWarnings("unchecked") public <A extends Annotation> A getAnnotation(Class<A> type) { for (Annotation annotation : this.annotations) { if (type.isInstance(annotation)) { return (A) annotation; } } return null; }
Return a single associated annotations that could affect binding. @param <A> the annotation type @param type annotation type @return the associated annotation or {@code null}
public Bindable<T> withAnnotations(Annotation... annotations) { return new Bindable<>(this.type, this.boxedType, this.value, (annotations != null) ? annotations : NO_ANNOTATIONS); }
Create an updated {@link Bindable} instance with the specified annotations. @param annotations the annotations @return an updated {@link Bindable}
public Bindable<T> withExistingValue(T existingValue) { Assert.isTrue( existingValue == null || this.type.isArray() || this.boxedType.resolve().isInstance(existingValue), () -> "ExistingValue must be an instance of " + this.type); Supplier<T> value = (existingValue != null) ? () -> existingValue : null; return new Bindable<>(this.type, this.boxedType, value, NO_ANNOTATIONS); }
Create an updated {@link Bindable} instance with an existing value. @param existingValue the existing value @return an updated {@link Bindable}
public Bindable<T> withSuppliedValue(Supplier<T> suppliedValue) { return new Bindable<>(this.type, this.boxedType, suppliedValue, NO_ANNOTATIONS); }
Create an updated {@link Bindable} instance with a value supplier. @param suppliedValue the supplier for the value @return an updated {@link Bindable}
@SuppressWarnings("unchecked") public static <T> Bindable<T> ofInstance(T instance) { Assert.notNull(instance, "Instance must not be null"); Class<T> type = (Class<T>) instance.getClass(); return of(type).withExistingValue(instance); }
Create a new {@link Bindable} of the type of the specified instance with an existing value equal to the instance. @param <T> the source type @param instance the instance (must not be {@code null}) @return a {@link Bindable} instance @see #of(ResolvableType) @see #withExistingValue(Object)
public static <T> Bindable<T> of(Class<T> type) { Assert.notNull(type, "Type must not be null"); return of(ResolvableType.forClass(type)); }
Create a new {@link Bindable} of the specified type. @param <T> the source type @param type the type (must not be {@code null}) @return a {@link Bindable} instance @see #of(ResolvableType)
public static <E> Bindable<List<E>> listOf(Class<E> elementType) { return of(ResolvableType.forClassWithGenerics(List.class, elementType)); }
Create a new {@link Bindable} {@link List} of the specified element type. @param <E> the element type @param elementType the list element type @return a {@link Bindable} instance
public static <E> Bindable<Set<E>> setOf(Class<E> elementType) { return of(ResolvableType.forClassWithGenerics(Set.class, elementType)); }
Create a new {@link Bindable} {@link Set} of the specified element type. @param <E> the element type @param elementType the set element type @return a {@link Bindable} instance
public static <K, V> Bindable<Map<K, V>> mapOf(Class<K> keyType, Class<V> valueType) { return of(ResolvableType.forClassWithGenerics(Map.class, keyType, valueType)); }
Create a new {@link Bindable} {@link Map} of the specified key and value type. @param <K> the key type @param <V> the value type @param keyType the map key type @param valueType the map value type @return a {@link Bindable} instance
public static <T> Bindable<T> of(ResolvableType type) { Assert.notNull(type, "Type must not be null"); ResolvableType boxedType = box(type); return new Bindable<>(type, boxedType, null, NO_ANNOTATIONS); }
Create a new {@link Bindable} of the specified type. @param <T> the source type @param type the type (must not be {@code null}) @return a {@link Bindable} instance @see #of(Class)
public static Origin get(PropertySource<?> propertySource, String name) { Origin origin = OriginLookup.getOrigin(propertySource, name); return (origin != null) ? origin : new PropertySourceOrigin(propertySource, name); }
Get an {@link Origin} for the given {@link PropertySource} and {@code propertyName}. Will either return an {@link OriginLookup} result or a {@link PropertySourceOrigin}. @param propertySource the origin property source @param name the property name @return the property origin
public static Validator get(ApplicationContext applicationContext, Validator validator) { if (validator != null) { return wrap(validator, false); } return getExistingOrCreate(applicationContext); }
Return a {@link Validator} that only implements the {@link Validator} interface, wrapping it if necessary. <p> If the specified {@link Validator} is not {@code null}, it is wrapped. If not, a {@link javax.validation.Validator} is retrieved from the context and wrapped. Otherwise, a new default validator is created. @param applicationContext the application context @param validator an existing validator to use or {@code null} @return the validator to use
public static EntityScanPackages get(BeanFactory beanFactory) { // Currently we only store a single base package, but we return a list to // allow this to change in the future if needed try { return beanFactory.getBean(BEAN, EntityScanPackages.class); } catch (NoSuchBeanDefinitionException ex) { return NONE; } }
Return the {@link EntityScanPackages} for the given bean factory. @param beanFactory the source bean factory @return the {@link EntityScanPackages} for the bean factory (never {@code null})
public static void register(BeanDefinitionRegistry registry, String... packageNames) { Assert.notNull(registry, "Registry must not be null"); Assert.notNull(packageNames, "PackageNames must not be null"); register(registry, Arrays.asList(packageNames)); }
Register the specified entity scan packages with the system. @param registry the source registry @param packageNames the package names to register
public static void register(BeanDefinitionRegistry registry, Collection<String> packageNames) { Assert.notNull(registry, "Registry must not be null"); Assert.notNull(packageNames, "PackageNames must not be null"); if (registry.containsBeanDefinition(BEAN)) { BeanDefinition beanDefinition = registry.getBeanDefinition(BEAN); ConstructorArgumentValues constructorArguments = beanDefinition .getConstructorArgumentValues(); constructorArguments.addIndexedArgumentValue(0, addPackageNames(constructorArguments, packageNames)); } else { GenericBeanDefinition beanDefinition = new GenericBeanDefinition(); beanDefinition.setBeanClass(EntityScanPackages.class); beanDefinition.getConstructorArgumentValues().addIndexedArgumentValue(0, StringUtils.toStringArray(packageNames)); beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); registry.registerBeanDefinition(BEAN, beanDefinition); } }
Register the specified entity scan packages with the system. @param registry the source registry @param packageNames the package names to register
public MongoClient createMongoClient(MongoClientOptions options) { Integer embeddedPort = getEmbeddedPort(); if (embeddedPort != null) { return createEmbeddedMongoClient(options, embeddedPort); } return createNetworkMongoClient(options); }
Creates a {@link MongoClient} using the given {@code options}. If the environment contains a {@code local.mongo.port} property, it is used to configure a client to an embedded MongoDB instance. @param options the options @return the Mongo client
private Artifact getSourceArtifact() { Artifact sourceArtifact = getArtifact(this.classifier); return (sourceArtifact != null) ? sourceArtifact : this.project.getArtifact(); }
Return the source {@link Artifact} to repackage. If a classifier is specified and an artifact with that classifier exists, it is used. Otherwise, the main artifact is used. @return the source artifact to repackage
protected String[] getSpringConfigLocations() { String[] locations = getStandardConfigLocations(); for (int i = 0; i < locations.length; i++) { String extension = StringUtils.getFilenameExtension(locations[i]); locations[i] = locations[i].substring(0, locations[i].length() - extension.length() - 1) + "-spring." + extension; } return locations; }
Return the spring config locations for this system. By default this method returns a set of locations based on {@link #getStandardConfigLocations()}. @return the spring config locations @see #getSpringInitializationConfig()
protected void extractResult(Session session, Health.Builder builder) throws Exception { Result result = session.query(CYPHER, Collections.emptyMap()); builder.up().withDetail("nodes", result.queryResults().iterator().next().get("nodes")); }
Provide health details using the specified {@link Session} and {@link Builder Builder}. @param session the session to use to execute a cypher statement @param builder the builder to add details to @throws Exception if getting health details failed
@Bean public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { return http .authorizeExchange() .matchers(PathRequest.toStaticResources().atCommonLocations()).permitAll() .pathMatchers("/foo", "/bar") .authenticated().and() .formLogin().and() .build(); }
tag::configuration[]
@Override public List<ForeignKey<Record, ?>> getReferences() { return Arrays.<ForeignKey<Record, ?>>asList(Keys.FK_B2BS_BOOK_STORE, Keys.FK_B2BS_BOOK); }
{@inheritDoc}
@SuppressWarnings("unchecked") protected Class<? extends T> getCauseType() { return (Class<? extends T>) ResolvableType .forClass(AbstractFailureAnalyzer.class, getClass()).resolveGeneric(); }
Return the cause type being handled by the analyzer. By default the class generic is used. @return the cause type
private Map<String, Object> flatten(Map<String, Object> map) { Map<String, Object> result = new LinkedHashMap<>(); flatten(null, result, map); return result; }
Flatten the map keys using period separator. @param map the map that should be flattened @return the flattened map
public String getWarningReport() { Map<String, List<PropertyMigration>> content = getContent( LegacyProperties::getRenamed); if (content.isEmpty()) { return null; } StringBuilder report = new StringBuilder(); report.append(String.format("%nThe use of configuration keys that have been " + "renamed was found in the environment:%n%n")); append(report, content); report.append(String.format("%n")); report.append("Each configuration key has been temporarily mapped to its " + "replacement for your convenience. To silence this warning, please " + "update your configuration to use the new keys."); report.append(String.format("%n")); return report.toString(); }
Return a report for all the properties that were automatically renamed. If no such properties were found, return {@code null}. @return a report with the configurations keys that should be renamed
public String getErrorReport() { Map<String, List<PropertyMigration>> content = getContent( LegacyProperties::getUnsupported); if (content.isEmpty()) { return null; } StringBuilder report = new StringBuilder(); report.append(String.format("%nThe use of configuration keys that are no longer " + "supported was found in the environment:%n%n")); append(report, content); report.append(String.format("%n")); report.append("Please refer to the migration guide or reference guide for " + "potential alternatives."); report.append(String.format("%n")); return report.toString(); }
Return a report for all the properties that are no longer supported. If no such properties were found, return {@code null}. @return a report with the configurations keys that are no longer supported
public void setDataSource(XADataSource dataSource) { this.dataSource = dataSource; setClassName(DirectXADataSource.class.getName()); setDriverProperties(new Properties()); }
Set the {@link XADataSource} directly, instead of calling {@link #setClassName(String)}. @param dataSource the data source to use
public void recordConditionEvaluation(String source, Condition condition, ConditionOutcome outcome) { Assert.notNull(source, "Source must not be null"); Assert.notNull(condition, "Condition must not be null"); Assert.notNull(outcome, "Outcome must not be null"); this.unconditionalClasses.remove(source); if (!this.outcomes.containsKey(source)) { this.outcomes.put(source, new ConditionAndOutcomes()); } this.outcomes.get(source).add(condition, outcome); this.addedAncestorOutcomes = false; }
Record the occurrence of condition evaluation. @param source the source of the condition (class or method name) @param condition the condition evaluated @param outcome the condition outcome
public void recordExclusions(Collection<String> exclusions) { Assert.notNull(exclusions, "exclusions must not be null"); this.exclusions.addAll(exclusions); }
Records the names of the classes that have been excluded from condition evaluation. @param exclusions the names of the excluded classes
public void recordEvaluationCandidates(List<String> evaluationCandidates) { Assert.notNull(evaluationCandidates, "evaluationCandidates must not be null"); this.unconditionalClasses.addAll(evaluationCandidates); }
Records the names of the classes that are candidates for condition evaluation. @param evaluationCandidates the names of the classes whose conditions will be evaluated
public Map<String, ConditionAndOutcomes> getConditionAndOutcomesBySource() { if (!this.addedAncestorOutcomes) { this.outcomes.forEach((source, sourceOutcomes) -> { if (!sourceOutcomes.isFullMatch()) { addNoMatchOutcomeToAncestors(source); } }); this.addedAncestorOutcomes = true; } return Collections.unmodifiableMap(this.outcomes); }
Returns condition outcomes from this report, grouped by the source. @return the condition outcomes
public Set<String> getUnconditionalClasses() { Set<String> filtered = new HashSet<>(this.unconditionalClasses); filtered.removeAll(this.exclusions); return Collections.unmodifiableSet(filtered); }
Returns the names of the classes that were evaluated but were not conditional. @return the names of the unconditional classes
public static ConditionEvaluationReport find(BeanFactory beanFactory) { if (beanFactory != null && beanFactory instanceof ConfigurableBeanFactory) { return ConditionEvaluationReport .get((ConfigurableListableBeanFactory) beanFactory); } return null; }
Attempt to find the {@link ConditionEvaluationReport} for the specified bean factory. @param beanFactory the bean factory (may be {@code null}) @return the {@link ConditionEvaluationReport} or {@code null}
public static ConditionEvaluationReport get( ConfigurableListableBeanFactory beanFactory) { synchronized (beanFactory) { ConditionEvaluationReport report; if (beanFactory.containsSingleton(BEAN_NAME)) { report = beanFactory.getBean(BEAN_NAME, ConditionEvaluationReport.class); } else { report = new ConditionEvaluationReport(); beanFactory.registerSingleton(BEAN_NAME, report); } locateParent(beanFactory.getParentBeanFactory(), report); return report; } }
Obtain a {@link ConditionEvaluationReport} for the specified bean factory. @param beanFactory the bean factory @return an existing or new {@link ConditionEvaluationReport}
public boolean createSchema() { List<Resource> scripts = getScripts("spring.datasource.schema", this.properties.getSchema(), "schema"); if (!scripts.isEmpty()) { if (!isEnabled()) { logger.debug("Initialization disabled (not running DDL scripts)"); return false; } String username = this.properties.getSchemaUsername(); String password = this.properties.getSchemaPassword(); runScripts(scripts, username, password); } return !scripts.isEmpty(); }
Create the schema if necessary. @return {@code true} if the schema was created @see DataSourceProperties#getSchema()
public void initSchema() { List<Resource> scripts = getScripts("spring.datasource.data", this.properties.getData(), "data"); if (!scripts.isEmpty()) { if (!isEnabled()) { logger.debug("Initialization disabled (not running data scripts)"); return; } String username = this.properties.getDataUsername(); String password = this.properties.getDataPassword(); runScripts(scripts, username, password); } }
Initialize the schema if necessary. @see DataSourceProperties#getData()
public static boolean shouldEnable(Thread thread) { for (StackTraceElement element : thread.getStackTrace()) { if (isSkippedStackElement(element)) { return false; } } return true; }
Checks if a specific {@link StackTraceElement} in the current thread's stacktrace should cause devtools to be disabled. @param thread the current thread @return {@code true} if devtools should be enabled skipped
public static SpringConfigurationPropertySource from(PropertySource<?> source) { Assert.notNull(source, "Source must not be null"); PropertyMapper mapper = getPropertyMapper(source); if (isFullEnumerable(source)) { return new SpringIterableConfigurationPropertySource( (EnumerablePropertySource<?>) source, mapper); } return new SpringConfigurationPropertySource(source, mapper, getContainsDescendantOfForSource(source)); }
Create a new {@link SpringConfigurationPropertySource} for the specified {@link PropertySource}. @param source the source Spring {@link PropertySource} @return a {@link SpringConfigurationPropertySource} or {@link SpringIterableConfigurationPropertySource} instance
public Instant getInstant(String key) { String s = get(key); if (s != null) { try { return Instant.ofEpochMilli(Long.parseLong(s)); } catch (NumberFormatException ex) { // Not valid epoch time } } return null; }
Return the value of the specified property as an {@link Instant} or {@code null} if the value is not a valid {@link Long} representation of an epoch time. @param key the key of the property @return the property value
private void resetDefaultLocaleMapping(TomcatEmbeddedContext context) { context.addLocaleEncodingMappingParameter(Locale.ENGLISH.toString(), DEFAULT_CHARSET.displayName()); context.addLocaleEncodingMappingParameter(Locale.FRENCH.toString(), DEFAULT_CHARSET.displayName()); }
Override Tomcat's default locale mappings to align with other servers. See {@code org.apache.catalina.util.CharsetMapperDefault.properties}. @param context the context to reset
protected void configureContext(Context context, ServletContextInitializer[] initializers) { TomcatStarter starter = new TomcatStarter(initializers); if (context instanceof TomcatEmbeddedContext) { TomcatEmbeddedContext embeddedContext = (TomcatEmbeddedContext) context; embeddedContext.setStarter(starter); embeddedContext.setFailCtxIfServletStartFails(true); } context.addServletContainerInitializer(starter, NO_CLASSES); for (LifecycleListener lifecycleListener : this.contextLifecycleListeners) { context.addLifecycleListener(lifecycleListener); } for (Valve valve : this.contextValves) { context.getPipeline().addValve(valve); } for (ErrorPage errorPage : getErrorPages()) { new TomcatErrorPage(errorPage).addToContext(context); } for (MimeMappings.Mapping mapping : getMimeMappings()) { context.addMimeMapping(mapping.getExtension(), mapping.getMimeType()); } configureSession(context); new DisableReferenceClearingContextCustomizer().customize(context); for (TomcatContextCustomizer customizer : this.tomcatContextCustomizers) { customizer.customize(context); } }
Configure the Tomcat {@link Context}. @param context the Tomcat context @param initializers initializers to apply
public void setTldSkipPatterns(Collection<String> patterns) { Assert.notNull(patterns, "Patterns must not be null"); this.tldSkipPatterns = new LinkedHashSet<>(patterns); }
Set the patterns that match jars to ignore for TLD scanning. See Tomcat's catalina.properties for typical values. Defaults to a list drawn from that source. @param patterns the jar patterns to skip when scanning for TLDs etc
public void addTldSkipPatterns(String... patterns) { Assert.notNull(patterns, "Patterns must not be null"); this.tldSkipPatterns.addAll(Arrays.asList(patterns)); }
Add patterns that match jars to ignore for TLD scanning. See Tomcat's catalina.properties for typical values. @param patterns the additional jar patterns to skip when scanning for TLDs etc
public void setEngineValves(Collection<? extends Valve> engineValves) { Assert.notNull(engineValves, "Valves must not be null"); this.engineValves = new ArrayList<>(engineValves); }
Set {@link Valve}s that should be applied to the Tomcat {@link Engine}. Calling this method will replace any existing valves. @param engineValves the valves to set
public void setContextValves(Collection<? extends Valve> contextValves) { Assert.notNull(contextValves, "Valves must not be null"); this.contextValves = new ArrayList<>(contextValves); }
Set {@link Valve}s that should be applied to the Tomcat {@link Context}. Calling this method will replace any existing valves. @param contextValves the valves to set
public void addContextValves(Valve... contextValves) { Assert.notNull(contextValves, "Valves must not be null"); this.contextValves.addAll(Arrays.asList(contextValves)); }
Add {@link Valve}s that should be applied to the Tomcat {@link Context}. @param contextValves the valves to add
public void setTomcatProtocolHandlerCustomizers( Collection<? extends TomcatProtocolHandlerCustomizer<?>> tomcatProtocolHandlerCustomizer) { Assert.notNull(tomcatProtocolHandlerCustomizer, "TomcatProtocolHandlerCustomizers must not be null"); this.tomcatProtocolHandlerCustomizers = new ArrayList<>( tomcatProtocolHandlerCustomizer); }
Set {@link TomcatProtocolHandlerCustomizer}s that should be applied to the Tomcat {@link Connector}. Calling this method will replace any existing customizers. @param tomcatProtocolHandlerCustomizer the customizers to set @since 2.2.0
public void addAdditionalTomcatConnectors(Connector... connectors) { Assert.notNull(connectors, "Connectors must not be null"); this.additionalTomcatConnectors.addAll(Arrays.asList(connectors)); }
Add {@link Connector}s in addition to the default connector, e.g. for SSL or AJP @param connectors the connectors to add
public void setConnectionFactory(XAConnectionFactory connectionFactory) { this.connectionFactory = connectionFactory; setClassName(DirectXAConnectionFactory.class.getName()); setDriverProperties(new Properties()); }
Set the {@link XAConnectionFactory} directly, instead of calling {@link #setClassName(String)}. @param connectionFactory the connection factory to use
public static int binarySearch(BaseNode[] branches, BaseNode node) { int high = branches.length - 1; if (branches.length < 1) { return high; } int low = 0; while (low <= high) { int mid = (low + high) >>> 1; int cmp = branches[mid].compareTo(node); if (cmp < 0) low = mid + 1; else if (cmp > 0) high = mid - 1; else return mid; } return -(low + 1); }
二分查找 @param branches 数组 @param node 要查找的node @return 数组下标,小于0表示没找到
public long distance(String a, String b) { Long[] itemA = get(a); if (itemA == null) return Long.MAX_VALUE / 3; Long[] itemB = get(b); if (itemB == null) return Long.MAX_VALUE / 3; return ArrayDistance.computeAverageDistance(itemA, itemB); }
语义距离 @param a @param b @return
public static void recognition(List<Vertex> segResult, WordNet wordNetOptimum, WordNet wordNetAll) { StringBuilder sbName = new StringBuilder(); int appendTimes = 0; char[] charArray = wordNetAll.charArray; DoubleArrayTrie<Character>.LongestSearcher searcher = JapanesePersonDictionary.getSearcher(charArray); int activeLine = 1; int preOffset = 0; while (searcher.next()) { Character label = searcher.value; int offset = searcher.begin; String key = new String(charArray, offset, searcher.length); if (preOffset != offset) { if (appendTimes > 1 && sbName.length() > 2) // 日本人名最短为3字 { insertName(sbName.toString(), activeLine, wordNetOptimum, wordNetAll); } sbName.setLength(0); appendTimes = 0; } if (appendTimes == 0) { if (label == JapanesePersonDictionary.X) { sbName.append(key); ++appendTimes; activeLine = offset + 1; } } else { if (label == JapanesePersonDictionary.M) { sbName.append(key); ++appendTimes; } else { if (appendTimes > 1 && sbName.length() > 2) { insertName(sbName.toString(), activeLine, wordNetOptimum, wordNetAll); } sbName.setLength(0); appendTimes = 0; } } preOffset = offset + key.length(); } if (sbName.length() > 0) { if (appendTimes > 1) { insertName(sbName.toString(), activeLine, wordNetOptimum, wordNetAll); } } }
执行识别 @param segResult 粗分结果 @param wordNetOptimum 粗分结果对应的词图 @param wordNetAll 全词图
public static boolean isBadCase(String name) { Character label = JapanesePersonDictionary.get(name); if (label == null) return false; return label.equals(JapanesePersonDictionary.A); }
是否是bad case @param name @return
private static void insertName(String name, int activeLine, WordNet wordNetOptimum, WordNet wordNetAll) { if (isBadCase(name)) return; wordNetOptimum.insert(activeLine, new Vertex(Predefine.TAG_PEOPLE, name, new CoreDictionary.Attribute(Nature.nrj), WORD_ID), wordNetAll); }
插入日本人名 @param name @param activeLine @param wordNetOptimum @param wordNetAll
public Result train(String trainingFile, String developFile, String modelFile, final double compressRatio, final int maxIteration, final int threadNum) throws IOException { if (developFile == null) { developFile = trainingFile; } // 加载训练语料 TagSet tagSet = createTagSet(); MutableFeatureMap mutableFeatureMap = new MutableFeatureMap(tagSet); ConsoleLogger logger = new ConsoleLogger(); logger.start("开始加载训练集...\n"); Instance[] instances = loadTrainInstances(trainingFile, mutableFeatureMap); tagSet.lock(); logger.finish("\n加载完毕,实例一共%d句,特征总数%d\n", instances.length, mutableFeatureMap.size() * tagSet.size()); // 开始训练 ImmutableFeatureMap immutableFeatureMap = new ImmutableFeatureMap(mutableFeatureMap.featureIdMap, tagSet); mutableFeatureMap = null; double[] accuracy = null; if (threadNum == 1) { AveragedPerceptron model; model = new AveragedPerceptron(immutableFeatureMap); final double[] total = new double[model.parameter.length]; final int[] timestamp = new int[model.parameter.length]; int current = 0; for (int iter = 1; iter <= maxIteration; iter++) { Utility.shuffleArray(instances); for (Instance instance : instances) { ++current; int[] guessLabel = new int[instance.length()]; model.viterbiDecode(instance, guessLabel); for (int i = 0; i < instance.length(); i++) { int[] featureVector = instance.getFeatureAt(i); int[] goldFeature = new int[featureVector.length]; int[] predFeature = new int[featureVector.length]; for (int j = 0; j < featureVector.length - 1; j++) { goldFeature[j] = featureVector[j] * tagSet.size() + instance.tagArray[i]; predFeature[j] = featureVector[j] * tagSet.size() + guessLabel[i]; } goldFeature[featureVector.length - 1] = (i == 0 ? tagSet.bosId() : instance.tagArray[i - 1]) * tagSet.size() + instance.tagArray[i]; predFeature[featureVector.length - 1] = (i == 0 ? tagSet.bosId() : guessLabel[i - 1]) * tagSet.size() + guessLabel[i]; model.update(goldFeature, predFeature, total, timestamp, current); } } // 在开发集上校验 accuracy = trainingFile.equals(developFile) ? IOUtility.evaluate(instances, model) : evaluate(developFile, model); out.printf("Iter#%d - ", iter); printAccuracy(accuracy); } // 平均 model.average(total, timestamp, current); accuracy = trainingFile.equals(developFile) ? IOUtility.evaluate(instances, model) : evaluate(developFile, model); out.print("AP - "); printAccuracy(accuracy); logger.start("以压缩比 %.2f 保存模型到 %s ... ", compressRatio, modelFile); model.save(modelFile, immutableFeatureMap.featureIdMap.entrySet(), compressRatio); logger.finish(" 保存完毕\n"); if (compressRatio == 0) return new Result(model, accuracy); } else { // 多线程用Structure Perceptron StructuredPerceptron[] models = new StructuredPerceptron[threadNum]; for (int i = 0; i < models.length; i++) { models[i] = new StructuredPerceptron(immutableFeatureMap); } TrainingWorker[] workers = new TrainingWorker[threadNum]; int job = instances.length / threadNum; for (int iter = 1; iter <= maxIteration; iter++) { Utility.shuffleArray(instances); try { for (int i = 0; i < workers.length; i++) { workers[i] = new TrainingWorker(instances, i * job, i == workers.length - 1 ? instances.length : (i + 1) * job, models[i]); workers[i].start(); } for (TrainingWorker worker : workers) { worker.join(); } for (int j = 0; j < models[0].parameter.length; j++) { for (int i = 1; i < models.length; i++) { models[0].parameter[j] += models[i].parameter[j]; } models[0].parameter[j] /= threadNum; } accuracy = trainingFile.equals(developFile) ? IOUtility.evaluate(instances, models[0]) : evaluate(developFile, models[0]); out.printf("Iter#%d - ", iter); printAccuracy(accuracy); } catch (InterruptedException e) { err.printf("线程同步异常,训练失败\n"); e.printStackTrace(); return null; } } logger.start("以压缩比 %.2f 保存模型到 %s ... ", compressRatio, modelFile); models[0].save(modelFile, immutableFeatureMap.featureIdMap.entrySet(), compressRatio, HanLP.Config.DEBUG); logger.finish(" 保存完毕\n"); if (compressRatio == 0) return new Result(models[0], accuracy); } LinearModel model = new LinearModel(modelFile); if (compressRatio > 0) { accuracy = evaluate(developFile, model); out.printf("\n%.2f compressed model - ", compressRatio); printAccuracy(accuracy); } return new Result(model, accuracy); }
训练 @param trainingFile 训练集 @param developFile 开发集 @param modelFile 模型保存路径 @param compressRatio 压缩比 @param maxIteration 最大迭代次数 @param threadNum 线程数 @return 一个包含模型和精度的结构 @throws IOException
public LexicalAnalyzer getAnalyzer() { for (Pipe<List<IWord>, List<IWord>> pipe : this) { if (pipe instanceof LexicalAnalyzerPipe) { return ((LexicalAnalyzerPipe) pipe).analyzer; } } return null; }
获取代理的词法分析器 @return
public static List<String> extract(String text, int size) { IPhraseExtractor extractor = new MutualInformationEntropyPhraseExtractor(); return extractor.extractPhrase(text, size); }
一句话提取 @param text @param size @return
public Stack<MDAGNode> getTransitionPathNodes(String str) { Stack<MDAGNode> nodeStack = new Stack<MDAGNode>(); MDAGNode currentNode = this; int numberOfChars = str.length(); //Iteratively _transition through the MDAG using the chars in str, //putting each encountered node in nodeStack for(int i = 0; i < numberOfChars && currentNode != null; i++) { currentNode = currentNode.transition(str.charAt(i)); nodeStack.add(currentNode); } ///// return nodeStack; }
获取一个字符串路径上经过的节点<br> Retrieves the nodes in the _transition path starting from this node corresponding to a given String . @param str a String corresponding to a _transition path starting from this node @return a Stack of MDAGNodes containing the nodes in the _transition path denoted by {@code str}, in the order they are encountered in during transitioning
public void decrementTargetIncomingTransitionCounts() { for(Entry<Character, MDAGNode> transitionKeyValuePair: outgoingTransitionTreeMap.entrySet()) transitionKeyValuePair.getValue().incomingTransitionCount--; }
本状态的目标状态们的入度减一 Decrements (by 1) the incoming _transition counts of all of the nodes that are targets of outgoing transitions from this node.
public void reassignOutgoingTransition(char letter, MDAGNode oldTargetNode, MDAGNode newTargetNode) { oldTargetNode.incomingTransitionCount--; newTargetNode.incomingTransitionCount++; outgoingTransitionTreeMap.put(letter, newTargetNode); }
重新设置转移状态函数的目标 Reassigns the target node of one of this node's outgoing transitions. @param letter the char which labels the outgoing _transition of interest @param oldTargetNode the MDAGNode that is currently the target of the _transition of interest @param newTargetNode the MDAGNode that is to be the target of the _transition of interest
public MDAGNode addOutgoingTransition(char letter, boolean targetAcceptStateStatus) { MDAGNode newTargetNode = new MDAGNode(targetAcceptStateStatus); newTargetNode.incomingTransitionCount++; outgoingTransitionTreeMap.put(letter, newTargetNode); return newTargetNode; }
新建一个转移目标<br> Creates an outgoing _transition labeled with a given char that has a new node as its target. @param letter a char representing the desired label of the _transition @param targetAcceptStateStatus a boolean representing to-be-created _transition target node's accept status @return the (newly created) MDAGNode that is the target of the created _transition
public static boolean haveSameTransitions(MDAGNode node1, MDAGNode node2) { TreeMap<Character, MDAGNode> outgoingTransitionTreeMap1 = node1.outgoingTransitionTreeMap; TreeMap<Character, MDAGNode> outgoingTransitionTreeMap2 = node2.outgoingTransitionTreeMap; if(outgoingTransitionTreeMap1.size() == outgoingTransitionTreeMap2.size()) { //For each _transition in outgoingTransitionTreeMap1, get the identically lableed _transition //in outgoingTransitionTreeMap2 (if present), and test the equality of the transitions' target nodes for(Entry<Character, MDAGNode> transitionKeyValuePair : outgoingTransitionTreeMap1.entrySet()) { Character currentCharKey = transitionKeyValuePair.getKey(); MDAGNode currentTargetNode = transitionKeyValuePair.getValue(); if(!outgoingTransitionTreeMap2.containsKey(currentCharKey) || !outgoingTransitionTreeMap2.get(currentCharKey).equals(currentTargetNode)) return false; } ///// } else return false; return true; }
是否含有相同的转移函数 @param node1 @param node2 @return
public void learn(List<Word> wordList) { LinkedList<char[]> sentence = new LinkedList<char[]>(); for (IWord iWord : wordList) { String word = iWord.getValue(); if (word.length() == 1) { sentence.add(new char[]{word.charAt(0), 's'}); } else { sentence.add(new char[]{word.charAt(0), 'b'}); for (int i = 1; i < word.length() - 1; ++i) { sentence.add(new char[]{word.charAt(i), 'm'}); } sentence.add(new char[]{word.charAt(word.length() - 1), 'e'}); } } // 转换完毕,开始统计 char[][] now = new char[3][]; // 定长3的队列 now[1] = bos; now[2] = bos; tf.add(1, bos, bos); tf.add(2, bos); for (char[] i : sentence) { System.arraycopy(now, 1, now, 0, 2); now[2] = i; tf.add(1, i); // uni tf.add(1, now[1], now[2]); // bi tf.add(1, now); // tri } }
让模型观测一个句子 @param wordList
public void train() { double tl1 = 0.0; double tl2 = 0.0; double tl3 = 0.0; for (String key : tf.d.keySet()) { if (key.length() != 6) continue; // tri samples char[][] now = new char[][] { {key.charAt(0), key.charAt(1)}, {key.charAt(2), key.charAt(3)}, {key.charAt(4), key.charAt(5)}, }; double c3 = div(tf.get(now) - 1, tf.get(now[0], now[1]) - 1); double c2 = div(tf.get(now[1], now[2]) - 1, tf.get(now[1]) - 1); double c1 = div(tf.get(now[2]) - 1, tf.getsum() - 1); if (c3 >= c1 && c3 >= c2) tl3 += tf.get(key.toCharArray()); else if (c2 >= c1 && c2 >= c3) tl2 += tf.get(key.toCharArray()); else if (c1 >= c2 && c1 >= c3) tl1 += tf.get(key.toCharArray()); } l1 = div(tl1, tl1 + tl2 + tl3); l2 = div(tl2, tl1 + tl2 + tl3); l3 = div(tl3, tl1 + tl2 + tl3); }
观测结束,开始训练
double log_prob(char s1, int i1, char s2, int i2, char s3, int i3) { if (transMatrix[i1][i2][i3] == 0) return inf; char t1 = id2tag[i1]; char t2 = id2tag[i2]; char t3 = id2tag[i3]; double uni = l1 * tf.freq(s3,t3); double bi = div(l2 * tf.get(s2,t2, s3,t3), tf.get(s2,t2)); double tri = div(l3 * tf.get(s1,t1, s2,t2, s3,t3), tf.get(s1,t1, s2,t2)); if (uni + bi + tri == 0) return inf; return Math.log(uni + bi + tri); }
求概率 @param s1 前2个字 @param s1 前2个状态的下标 @param s2 前1个字 @param s2 前1个状态的下标 @param s3 当前字 @param s3 当前状态的下标 @return 序列的概率
public char[] tag(char[] charArray) { if (charArray.length == 0) return new char[0]; if (charArray.length == 1) return new char[]{'s'}; char[] tag = new char[charArray.length]; double[][] now = new double[4][4]; double[] first = new double[4]; // link[i][s][t] := 第i个节点在前一个状态是s,当前状态是t时,前2个状态的tag的值 int[][][] link = new int[charArray.length][4][4]; // 第一个字,只可能是bs for (int s = 0; s < 4; ++s) { double p = (s == 1 || s == 2) ? inf : log_prob(bos[0], 4, bos[0], 4, charArray[0],s); first[s] = p; } // 第二个字,尚不能完全利用TriGram for (int f = 0; f < 4; ++f) { for (int s = 0; s < 4; ++s) { double p = first[f] + log_prob(bos[0],4, charArray[0],f, charArray[1],s); now[f][s] = p; link[1][f][s] = f; } } // 第三个字开始,利用TriGram标注 double[][] pre = new double[4][4]; for (int i = 2; i < charArray.length; i++) { // swap(now, pre) double[][] _ = pre; pre = now; now = _; // end of swap for (int s = 0; s < 4; ++s) { for (int t = 0; t < 4; ++t) { now[s][t] = -1e20; for (int f = 0; f < 4; ++f) { double p = pre[f][s] + log_prob(charArray[i - 2], f, charArray[i - 1], s, charArray[i], t); if (p > now[s][t]) { now[s][t] = p; link[i][s][t] = f; } } } } } // 无法保证最优路径每个状态的概率都是非最小值, 所以回溯路径得分最小值必须小于inf double score = charArray.length*inf; int s = 0; int t = 0; for (int i = 0; i < probableTail.length; i++) { int [] state = probableTail[i]; if (now[state[0]][state[1]] > score) { score = now[state[0]][state[1]]; s = state[0]; t = state[1]; } } for (int i = link.length - 1; i >= 0; --i) { tag[i] = id2tag[t]; int f = link[i][s][t]; t = s; s = f; } return tag; }
序列标注 @param charArray 观测序列 @return 标注序列
public static void parsePattern(List<NR> nrList, List<Vertex> vertexList, final WordNet wordNetOptimum, final WordNet wordNetAll) { // 拆分UV ListIterator<Vertex> listIterator = vertexList.listIterator(); StringBuilder sbPattern = new StringBuilder(nrList.size()); NR preNR = NR.A; boolean backUp = false; int index = 0; for (NR nr : nrList) { ++index; Vertex current = listIterator.next(); // logger.trace("{}/{}", current.realWord, nr); switch (nr) { case U: if (!backUp) { vertexList = new ArrayList<Vertex>(vertexList); listIterator = vertexList.listIterator(index); backUp = true; } sbPattern.append(NR.K.toString()); sbPattern.append(NR.B.toString()); preNR = B; listIterator.previous(); String nowK = current.realWord.substring(0, current.realWord.length() - 1); String nowB = current.realWord.substring(current.realWord.length() - 1); listIterator.set(new Vertex(nowK)); listIterator.next(); listIterator.add(new Vertex(nowB)); continue; case V: if (!backUp) { vertexList = new ArrayList<Vertex>(vertexList); listIterator = vertexList.listIterator(index); backUp = true; } if (preNR == B) { sbPattern.append(NR.E.toString()); //BE } else { sbPattern.append(NR.D.toString()); //CD } sbPattern.append(NR.L.toString()); // 对串也做一些修改 listIterator.previous(); String EorD = current.realWord.substring(0, 1); String L = current.realWord.substring(1, current.realWord.length()); listIterator.set(new Vertex(EorD)); listIterator.next(); listIterator.add(new Vertex(L)); continue; default: sbPattern.append(nr.toString()); break; } preNR = nr; } String pattern = sbPattern.toString(); // logger.trace("模式串:{}", pattern); // logger.trace("对应串:{}", vertexList); // if (pattern.length() != vertexList.size()) // { // logger.warn("人名识别模式串有bug", pattern, vertexList); // return; // } final Vertex[] wordArray = vertexList.toArray(new Vertex[0]); final int[] offsetArray = new int[wordArray.length]; offsetArray[0] = 0; for (int i = 1; i < wordArray.length; ++i) { offsetArray[i] = offsetArray[i - 1] + wordArray[i - 1].realWord.length(); } trie.parseText(pattern, new AhoCorasickDoubleArrayTrie.IHit<NRPattern>() { @Override public void hit(int begin, int end, NRPattern value) { // logger.trace("匹配到:{}", keyword); StringBuilder sbName = new StringBuilder(); for (int i = begin; i < end; ++i) { sbName.append(wordArray[i].realWord); } String name = sbName.toString(); // logger.trace("识别出:{}", name); // 对一些bad case做出调整 switch (value) { case BCD: if (name.charAt(0) == name.charAt(2)) return; // 姓和最后一个名不可能相等的 // String cd = name.substring(1); // if (CoreDictionary.contains(cd)) // { // EnumItem<NR> item = PersonDictionary.dictionary.get(cd); // if (item == null || !item.containsLabel(Z)) return; // 三字名字但是后两个字不在词典中,有很大可能性是误命中 // } break; } if (isBadCase(name)) return; // 正式算它是一个名字 if (HanLP.Config.DEBUG) { System.out.printf("识别出人名:%s %s\n", name, value); } int offset = offsetArray[begin]; wordNetOptimum.insert(offset, new Vertex(Predefine.TAG_PEOPLE, name, ATTRIBUTE, WORD_ID), wordNetAll); } }); }
模式匹配 @param nrList 确定的标注序列 @param vertexList 原始的未加角色标注的序列 @param wordNetOptimum 待优化的图 @param wordNetAll 全词图
static boolean isBadCase(String name) { EnumItem<NR> nrEnumItem = dictionary.get(name); if (nrEnumItem == null) return false; return nrEnumItem.containsLabel(NR.A); }
因为任何算法都无法解决100%的问题,总是有一些bad case,这些bad case会以“盖公章 A 1”的形式加入词典中<BR> 这个方法返回人名是否是bad case @param name @return
public static List<NT> viterbiCompute(List<EnumItem<NT>> roleTagList) { return Viterbi.computeEnum(roleTagList, OrganizationDictionary.transformMatrixDictionary); }
维特比算法求解最优标签 @param roleTagList @return
public Vector addDocument(int id, String content) { Vector result = query(content); if (result == null) return null; storage.put(id, result); return result; }
添加文档 @param id 文档id @param content 文档内容 @return 文档向量
public List<Map.Entry<Integer, Float>> nearest(String query) { return queryNearest(query, 10); }
查询最相似的前10个文档 @param query 查询语句(或者说一个文档的内容) @return
public Vector query(String content) { if (content == null || content.length() == 0) return null; List<Term> termList = NotionalTokenizer.segment(content); Vector result = new Vector(dimension()); int n = 0; for (Term term : termList) { Vector vector = wordVectorModel.vector(term.word); if (vector == null) { continue; } ++n; result.addToSelf(vector); } if (n == 0) { return null; } result.normalize(); return result; }
将一个文档转为向量 @param content 文档 @return 向量
public float similarity(String what, String with) { Vector A = query(what); if (A == null) return -1f; Vector B = query(with); if (B == null) return -1f; return A.cosineForUnitVector(B); }
文档相似度计算 @param what @param with @return
void init() { _table.resize(INITIAL_TABLE_SIZE, 0); appendNode(); appendUnit(); _numStates = 1; _nodes.get(0).label = (byte) 0xFF; _nodeStack.add(0); }
初始化
public static KBeamArcEagerDependencyParser train(String trainCorpus, String devCorpus, String clusterPath, String modelPath) throws InterruptedException, ExecutionException, IOException, ClassNotFoundException { Options options = new Options(); options.train = true; options.inputFile = trainCorpus; options.devPath = devCorpus; options.clusterFile = clusterPath; options.modelFile = modelPath; Main.train(options); return new KBeamArcEagerDependencyParser(modelPath); }
训练依存句法分析器 @param trainCorpus 训练集 @param devCorpus 开发集 @param clusterPath Brown词聚类文件 @param modelPath 模型储存路径 @throws InterruptedException @throws ExecutionException @throws IOException @throws ClassNotFoundException
public double[] evaluate(String testCorpus) throws IOException, ExecutionException, InterruptedException { Options options = parser.options; options.goldFile = testCorpus; File tmpTemplate = File.createTempFile("pred-" + new Date().getTime(), ".conll"); tmpTemplate.deleteOnExit(); options.predFile = tmpTemplate.getAbsolutePath(); options.outputFile = options.predFile; File scoreFile = File.createTempFile("score-" + new Date().getTime(), ".txt"); scoreFile.deleteOnExit(); parser.parseConllFile(testCorpus, options.outputFile, options.rootFirst, options.beamWidth, true, options.lowercase, 1, false, scoreFile.getAbsolutePath()); return Evaluator.evaluate(options.goldFile, options.predFile, options.punctuations); }
标准化评测 @param testCorpus 测试语料 @return 包含UF、LF的数组 @throws IOException @throws ExecutionException @throws InterruptedException
public CoNLLSentence parse(List<Term> termList, int beamWidth, int numOfThreads) { String[] words = new String[termList.size()]; String[] tags = new String[termList.size()]; int k = 0; for (Term term : termList) { words[k] = term.word; tags[k] = term.nature.toString(); ++k; } Configuration bestParse; try { bestParse = parser.parse(words, tags, false, beamWidth, numOfThreads); } catch (Exception e) { throw new RuntimeException(e); } CoNLLWord[] wordArray = new CoNLLWord[termList.size()]; for (int i = 0; i < words.length; i++) { wordArray[i] = new CoNLLWord(i + 1, words[i], tags[i]); } for (int i = 0; i < words.length; i++) { wordArray[i].DEPREL = parser.idWord(bestParse.state.getDependent(i + 1)); int index = bestParse.state.getHead(i + 1) - 1; if (index < 0 || index >= wordArray.length) { wordArray[i].HEAD = CoNLLWord.ROOT; } else { wordArray[i].HEAD = wordArray[index]; } } return new CoNLLSentence(wordArray); }
执行句法分析 @param termList 分词结果 @param beamWidth 柱搜索宽度 @param numOfThreads 多线程数 @return 句法树
public static CoreDictionary.Attribute guessAttribute(Term term) { CoreDictionary.Attribute attribute = CoreDictionary.get(term.word); if (attribute == null) { attribute = CustomDictionary.get(term.word); } if (attribute == null) { if (term.nature != null) { if (Nature.nx == term.nature) attribute = new CoreDictionary.Attribute(Nature.nx); else if (Nature.m == term.nature) attribute = CoreDictionary.get(CoreDictionary.M_WORD_ID); } else if (term.word.trim().length() == 0) attribute = new CoreDictionary.Attribute(Nature.x); else attribute = new CoreDictionary.Attribute(Nature.nz); } else term.nature = attribute.nature[0]; return attribute; }
查询或猜测一个词语的属性, 先查词典,然后对字母、数字串的属性进行判断,最后猜测未登录词 @param term @return
@Override protected List<Term> segSentence(char[] sentence) { if (sentence.length == 0) return Collections.emptyList(); List<Term> termList = roughSegSentence(sentence); if (!(config.ner || config.useCustomDictionary || config.speechTagging)) return termList; List<Vertex> vertexList = toVertexList(termList, true); if (config.speechTagging) { Viterbi.compute(vertexList, CoreDictionaryTransformMatrixDictionary.transformMatrixDictionary); int i = 0; for (Term term : termList) { if (term.nature != null) term.nature = vertexList.get(i + 1).guessNature(); ++i; } } if (config.useCustomDictionary) { combineByCustomDictionary(vertexList); termList = convert(vertexList, config.offset); } return termList; }
以下方法用于纯分词模型 分词、词性标注联合模型则直接重载segSentence
protected List<Vertex> toVertexList(List<Term> wordList, boolean appendStart) { ArrayList<Vertex> vertexList = new ArrayList<Vertex>(wordList.size() + 2); if (appendStart) vertexList.add(Vertex.newB()); for (Term word : wordList) { CoreDictionary.Attribute attribute = guessAttribute(word); Vertex vertex = new Vertex(word.word, attribute); vertexList.add(vertex); } if (appendStart) vertexList.add(Vertex.newE()); return vertexList; }
将中间结果转换为词网顶点, 这样就可以利用基于Vertex开发的功能, 如词性标注、NER等 @param wordList @param appendStart @return
public void save(String modelFile) throws IOException { DataOutputStream out = new DataOutputStream(new BufferedOutputStream(IOUtil.newOutputStream(modelFile))); save(out); out.close(); }
保存到路径 @param modelFile @throws IOException
public void save(String modelFile, final double ratio) throws IOException { save(modelFile, featureMap.entrySet(), ratio); }
压缩并保存 @param modelFile 路径 @param ratio 压缩比c(压缩掉的体积,压缩后体积变为1-c) @throws IOException
public void save(String modelFile, Set<Map.Entry<String, Integer>> featureIdSet, final double ratio, boolean text) throws IOException { float[] parameter = this.parameter; this.compress(ratio, 1e-3f); DataOutputStream out = new DataOutputStream(new BufferedOutputStream(IOUtil.newOutputStream(modelFile))); save(out); out.close(); if (text) { BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(IOUtil.newOutputStream(modelFile + ".txt"), "UTF-8")); TagSet tagSet = featureMap.tagSet; for (Map.Entry<String, Integer> entry : featureIdSet) { bw.write(entry.getKey()); if (featureIdSet.size() == parameter.length) { bw.write("\t"); bw.write(String.valueOf(parameter[entry.getValue()])); } else { for (int i = 0; i < tagSet.size(); ++i) { bw.write("\t"); bw.write(String.valueOf(parameter[entry.getValue() * tagSet.size() + i])); } } bw.newLine(); } bw.close(); } }
保存 @param modelFile 路径 @param featureIdSet 特征集(有些数据结构不支持遍历,可以提供构造时用到的特征集来规避这个缺陷) @param ratio 压缩比 @param text 是否输出文本以供调试 @throws IOException
public void update(Collection<Integer> x, int y) { assert y == 1 || y == -1 : "感知机的标签y必须是±1"; for (Integer f : x) parameter[f] += y; }
参数更新 @param x 特征向量 @param y 正确答案
public int decode(Collection<Integer> x) { float y = 0; for (Integer f : x) y += parameter[f]; return y < 0 ? -1 : 1; }
分离超平面解码 @param x 特征向量 @return sign(wx)
public double viterbiDecode(Instance instance, int[] guessLabel) { final int[] allLabel = featureMap.allLabels(); final int bos = featureMap.bosTag(); final int sentenceLength = instance.tagArray.length; final int labelSize = allLabel.length; int[][] preMatrix = new int[sentenceLength][labelSize]; double[][] scoreMatrix = new double[2][labelSize]; for (int i = 0; i < sentenceLength; i++) { int _i = i & 1; int _i_1 = 1 - _i; int[] allFeature = instance.getFeatureAt(i); final int transitionFeatureIndex = allFeature.length - 1; if (0 == i) { allFeature[transitionFeatureIndex] = bos; for (int j = 0; j < allLabel.length; j++) { preMatrix[0][j] = j; double score = score(allFeature, j); scoreMatrix[0][j] = score; } } else { for (int curLabel = 0; curLabel < allLabel.length; curLabel++) { double maxScore = Integer.MIN_VALUE; for (int preLabel = 0; preLabel < allLabel.length; preLabel++) { allFeature[transitionFeatureIndex] = preLabel; double score = score(allFeature, curLabel); double curScore = scoreMatrix[_i_1][preLabel] + score; if (maxScore < curScore) { maxScore = curScore; preMatrix[i][curLabel] = preLabel; scoreMatrix[_i][curLabel] = maxScore; } } } } } int maxIndex = 0; double maxScore = scoreMatrix[(sentenceLength - 1) & 1][0]; for (int index = 1; index < allLabel.length; index++) { if (maxScore < scoreMatrix[(sentenceLength - 1) & 1][index]) { maxIndex = index; maxScore = scoreMatrix[(sentenceLength - 1) & 1][index]; } } for (int i = sentenceLength - 1; i >= 0; --i) { guessLabel[i] = allLabel[maxIndex]; maxIndex = preMatrix[i][maxIndex]; } return maxScore; }
维特比解码 @param instance 实例 @param guessLabel 输出标签 @return
public double score(int[] featureVector, int currentTag) { double score = 0; for (int index : featureVector) { if (index == -1) { continue; } else if (index < -1 || index >= featureMap.size()) { throw new IllegalArgumentException("在打分时传入了非法的下标"); } else { index = index * featureMap.tagSet.size() + currentTag; score += parameter[index]; // 其实就是特征权重的累加 } } return score; }
通过命中的特征函数计算得分 @param featureVector 压缩形式的特征id构成的特征向量 @return
public void load(String modelFile) throws IOException { if (HanLP.Config.DEBUG) logger.start("加载 %s ... ", modelFile); ByteArrayStream byteArray = ByteArrayStream.createByteArrayStream(modelFile); if (!load(byteArray)) { throw new IOException(String.format("%s 加载失败", modelFile)); } if (HanLP.Config.DEBUG) logger.finish(" 加载完毕\n"); }
加载模型 @param modelFile @throws IOException
public static double GaussCdf(double z) { // input = z-value (-inf to +inf) // output = p under Normal curve from -inf to z // e.g., if z = 0.0, function returns 0.5000 // ACM Algorithm #209 double y; // 209 scratch variable double p; // result. called ‘z’ in 209 double w; // 209 scratch variable if (z == 0.0) { p = 0.0; } else { y = Math.abs(z) / 2.0; if (y >= 3.0) { p = 1.0; } else if (y < 1.0) { w = y * y; p = ((((((((0.000124818987 * w - 0.001075204047) * w + 0.005198775019) * w - 0.019198292004) * w + 0.059054035642) * w - 0.151968751364) * w + 0.319152932694) * w - 0.531923007300) * w + 0.797884560593) * y * 2.0; } else { y = y - 2.0; p = (((((((((((((-0.000045255659 * y + 0.000152529290) * y - 0.000019538132) * y - 0.000676904986) * y + 0.001390604284) * y - 0.000794620820) * y - 0.002034254874) * y + 0.006549791214) * y - 0.010557625006) * y + 0.011630447319) * y - 0.009279453341) * y + 0.005353579108) * y - 0.002141268741) * y + 0.000535310849) * y + 0.999936657524; } } if (z > 0.0) { return (p + 1.0) / 2.0; } return (1.0 - p) / 2.0; }
给定高斯函数的z值,返回p值(累积分布函数值)<br> http://jamesmccaffrey.wordpress.com/2010/11/05/programmatically-computing-the-area-under-the-normal-curve/ @param z 从负无穷到正无穷的值 @return 高斯函数累积分布函数值
public static double LogGamma(double Z) { double S = 1.0 + 76.18009173 / Z - 86.50532033 / (Z + 1.0) + 24.01409822 / (Z + 2.0) - 1.231739516 / (Z + 3.0) + 0.00120858003 / (Z + 4.0) - 0.00000536382 / (Z + 5.0); double LG = (Z - 0.5) * Math.log(Z + 4.5) - (Z + 4.5) + Math.log(S * 2.50662827465); return LG; }
Log Gamma Function @param Z @return
protected static double Gcf(double x, double A) { // Good for X>A+1 double A0 = 0; double B0 = 1; double A1 = 1; double B1 = x; double AOLD = 0; double N = 0; while (Math.abs((A1 - AOLD) / A1) > .00001) { AOLD = A1; N = N + 1; A0 = A1 + (N - A) * A0; B0 = B1 + (N - A) * B0; A1 = x * A0 + N * A1; B1 = x * B0 + N * B1; A0 = A0 / B1; B0 = B0 / B1; A1 = A1 / B1; B1 = 1; } double Prob = Math.exp(A * Math.log(x) - x - LogGamma(A)) * A1; return 1.0 - Prob; }
Internal function used by GammaCdf @param x @param A @return
protected static double Gser(double x, double A) { // Good for X<A+1. double T9 = 1 / A; double G = T9; double I = 1; while (T9 > G * 0.00001) { T9 = T9 * x / (A + I); G = G + T9; ++I; } G = G * Math.exp(A * Math.log(x) - x - LogGamma(A)); return G; }
Internal function used by GammaCdf @param x @param A @return
protected static double GammaCdf(double x, double a) throws IllegalArgumentException { if (x < 0) { throw new IllegalArgumentException(); } double GI = 0; if (a > 200) { double z = (x - a) / Math.sqrt(a); double y = GaussCdf(z); double b1 = 2 / Math.sqrt(a); double phiz = 0.39894228 * Math.exp(-z * z / 2); double w = y - b1 * (z * z - 1) * phiz / 6; //Edgeworth1 double b2 = 6 / a; int zXor4 = ((int) z) ^ 4; double u = 3 * b2 * (z * z - 3) + b1 * b1 * (zXor4 - 10 * z * z + 15); GI = w - phiz * z * u / 72; //Edgeworth2 } else if (x < a + 1) { GI = Gser(x, a); } else { GI = Gcf(x, a); } return GI; }
伽马函数 @param x @param a @return @throws IllegalArgumentException