Share via


TextCatalog.ProduceHashedNgrams 方法

定义

重载

ProduceHashedNgrams(TransformsCatalog+TextTransforms, String, String, Int32, Int32, Int32, Boolean, UInt32, Boolean, Int32, Boolean)

创建一个 NgramHashingEstimator,用于将数据从指定 inputColumnName 列复制到新列: outputColumnName 并生成哈希 n 元语法计数的向量。

ProduceHashedNgrams(TransformsCatalog+TextTransforms, String, String[], Int32, Int32, Int32, Boolean, UInt32, Boolean, Int32, Boolean)

创建一个 NgramHashingEstimator,它将数据从指定的 inputColumnNames 多个列提取到一个新列: outputColumnName 并生成哈希 n 元语法计数的向量。

ProduceHashedNgrams(TransformsCatalog+TextTransforms, String, String, Int32, Int32, Int32, Boolean, UInt32, Boolean, Int32, Boolean)

创建一个 NgramHashingEstimator,用于将数据从指定 inputColumnName 列复制到新列: outputColumnName 并生成哈希 n 元语法计数的向量。

public static Microsoft.ML.Transforms.Text.NgramHashingEstimator ProduceHashedNgrams (this Microsoft.ML.TransformsCatalog.TextTransforms catalog, string outputColumnName, string inputColumnName = default, int numberOfBits = 16, int ngramLength = 2, int skipLength = 0, bool useAllLengths = true, uint seed = 314489979, bool useOrderedHashing = true, int maximumNumberOfInverts = 0, bool rehashUnigrams = false);
static member ProduceHashedNgrams : Microsoft.ML.TransformsCatalog.TextTransforms * string * string * int * int * int * bool * uint32 * bool * int * bool -> Microsoft.ML.Transforms.Text.NgramHashingEstimator
<Extension()>
Public Function ProduceHashedNgrams (catalog As TransformsCatalog.TextTransforms, outputColumnName As String, Optional inputColumnName As String = Nothing, Optional numberOfBits As Integer = 16, Optional ngramLength As Integer = 2, Optional skipLength As Integer = 0, Optional useAllLengths As Boolean = true, Optional seed As UInteger = 314489979, Optional useOrderedHashing As Boolean = true, Optional maximumNumberOfInverts As Integer = 0, Optional rehashUnigrams As Boolean = false) As NgramHashingEstimator

参数

catalog
TransformsCatalog.TextTransforms

转换的目录。

outputColumnName
String

由转换 inputColumnName生成的列的名称。 此列的数据类型将为向量 Single

inputColumnName
String

要从中复制数据的列的名称。 此估算器对键类型的向量进行操作。

numberOfBits
Int32

要哈希到的位数。 必须介于 1 和 30 之间(含限值)。

ngramLength
Int32

Ngram 长度。

skipLength
Int32

构造 n 元语法时要跳过的最大标记数。

useAllLengths
Boolean

是否包括所有 n 元语法长度, ngramLength 最大或仅 ngramLength包含 。

seed
UInt32

哈希种子。

useOrderedHashing
Boolean

是否应将每个源列的位置包括在哈希中(当存在多个源列时)。

maximumNumberOfInverts
Int32

在哈希处理期间,我们在原始值和生成的哈希值之间构造映射。 原始值的文本表示形式存储在新列的批注的槽名称中。因此,哈希可以将许多初始值映射到一个值。 maximumNumberOfInverts 指定映射到应保留的哈希的非重复输入值数的上限。 0 不保留任何输入值。 -1 保留映射到每个哈希的所有输入值。

rehashUnigrams
Boolean

是否重写 unigram。

返回

注解

NgramHashingEstimator不同于WordHashBagEstimator在内部标记文本时WordHashBagEstimator将标记化文本作为输入的方式NgramHashingEstimator

适用于

ProduceHashedNgrams(TransformsCatalog+TextTransforms, String, String[], Int32, Int32, Int32, Boolean, UInt32, Boolean, Int32, Boolean)

创建一个 NgramHashingEstimator,它将数据从指定的 inputColumnNames 多个列提取到一个新列: outputColumnName 并生成哈希 n 元语法计数的向量。

public static Microsoft.ML.Transforms.Text.NgramHashingEstimator ProduceHashedNgrams (this Microsoft.ML.TransformsCatalog.TextTransforms catalog, string outputColumnName, string[] inputColumnNames = default, int numberOfBits = 16, int ngramLength = 2, int skipLength = 0, bool useAllLengths = true, uint seed = 314489979, bool useOrderedHashing = true, int maximumNumberOfInverts = 0, bool rehashUnigrams = false);
static member ProduceHashedNgrams : Microsoft.ML.TransformsCatalog.TextTransforms * string * string[] * int * int * int * bool * uint32 * bool * int * bool -> Microsoft.ML.Transforms.Text.NgramHashingEstimator
<Extension()>
Public Function ProduceHashedNgrams (catalog As TransformsCatalog.TextTransforms, outputColumnName As String, Optional inputColumnNames As String() = Nothing, Optional numberOfBits As Integer = 16, Optional ngramLength As Integer = 2, Optional skipLength As Integer = 0, Optional useAllLengths As Boolean = true, Optional seed As UInteger = 314489979, Optional useOrderedHashing As Boolean = true, Optional maximumNumberOfInverts As Integer = 0, Optional rehashUnigrams As Boolean = false) As NgramHashingEstimator

参数

catalog
TransformsCatalog.TextTransforms

