How can I make a function generic on an MLReader The Next CEO of Stack OverflowRequiring an argument extends a particular class AND implements a particular interfaceHow can a time function exist in functional programming?What is the apply function in Scala?Best way to add and extend a generic writer trait for step by step data storageTask not serializable: java.io.NotSerializableException when calling function outside closure only on classes not objectshow to make saveAsTextFile NOT split output into multiple file?Scala: trait extends java.nio.file.FileVisitorflatMap Compile Error found: TraversableOnce[String] required: TraversableOnce[String]Error with RDD[Vector] in function parameterBucketedRandomProjectionLSHModel approxNearestNeighbors function on entire dataframe

Can this note be analyzed as a non-chord tone?

Why is the US ranked as #45 in Press Freedom ratings, despite its extremely permissive free speech laws?

Are the names of these months realistic?

Why am I getting "Static method cannot be referenced from a non static context: String String.valueOf(Object)"?

What steps are necessary to read a Modern SSD in Medieval Europe?

What day is it again?

What is the process for cleansing a very negative action

what's the use of '% to gdp' type of variables?

Cannot shrink btrfs filesystem although there is still data and metadata space left : ERROR: unable to resize '/home': No space left on device

Lucky Feat: How can "more than one creature spend a luck point to influence the outcome of a roll"?

Audio Conversion With ADS1243

Can you teleport closer to a creature you are Frightened of?

IC has pull-down resistors on SMBus lines?

Why do we say 'Un seul M' and not 'Une seule M' even though M is a "consonne"

Is there an equivalent of cd - for cp or mv

Is it correct to say moon starry nights?

Can Sneak Attack be used when hitting with an improvised weapon?

Physiological effects of huge anime eyes

Film where the government was corrupt with aliens, people sent to kill aliens are given rigged visors not showing the right aliens

How to get the last not-null value in an ordered column of a huge table?

What difference does it make using sed with/without whitespaces?

Getting Stale Gas Out of a Gas Tank w/out Dropping the Tank

how one can write a nice vector parser, something that does pgfvecparseA=B-C; D=E x F;

Can I calculate next year's exemptions based on this year's refund/amount owed?



How can I make a function generic on an MLReader



The Next CEO of Stack OverflowRequiring an argument extends a particular class AND implements a particular interfaceHow can a time function exist in functional programming?What is the apply function in Scala?Best way to add and extend a generic writer trait for step by step data storageTask not serializable: java.io.NotSerializableException when calling function outside closure only on classes not objectshow to make saveAsTextFile NOT split output into multiple file?Scala: trait extends java.nio.file.FileVisitorflatMap Compile Error found: TraversableOnce[String] required: TraversableOnce[String]Error with RDD[Vector] in function parameterBucketedRandomProjectionLSHModel approxNearestNeighbors function on entire dataframe










1















I am working in Spark 1.6.3. Here are two functions that do the same thing:



def modelFromBytesCV(modelArray: Array[Byte]): CountVectorizerModel = 
val tempPath: Path = KAZOO_TEMP_DIR.resolve(s"model_$System.currentTimeMillis()")
Files.write(tempPath, modelArray)
CountVectorizerModel.read.load(tempPath.toString)


def modelFromBytesIDF(modelArray: Array[Byte]): IDFModel =
val tempPath: Path = KAZOO_TEMP_DIR.resolve(s"model_$System.currentTimeMillis()")
Files.write(tempPath, modelArray)
IDFModel.read.load(tempPath.toString)



I would like to make these functions generic. What I am hung up on is that the common trait between the CountVectorizerModel object and IDFModel is MLReadable[T] which itself must take as a type either CountVectorizerModel or IDFModel. This is sort of a recursive parent class loop that I can't figure out a solution to.



By comparison, the generic model writer is easy, because MLWritable is a common trait extended by all the models I am interested in:



def modelToBytes[M <: MLWritable](model: M): Array[Byte] = 
val tempPath: Path = KAZOO_TEMP_DIR.resolve(s"model_$System.currentTimeMillis()")
model.write.overwrite().save(tempPath.toString)
Files.readAllBytes(tempPath)



How can I make a generic reader that will turn turn a spark-ml model into a byte array?










share|improve this question






















  • Note: the accepted solution answers the question in the title, but the code doesn't work because you can't write a model to and from a single file. A model is written to a folder; my full implementation involves tar-ing the folder and converting that to a byte array. Just be aware.

    – kingledion
    Mar 8 at 18:12















1















I am working in Spark 1.6.3. Here are two functions that do the same thing:



def modelFromBytesCV(modelArray: Array[Byte]): CountVectorizerModel = 
val tempPath: Path = KAZOO_TEMP_DIR.resolve(s"model_$System.currentTimeMillis()")
Files.write(tempPath, modelArray)
CountVectorizerModel.read.load(tempPath.toString)


