Packages

class Word2VecModel extends AnnotatorModel[Word2VecModel] with HasSimpleAnnotate[Word2VecModel] with HasStorageRef with HasEmbeddingsProperties with ParamsAndFeaturesWritable

Word2Vec model that creates vector representations of words in a text corpus.

The algorithm first constructs a vocabulary from the corpus and then learns vector representation of words in the vocabulary. The vector representation can be used as features in natural language processing and machine learning algorithms.

We use Word2Vec implemented in Spark ML. It uses skip-gram model in our implementation and a hierarchical softmax method to train the model. The variable names in the implementation match the original C implementation.

This is the instantiated model of the Word2VecApproach. For training your own model, please see the documentation of that class.

Pretrained models can be loaded with pretrained of the companion object:

val embeddings = Word2VecModel.pretrained()
  .setInputCols("token")
  .setOutputCol("embeddings")

The default model is "word2vec_gigaword_300", if no name is provided.

For available pretrained models please see the Models Hub.

Sources :

For the original C implementation, see https://code.google.com/p/word2vec/

For the research paper, see Efficient Estimation of Word Representations in Vector Space and Distributed Representations of Words and Phrases and their Compositionality.

Example

import spark.implicits._
import com.johnsnowlabs.nlp.base.DocumentAssembler
import com.johnsnowlabs.nlp.annotator.{Tokenizer, Word2VecModel}
import com.johnsnowlabs.nlp.EmbeddingsFinisher

import org.apache.spark.ml.Pipeline

val documentAssembler = new DocumentAssembler()
  .setInputCol("text")
  .setOutputCol("document")

val tokenizer = new Tokenizer()
  .setInputCols(Array("document"))
  .setOutputCol("token")

val embeddings = Word2VecModel.pretrained()
  .setInputCols("token")
  .setOutputCol("embeddings")

val embeddingsFinisher = new EmbeddingsFinisher()
  .setInputCols("embeddings")
  .setOutputCols("finished_embeddings")
  .setOutputAsVector(true)

val pipeline = new Pipeline().setStages(Array(
  documentAssembler,
  tokenizer,
  embeddings,
  embeddingsFinisher
))

val data = Seq("This is a sentence.").toDF("text")
val result = pipeline.fit(data).transform(data)

