用烫伤法,我试图找到相似字符串对之间的编辑距离。总之,我有10000个字符串在一个csv文件。为了减少计算量,我使用以下算法:
使用前三个字符作为键将所有字符串分组
在每个组中生成两个字符串的组合
查找每组中每对字符串的编辑距离(请参见下面的代码)
当我在hdfs上运行这个算法时,它可以处理1000000个字符串。有10000个字符串,节点管理器抱怨我的“Map”作业试图分配比节点更多的物理内存。我知道,这种情况发生时,大量的组合是建立在 .groupBy('key) { _.mapList ...}
代码。当然,这个算法并没有真正的规模。
请建议其他方法来减少这项任务的计算。
import cascading.tuple.Fields
import com.twitter.scalding._
class Proto1(args: Args) extends Job(args) {
val outputStr = "tmp/out.txt"
val output = TextLine(outputStr)
val wordsList = List(
("aaaa"),
("aaaa"),
("aaaad"),
("aaaab"),
("aaabb"),
("aabbcc"),
("aaabccdd"),
("aaabbccdde"),
("aaabbddd"),
("bbbb"),
("bbbb"),
("bbbaaa"),
("bbaaabb"),
("bbbcccc"),
("bbbddde"),
("bbbdddd"),
("bbbdddf"),
("bbbdddd"),
("ccccc"),
("cccaaa"),
("ccccaabbb"),
("ccbbbddd"),
("cdddeee"),
("ddd"),
("ddd")
)
val orderedPipe =
IterableSource[(String)](wordsList, ('word))
.map('word -> 'key) { word: String => word.take(3) }
.debug
//.groupBy('key) { _.toList[String]('word -> 'list) }
//.debug
.groupBy('key) { _.mapList[String, List[(String, String, Int)]]('word -> 'list)(editDistances) }
.filterNot('key, 'list) { fields: (String, List[(String, String, Int)]) =>
val (key, list) = fields
list.isEmpty
}
.flatMapTo('list -> ('str1, 'str2, 'dist)) {list:List[(String, String, Int)] => list }
.debug
//.write(output)
.write(Csv(outputStr))
def editDistances(list: List[String]): List[(String, String, Int)] = {
val resultList = list.combinations(2).toList.map(x => (x(0), x(1), editDistance(x(0), x(1))))
//println(resultList+"\n")
val result = resultList.filter(x => x._3 <= 1)
result
}
def editDistance(a: String, b: String): Int = {
import scala.math.min
def min3(x: Int, y: Int, z: Int) = min(min(x, y), z)
val (m, n) = (a.length, b.length)
val matrix = Array.fill(m + 1, n + 1)(0)
for (i <- 0 to m; j <- 0 to n) {
matrix(i)(j) = if (i == 0) j
else if (j == 0) i
else if (a(i - 1) == b(j - 1)) matrix(i - 1)(j - 1)
else min3(
matrix(i - 1)(j) + 1,
matrix(i)(j - 1) + 1,
matrix(i - 1)(j - 1) + 1)
}
matrix(m)(n)
}
}
有什么想法吗?
暂无答案!
目前还没有任何答案,快来回答吧!