def modelFromBytesIDF(modelArray: Array[Byte]): IDFModel =
val tempPath: Path = KAZOO_TEMP_DIR.resolve(s"model_$System.currentTimeMillis()")
Files.write(tempPath, modelArray)
IDFModel.read.load(tempPath.toString)



I would like to make these functions generic. What I am hung up on is that the common trait between the CountVectorizerModel object and IDFModel is MLReadable[T] which itself must take as a type either CountVectorizerModel or IDFModel. This is sort of a recursive parent class loop that I can't figure out a solution to.



By comparison, the generic model writer is easy, because MLWritable is a common trait extended by all the models I am interested in:



def modelToBytes[M <: MLWritable](model: M): Array[Byte] = 
val tempPath: Path = KAZOO_TEMP_DIR.resolve(s"model_$System.currentTimeMillis()")
model.write.overwrite().save(tempPath.toString)
Files.readAllBytes(tempPath)



How can I make a generic reader that will turn turn a spark-ml model into a byte array?










share|improve this question






















  • Note: the accepted solution answers the question in the title, but the code doesn't work because you can't write a model to and from a single file. A model is written to a folder; my full implementation involves tar-ing the folder and converting that to a byte array. Just be aware.

    – kingledion
    Mar 8 at 18:12













1












1








1








I am working in Spark 1.6.3. Here are two functions that do the same thing:



def modelFromBytesCV(modelArray: Array[Byte]): CountVectorizerModel = 
val tempPath: Path = KAZOO_TEMP_DIR.resolve(s"model_$System.currentTimeMillis()")
Files.write(tempPath, modelArray)
CountVectorizerModel.read.load(tempPath.toString)


def modelFromBytesIDF(modelArray: Array[Byte]): IDFModel =
val tempPath: Path = KAZOO_TEMP_DIR.resolve(s"model_$System.currentTimeMillis()")
Files.write(tempPath, modelArray)
IDFModel.read.load(tempPath.toString)



I would like to make these functions generic. What I am hung up on is that the common trait between the CountVectorizerModel object and IDFModel is MLReadable[T] which itself must take as a type either CountVectorizerModel or IDFModel. This is sort of a recursive parent class loop that I can't figure out a solution to.



By comparison, the generic model writer is easy, because MLWritable is a common trait extended by all the models I am interested in:



def modelToBytes[M <: MLWritable](model: M): Array[Byte] = 
val tempPath: Path = KAZOO_TEMP_DIR.resolve(s"model_$System.currentTimeMillis()")
model.write.overwrite().save(tempPath.toString)
Files.readAllBytes(tempPath)



How can I make a generic reader that will turn turn a spark-ml model into a byte array?










share|improve this question














I am working in Spark 1.6.3. Here are two functions that do the same thing:



def modelFromBytesCV(modelArray: Array[Byte]): CountVectorizerModel = 
val tempPath: Path = KAZOO_TEMP_DIR.resolve(s"model_$System.currentTimeMillis()")
Files.write(tempPath, modelArray)
CountVectorizerModel.read.load(tempPath.toString)


def modelFromBytesIDF(modelArray: Array[Byte]): IDFModel =
val tempPath: Path = KAZOO_TEMP_DIR.resolve(s"model_$System.currentTimeMillis()")
Files.write(tempPath, modelArray)
IDFModel.read.load(tempPath.toString)



I would like to make these functions generic. What I am hung up on is that the common trait between the CountVectorizerModel object and IDFModel is MLReadable[T] which itself must take as a type either CountVectorizerModel or IDFModel. This is sort of a recursive parent class loop that I can't figure out a solution to.



By comparison, the generic model writer is easy, because MLWritable is a common trait extended by all the models I am interested in:



def modelToBytes[M <: MLWritable](model: M): Array[Byte] = 
val tempPath: Path = KAZOO_TEMP_DIR.resolve(s"model_$System.currentTimeMillis()")
model.write.overwrite().save(tempPath.toString)
Files.readAllBytes(tempPath)



How can I make a generic reader that will turn turn a spark-ml model into a byte array?







scala apache-spark apache-spark-ml






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 8 at 14:05









kingledionkingledion

833719




833719












  • Note: the accepted solution answers the question in the title, but the code doesn't work because you can't write a model to and from a single file. A model is written to a folder; my full implementation involves tar-ing the folder and converting that to a byte array. Just be aware.

    – kingledion
    Mar 8 at 18:12

















  • Note: the accepted solution answers the question in the title, but the code doesn't work because you can't write a model to and from a single file. A model is written to a folder; my full implementation involves tar-ing the folder and converting that to a byte array. Just be aware.

    – kingledion
    Mar 8 at 18:12
