result.selectExpr("explode(finished_embeddings) as result").show(1, 80)
+--------------------------------------------------------------------------------+
|                                                                          result|
+--------------------------------------------------------------------------------+
|[0.06222493574023247,0.011579325422644615,0.009919632226228714,0.109361454844...|
+--------------------------------------------------------------------------------+
Linear Supertypes
Ordering
  1. Grouped
  2. Alphabetic
  3. By Inheritance
Inherited
  1. Word2VecModel
  2. HasEmbeddingsProperties
  3. HasProtectedParams
  4. HasStorageRef
  5. HasSimpleAnnotate
  6. AnnotatorModel
  7. CanBeLazy
  8. RawAnnotator
  9. HasOutputAnnotationCol
  10. HasInputAnnotationCols
  11. HasOutputAnnotatorType
  12. ParamsAndFeaturesWritable
  13. HasFeatures
  14. DefaultParamsWritable
  15. MLWritable
  16. Model
  17. Transformer
  18. PipelineStage
  19. Logging
  20. Params
  21. Serializable
  22. Serializable
  23. Identifiable
  24. AnyRef
  25. Any
  1. Hide All
  2. Show All
Visibility
  1. Public
  2. All

Parameters

A list of (hyper-)parameter keys this annotator can take. Users can set and get the parameter values through setters and getters, respectively.

  1. val dimension: ProtectedParam[Int]

    Number of embedding dimensions (Default depends on model)

    Number of embedding dimensions (Default depends on model)

    Definition Classes
    HasEmbeddingsProperties
  2. val storageRef: Param[String]

    Unique identifier for storage (Default: this.uid)

    Unique identifier for storage (Default: this.uid)

    Definition Classes
    HasStorageRef
  3. val vectorSize: ProtectedParam[Int]

    The dimension of codes after transforming from words (> 0) (Default: 100)

  4. val wordVectors: MapFeature[String, Array[Float]]

    Dictionary of words with their vectors

Annotator types

Required input and expected output annotator types

  1. val inputAnnotatorTypes: Array[AnnotatorType]

    Input annotator type : TOKEN

    Input annotator type : TOKEN

    Definition Classes
    Word2VecModelHasInputAnnotationCols
  2. val outputAnnotatorType: String

    Output annotator type : WORD_EMBEDDINGS

    Output annotator type : WORD_EMBEDDINGS

    Definition Classes
    Word2VecModelHasOutputAnnotatorType

Members

  1. implicit class ProtectedParam[T] extends Param[T]
    Definition Classes
    HasProtectedParams
  2. type AnnotatorType = String
    Definition Classes
    HasOutputAnnotatorType
  1. def annotate(annotations: Seq[Annotation]): Seq[Annotation]

    takes a document and annotations and produces new annotations of this annotator's annotation type

    takes a document and annotations and produces new annotations of this annotator's annotation type

    annotations

    Annotations that correspond to inputAnnotationCols generated by previous annotators if any

    returns

    any number of annotations processed for every input annotation. Not necessary one to one relationship

    Definition Classes
    Word2VecModelHasSimpleAnnotate
  2. def beforeAnnotate(dataset: Dataset[_]): Dataset[_]
    Definition Classes
    Word2VecModelAnnotatorModel
  3. final def clear(param: Param[_]): Word2VecModel.this.type
    Definition Classes
    Params
  4. def copy(extra: ParamMap): Word2VecModel

    requirement for annotators copies

    requirement for annotators copies

    Definition Classes
    RawAnnotator → Model → Transformer → PipelineStage → Params
  5. def createDatabaseConnection(database: Name): RocksDBConnection
    Definition Classes
    HasStorageRef
  6. def dfAnnotate: UserDefinedFunction

    Wraps annotate to happen inside SparkSQL user defined functions in order to act with org.apache.spark.sql.Column

    Wraps annotate to happen inside SparkSQL user defined functions in order to act with org.apache.spark.sql.Column

    returns

    udf function to be applied to inputCols using this annotator's annotate function as part of ML transformation

    Definition Classes
    HasSimpleAnnotate
  7. def explainParam(param: Param[_]): String
    Definition Classes
    Params
  8. def explainParams(): String
    Definition Classes
    Params
  9. final def extractParamMap(): ParamMap
    Definition Classes
    Params
  10. final def extractParamMap(extra: ParamMap): ParamMap
    Definition Classes
    Params
  11. val features: ArrayBuffer[Feature[_, _, _]]
    Definition Classes
    HasFeatures
  12. final def get[T](param: Param[T]): Option[T]
    Definition Classes
    Params
  13. final def getDefault[T](param: Param[T]): Option[T]
    Definition Classes
    Params
  14. def getInputCols: Array[String]

    returns

    input annotations columns currently used

    Definition Classes
    HasInputAnnotationCols
  15. def getLazyAnnotator: Boolean
    Definition Classes
    CanBeLazy
  16. final def getOrDefault[T](param: Param[T]): T
    Definition Classes
    Params
  17. final def getOutputCol: String

    Gets annotation column name going to generate

    Gets annotation column name going to generate

    Definition Classes
    HasOutputAnnotationCol
  18. def getParam(paramName: String): Param[Any]
    Definition Classes
    Params
  19. def getStorageRef: String
    Definition Classes
    HasStorageRef
  20. def getVectors: DataFrame
  21. final def hasDefault[T](param: Param[T]): Boolean
    Definition Classes
    Params
  22. def hasParam(paramName: String): Boolean
    Definition Classes
    Params
  23. def hasParent: Boolean
    Definition Classes
    Model
  24. final def isDefined(param: Param[_]): Boolean
    Definition Classes
    Params
  25. final def isSet(param: Param[_]): Boolean
    Definition Classes
    Params
  26. val lazyAnnotator: BooleanParam
    Definition Classes
    CanBeLazy
  27. val optionalInputAnnotatorTypes: Array[String]
    Definition Classes
    HasInputAnnotationCols
  28. lazy val params: Array[Param[_]]
    Definition Classes
    Params
  29. var parent: Estimator[Word2VecModel]
    Definition Classes
    Model
  30. def save(path: String): Unit
    Definition Classes
    MLWritable
    Annotations
    @Since( "1.6.0" ) @throws( ... )
  31. def set[T](param: ProtectedParam[T], value: T): Word2VecModel.this.type

    Sets the value for a protected Param.

    Sets the value for a protected Param.

    If the parameter was already set, it will not be set again. Default values do not count as a set value and can be overridden.

    T

    Type of the parameter

    param

    Protected parameter to set

    value

    Value for the parameter

    returns

    This object

    Definition Classes
    HasProtectedParams
  32. final def set[T](param: Param[T], value: T): Word2VecModel.this.type
    Definition Classes
    Params
  33. final def setInputCols(value: String*): Word2VecModel.this.type
    Definition Classes
    HasInputAnnotationCols
  34. def setInputCols(value: Array[String]): Word2VecModel.this.type

    Overrides required annotators column if different than default

    Overrides required annotators column if different than default

    Definition Classes
    HasInputAnnotationCols
  35. def setLazyAnnotator(value: Boolean): Word2VecModel.this.type
    Definition Classes
    CanBeLazy
  36. final def setOutputCol(value: String): Word2VecModel.this.type

    Overrides annotation column name when transforming

    Overrides annotation column name when transforming

    Definition Classes
    HasOutputAnnotationCol
  37. def setParent(parent: Estimator[Word2VecModel]): Word2VecModel
    Definition Classes
    Model
  38. def setStorageRef(value: String): Word2VecModel.this.type
    Definition Classes
    HasStorageRef
  39. def toString(): String
    Definition Classes
    Identifiable → AnyRef → Any
  40. final def transform(dataset: Dataset[_]): DataFrame

    Given requirements are met, this applies ML transformation within a Pipeline or stand-alone Output annotation will be generated as a new column, previous annotations are still available separately metadata is built at schema level to record annotations structural information outside its content

    Given requirements are met, this applies ML transformation within a Pipeline or stand-alone Output annotation will be generated as a new column, previous annotations are still available separately metadata is built at schema level to record annotations structural information outside its content

    dataset

    Dataset[Row]

    Definition Classes
    AnnotatorModel → Transformer
  41. def transform(dataset: Dataset[_], paramMap: ParamMap): DataFrame
    Definition Classes
    Transformer
    Annotations
    @Since( "2.0.0" )
  42. def transform(dataset: Dataset[_], firstParamPair: ParamPair[_], otherParamPairs: ParamPair[_]*): DataFrame
    Definition Classes
    Transformer
    Annotations
    @Since( "2.0.0" ) @varargs()
  43. final def transformSchema(schema: StructType): StructType

    requirement for pipeline transformation validation.

    requirement for pipeline transformation validation. It is called on fit()

    Definition Classes
    RawAnnotator → PipelineStage
  44. val uid: String
    Definition Classes
    Word2VecModel → Identifiable
  45. def validateStorageRef(dataset: Dataset[_], inputCols: Array[String], annotatorType: String): Unit
    Definition Classes
    HasStorageRef
  46. def write: MLWriter
    Definition Classes
    ParamsAndFeaturesWritable → DefaultParamsWritable → MLWritable

Parameter setters

  1. def setDimension(value: Int): Word2VecModel.this.type

    Definition Classes
    HasEmbeddingsProperties
  2. def setVectorSize(value: Int): Word2VecModel.this.type

  3. def setWordVectors(value: Map[String, Array[Float]]): Word2VecModel.this.type

Parameter getters

  1. def getDimension: Int

    Definition Classes
    HasEmbeddingsProperties
  2. def getVectorSize: Int