[英]Read a matrix from a file in Scala Breeze
I want to read a tab-delimited text file into a Breeze DenseMatrix. 我想将制表符分隔的文本文件读入Breeze DenseMatrix。 I see in the ScalaDoc that this should be possible and there are a whole set of I/O classes, but I can't find any examples and it's hard to digest the ScalaDoc. 我在ScalaDoc中看到这应该是可能的,并且有一整套I / O类,但我找不到任何示例,并且很难消化ScalaDoc。
Can someone provide a simple read/write example? 有人可以提供简单的读/写示例吗?
There's a way to read a csv file into densematrix 有一种方法可以将csv文件读入densematrix
import breeze.linalg._
import java.io._
val matrix=csvread(new File("your file localtion"),',')
api: http://www.scalanlp.org/api/breeze/index.html#breeze.linalg.package api: http : //www.scalanlp.org/api/breeze/index.html#breeze.linalg.package
You can use scala.io.Source
to read in tab delimited data from file. 您可以使用scala.io.Source
从文件中读取制表符分隔的数据。
Some sample data: 一些样本数据:
0 1 2 3 4 5
6 7 8 9 10 11
One of the DenseMatrix
constructors has this form new DenseMatrix(rows: Int, data: Array[V], offset: Int = 0)
so I'll use that. 其中一个DenseMatrix
构造函数具有这种形式的new DenseMatrix(rows: Int, data: Array[V], offset: Int = 0)
所以我将使用它。
Get the number of rows: 获取行数:
scala> scala.io.Source.fromFile("TabDelimited.txt").getLines.size
res 0:Int = 2
Then get the data as an Array[Int]
: 然后将数据作为Array[Int]
:
scala> scala.io.Source.fromFile("TabDelimited.txt").getLines.toArray.flatMap(_.split("\t")).map(_.toInt)
res1: Array[Int] = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
Then res0
and res1
can be used to create a new DenseMatrix
. 然后res0
和res1
可用于创建新的DenseMatrix
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.