转换的目录。

outputColumnName
String

由转换 inputColumnNames生成的列的名称。 此列的数据类型将是已知大小的 Single向量。

inputColumnNames
String[]

要从中获取数据的多个列的名称。 此估算器对键类型的向量进行操作。

numberOfBits
Int32

要哈希到的位数。 必须介于 1 和 30 之间(含限值)。

ngramLength
Int32

Ngram 长度。

skipLength
Int32

构造 n 元语法时要跳过的最大标记数。

useAllLengths
Boolean

是否包括所有 n 元语法长度, ngramLength 最大或仅 ngramLength包含 。

seed
UInt32

哈希种子。

useOrderedHashing
Boolean

是否应将每个源列的位置包括在哈希中(当存在多个源列时)。

maximumNumberOfInverts
Int32

在哈希处理期间,我们在原始值和生成的哈希值之间构造映射。 原始值的文本表示形式存储在新列的批注的槽名称中。因此,哈希可以将许多初始值映射到一个值。 maximumNumberOfInverts 指定映射到应保留的哈希的非重复输入值数的上限。 0 不保留任何输入值。 -1 保留映射到每个哈希的所有输入值。

rehashUnigrams
Boolean

是否重写 unigram。

返回

示例

using System;
using System.Collections.Generic;
using Microsoft.ML;
using Microsoft.ML.Data;

namespace Samples.Dynamic
{
    public static class ProduceHashedNgrams
    {
        public static void Example()
        {
            // Create a new ML context, for ML.NET operations. It can be used for
            // exception tracking and logging, as well as the source of randomness.
            var mlContext = new MLContext();

            // Create a small dataset as an IEnumerable.
            var samples = new List<TextData>()
            {
                new TextData(){ Text = "This is an example to compute n-grams " +
                "using hashing." },

                new TextData(){ Text = "N-gram is a sequence of 'N' consecutive" +
                " words/tokens." },

                new TextData(){ Text = "ML.NET's ProduceHashedNgrams API " +
                "produces count of n-grams and hashes it as an index into a " +
                "vector of given bit length." },

                new TextData(){ Text = "The hashing reduces the size of the " +
                "output feature vector" },

                new TextData(){ Text = "which is useful in case when number of " +
                "n-grams is very large." },
            };

            // Convert training data to IDataView.
            var dataview = mlContext.Data.LoadFromEnumerable(samples);

            // A pipeline for converting text into numeric hashed n-gram features.
            // The following call to 'ProduceHashedNgrams' requires the tokenized
            // text /string as input. This is achieved by calling 
            // 'TokenizeIntoWords' first followed by 'ProduceHashedNgrams'.
            // Please note that the length of the output feature vector depends on
            // the 'numberOfBits' settings.
            var textPipeline = mlContext.Transforms.Text.TokenizeIntoWords("Tokens",
                "Text")
                .Append(mlContext.Transforms.Conversion.MapValueToKey("Tokens"))
                .Append(mlContext.Transforms.Text.ProduceHashedNgrams(
                    "NgramFeatures", "Tokens",
                    numberOfBits: 5,
                    ngramLength: 3,
                    useAllLengths: false,
                    maximumNumberOfInverts: 1));

            // Fit to data.
            var textTransformer = textPipeline.Fit(dataview);
            var transformedDataView = textTransformer.Transform(dataview);

            // Create the prediction engine to get the features extracted from the
            // text.
            var predictionEngine = mlContext.Model.CreatePredictionEngine<TextData,
                TransformedTextData>(textTransformer);

            // Convert the text into numeric features.
            var prediction = predictionEngine.Predict(samples[0]);

            // Print the length of the feature vector.
            Console.WriteLine("Number of Features: " + prediction.NgramFeatures
                .Length);

            // Preview of the produced n-grams.
            // Get the slot names from the column's metadata.
            // The slot names for a vector column corresponds to the names
            // associated with each position in the vector.
            VBuffer<ReadOnlyMemory<char>> slotNames = default;
            transformedDataView.Schema["NgramFeatures"].GetSlotNames(ref slotNames);
            var NgramFeaturesColumn = transformedDataView.GetColumn<VBuffer<float>>(
                transformedDataView.Schema["NgramFeatures"]);

            var slots = slotNames.GetValues();
            Console.Write("N-grams: ");
            foreach (var featureRow in NgramFeaturesColumn)
            {
                foreach (var item in featureRow.Items())
                    Console.Write($"{slots[item.Key]}  ");
                Console.WriteLine();
            }

            // Print the first 10 feature values.
            Console.Write("Features: ");
            for (int i = 0; i < 10; i++)
                Console.Write($"{prediction.NgramFeatures[i]:F4}  ");

            //  Expected output:
            //   Number of Features:  32
            //   N-grams:   This|is|an  example|to|compute  compute|n-grams|using  n-grams|using|hashing.  an|example|to  is|an|example  a|sequence|of  of|'N'|consecutive  is|a|sequence  N-gram|is|a  ...
            //   Features:    0.0000          0.0000               2.0000               0.0000               0.0000        1.0000          0.0000        0.0000              1.0000          0.0000  ...
        }

        private class TextData
        {
            public string Text { get; set; }
        }

        private class TransformedTextData : TextData
        {
            public float[] NgramFeatures { get; set; }
        }
    }
}

注解

NgramHashingEstimator不同于WordHashBagEstimator在内部标记文本时WordHashBagEstimator将标记化文本作为输入的方式NgramHashingEstimator

适用于