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
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
add a comment |
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
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
add a comment |
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
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
scala apache-spark apache-spark-ml
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
add a comment |
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
add a comment |
1 Answer
1
active
oldest
votes
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.
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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.
add a comment |
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.
add a comment |
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.
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.
edited Mar 8 at 20:00
answered Mar 8 at 14:49
user10958683user10958683
7759
7759
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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