Note: the accepted solution answers the question in the title, but the code doesn't work because you can't write a model to and from a single file. A model is written to a folder; my full implementation involves tar-ing the folder and converting that to a byte array. Just be aware.

– kingledion
Mar 8 at 18:12





Note: the accepted solution answers the question in the title, but the code doesn't work because you can't write a model to and from a single file. A model is written to a folder; my full implementation involves tar-ing the folder and converting that to a byte array. Just be aware.

– kingledion
Mar 8 at 18:12












1 Answer
1






active

oldest

votes


















2














To make it work you'll need access to a specific MlReadable object.



import org.apache.spark.ml.util.MLReadable

def modelFromBytes[M](obj: MLReadable[M], modelArray: Array[Byte]): M =
val tempPath: Path = ???
...
obj.read.load(tempPath.toString)



which could be later used as:



val bytes: Array[Byte] = ???
modelFromBytes(CountVectorizerModel, bytes)


Note that, despite the first appearance, there is nothing recursive here - MLReadable[M] refers to companion object, not class as such. So for example CountVectorizerModel object is MLReadable, while CountVectorizeModel class isn't.



Internally, Spark MLReader handles this in a different way - it creates an instance of the class using reflection, and then sets its Params. However this path won't be very useful for you here*.



If compatibility with the current API is required, you can try making readable object implicit:



def modelFromBytes[M](modelArray: Array[Byte])(implicit obj: MLReadable[M]): M = 
...



and then



implicit val readable: MLReadable[CountVectorizerModel] = CountVectorizerModel

modelFromBytes[CountVectorizerModel](bytes)



* Technically speaking it is possible to get companion object via reflection





def modelFromBytesCV[M <: MLWritable](
modelArray: Array[Byte])(implicit ct: ClassTag[M]): M =
val tempPath: Path = ???
...
val cls = Class.forName(ct.runtimeClass.getName + "$");
cls.getField("MODULE$").get(cls).asInstanceOf[MLReadable[M]]
.read.load(tempPath.toString))





but I don't think that is a path worth exploring here. In particular we cannot really provide strict type bounds here - using MLWritable is a hack to limit human errors, but is rather useless for compiler.






