gpt4 book ai didi

linux - 从两个文本文件(平行语料库)中连续随机抽取 N 行

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:26:12 24 4
gpt4 key购买 nike

一次又一次,我面临着从两个文件(即从平行语料库)中抽取特定行数(比方说 N)的问题;句子根据到行号)一致

对于从事(神经)机器翻译研究的任何人来说,这是一项常见且频繁的任务。

我想知道一种快速有效的抽样方法(即选择) N 来自平行语料库的行,可能来自命令行。

例如,如果我们要选择4以一致的方式来自两个文件的行,我们可以在行号 3 处对行进行采样, 12 , 17 , 23 .这应该为我们提供来自两个文件的这些行。另外,最好有这个参数 N随意,这样我们就可以随心所欲地改变它。此外,应该对这些行进行采样,不要重复。并且,所需的行数 N需要采样的行数将始终少于两个文件中的总行数,其中两个文件的总行数将始终相等。

一旦我们对所需的行进行采样,还希望从两个文件中获取尚未采样的行(即获取随机采样中未选择的其余行)。

The whole idea of doing this is to sample two files in a consistent manner such that their line-alignments are preserved. (i.e. choose N lines and N-T lines where T is the total number of lines.)

哪里N是不重复采样所需的行数,N-T是其余未采样的行。

我该怎么做呢?提前致谢!

最佳答案

如果不允许重复,最好使用shuffle算法。已经有用于此目的的工具 shuf

例如,

$ shuf -n 10 file

将从文件中随机选择 10 行(随机顺序)。您的请求有两个额外的约束,首先应该对选择进行排序,其次选择需要与另一次运行保持一致。对于第二个要求,您可以将随机源提供给 shuf 以两次获得相同的序列。对于排序,我们自己...

$ shuf -n 10 --random-source=file <(cat -n file1) | sort -n | cut -f2- > sample1
$ shuf -n 10 --random-source=file <(cat -n file2) | sort -n | cut -f2- > sample2

将以正确的顺序为您提供相同的采样行。对于随机性,您可以使用文件或任何其他第三方文件(但两次运行应该相同)。

另一种方法是将两个文件粘贴在一起,进行一次随机播放,然后拆分样本。

$ paste -d'|' file1 file2 | cat -n | shuf -n 10 | sort -n | cut -f2 > sample

$ cut -d'|' -f1 sample > sample1
$ cut -d'|' -f2 sample > sample2

要获取未选中的行,您需要保留行号。使用第二种选择

$ paste -d'|' file1 file2 | cat -n | shuf -n 10 | sort -n > n_samples
$ cut -f2- n_samples > samples
$ awk 'NR==FNR{a[$1];next} !(FNR in a)' <(cut -f1 n_samples) samples > notselected

并且您可以像以前一样拆分样本和未选择的文件。

使用第一种选择,文件中未选择的行将被写入具有相同名称和扩展名“.not”的文件

$ cat -n file1 | shuf -n 10 --random-source=file | sort -n > n_sample1
$ cut -f2- n_sample1 > sample1
$ cat -n file2 | shuf -n 10 --random-source=file | sort -n | cut -f2- > sample2
$ awk 'NR==FNR {a[$1];next}
!(FNR in a) {print > FILENAME".not"}' <(cut -f1 n_sample1) sample1 sample2

关于linux - 从两个文本文件(平行语料库)中连续随机抽取 N 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49037494/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com