share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55064874%2fhow-can-i-make-a-function-generic-on-an-mlreader%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    To make it work you'll need access to a specific MlReadable object.



    import org.apache.spark.ml.util.MLReadable

    def modelFromBytes[M](obj: MLReadable[M], modelArray: Array[Byte]): M =
    val tempPath: Path = ???
    ...
    obj.read.load(tempPath.toString)



    which could be later used as:



    val bytes: Array[Byte] = ???
    modelFromBytes(CountVectorizerModel, bytes)


    Note that, despite the first appearance, there is nothing recursive here - MLReadable[M] refers to companion object, not class as such. So for example CountVectorizerModel object is MLReadable, while CountVectorizeModel class isn't.



    Internally, Spark MLReader handles this in a different way - it creates an instance of the class using reflection, and then sets its Params. However this path won't be very useful for you here*.



    If compatibility with the current API is required, you can try making readable object implicit:



    def modelFromBytes[M](modelArray: Array[Byte])(implicit obj: MLReadable[M]): M = 
    ...



    and then



    implicit val readable: MLReadable[CountVectorizerModel] = CountVectorizerModel

    modelFromBytes[CountVectorizerModel](bytes)



    * Technically speaking it is possible to get companion object via reflection





    def modelFromBytesCV[M <: MLWritable](
    modelArray: Array[Byte])(implicit ct: ClassTag[M]): M =
    val tempPath: Path = ???
    ...
    val cls = Class.forName(ct.runtimeClass.getName + "$");
    cls.getField("MODULE$").get(cls).asInstanceOf[MLReadable[M]]
    .read.load(tempPath.toString))





    but I don't think that is a path worth exploring here. In particular we cannot really provide strict type bounds here - using MLWritable is a hack to limit human errors, but is rather useless for compiler.






    share|improve this answer





























      2














      To make it work you'll need access to a specific MlReadable object.



      import org.apache.spark.ml.util.MLReadable

      def modelFromBytes[M](obj: MLReadable[M], modelArray: Array[Byte]): M =
      val tempPath: Path = ???
      ...
      obj.read.load(tempPath.toString)



      which could be later used as:



      val bytes: Array[Byte] = ???
      modelFromBytes(CountVectorizerModel, bytes)


      Note that, despite the first appearance, there is nothing recursive here - MLReadable[M] refers to companion object, not class as such. So for example CountVectorizerModel object is MLReadable, while CountVectorizeModel class isn't.



      Internally, Spark MLReader handles this in a different way - it creates an instance of the class using reflection, and then sets its Params. However this path won't be very useful for you here*.



      If compatibility with the current API is required, you can try making readable object implicit:



      def modelFromBytes[M](modelArray: Array[Byte])(implicit obj: MLReadable[M]): M = 
      ...



      and then



      implicit val readable: MLReadable[CountVectorizerModel] = CountVectorizerModel

      modelFromBytes[CountVectorizerModel](bytes)



      * Technically speaking it is possible to get companion object via reflection





      def modelFromBytesCV[M <: MLWritable](
      modelArray: Array[Byte])(implicit ct: ClassTag[M]): M =
      val tempPath: Path = ???
      ...
      val cls = Class.forName(ct.runtimeClass.getName + "$");
      cls.getField("MODULE$").get(cls).asInstanceOf[MLReadable[M]]
      .read.load(tempPath.toString))





      but I don't think that is a path worth exploring here. In particular we cannot really provide strict type bounds here - using MLWritable is a hack to limit human errors, but is rather useless for compiler.






      share|improve this answer



























        2












        2








        2







        To make it work you'll need access to a specific MlReadable object.



        import org.apache.spark.ml.util.MLReadable

        def modelFromBytes[M](obj: MLReadable[M], modelArray: Array[Byte]): M =
        val tempPath: Path = ???
        ...
        obj.read.load(tempPath.toString)



        which could be later used as:



        val bytes: Array[Byte] = ???
        modelFromBytes(CountVectorizerModel, bytes)


        Note that, despite the first appearance, there is nothing recursive here - MLReadable[M] refers to companion object, not class as such. So for example CountVectorizerModel object is MLReadable, while CountVectorizeModel class isn't.



        Internally, Spark MLReader handles this in a different way - it creates an instance of the class using reflection, and then sets its Params. However this path won't be very useful for you here*.



        If compatibility with the current API is required, you can try making readable object implicit:



        def modelFromBytes[M](modelArray: Array[Byte])(implicit obj: MLReadable[M]): M = 
        ...



        and then



        implicit val readable: MLReadable[CountVectorizerModel] = CountVectorizerModel

        modelFromBytes[CountVectorizerModel](bytes)



        * Technically speaking it is possible to get companion object via reflection





        def modelFromBytesCV[M <: MLWritable](
        modelArray: Array[Byte])(implicit ct: ClassTag[M]): M =
        val tempPath: Path = ???
        ...
        val cls = Class.forName(ct.runtimeClass.getName + "$");
        cls.getField("MODULE$").get(cls).asInstanceOf[MLReadable[M]]
        .read.load(tempPath.toString))





        but I don't think that is a path worth exploring here. In particular we cannot really provide strict type bounds here - using MLWritable is a hack to limit human errors, but is rather useless for compiler.






        share|improve this answer















        To make it work you'll need access to a specific MlReadable object.



        import org.apache.spark.ml.util.MLReadable

        def modelFromBytes[M](obj: MLReadable[M], modelArray: Array[Byte]): M =
        val tempPath: Path = ???
        ...
        obj.read.load(tempPath.toString)



        which could be later used as:



        val bytes: Array[Byte] = ???
        modelFromBytes(CountVectorizerModel, bytes)


        Note that, despite the first appearance, there is nothing recursive here - MLReadable[M] refers to companion object, not class as such. So for example CountVectorizerModel object is MLReadable, while CountVectorizeModel class isn't.



        Internally, Spark MLReader handles this in a different way - it creates an instance of the class using reflection, and then sets its Params. However this path won't be very useful for you here*.



        If compatibility with the current API is required, you can try making readable object implicit:



        def modelFromBytes[M](modelArray: Array[Byte])(implicit obj: MLReadable[M]): M = 
        ...



        and then



        implicit val readable: MLReadable[CountVectorizerModel] = CountVectorizerModel

        modelFromBytes[CountVectorizerModel](bytes)



        * Technically speaking it is possible to get companion object via reflection





        def modelFromBytesCV[M <: MLWritable](
        modelArray: Array[Byte])(implicit ct: ClassTag[M]): M =
        val tempPath: Path = ???
        ...
        val cls = Class.forName(ct.runtimeClass.getName + "$");
        cls.getField("MODULE$").get(cls).asInstanceOf[MLReadable[M]]
        .read.load(tempPath.toString))





        but I don't think that is a path worth exploring here. In particular we cannot really provide strict type bounds here - using MLWritable is a hack to limit human errors, but is rather useless for compiler.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 8 at 20:00

























        answered Mar 8 at 14:49









        user10958683user10958683

        7759




        7759





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55064874%2fhow-can-i-make-a-function-generic-on-an-mlreader%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

            Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

            2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived