Python 用单词替换机器翻译中的生词
我正在研究机器学习人工智能翻译系统,我想让它更具适应性。现在,当单词是新单词时,我的代码将放置UNK,表示未知,并将其保留,但我想复制相同的单词并将其返回,而不是打印UNK,因此,如果一个新词出现,它应该传回与翻译相同的词,而不是UNK。我的代码目前如下所示: 有什么想法吗?我应该改变什么Python 用单词替换机器翻译中的生词,python,tensorflow,keras,nlp,machine-translation,Python,Tensorflow,Keras,Nlp,Machine Translation,我正在研究机器学习人工智能翻译系统,我想让它更具适应性。现在,当单词是新单词时,我的代码将放置UNK,表示未知,并将其保留,但我想复制相同的单词并将其返回,而不是打印UNK,因此,如果一个新词出现,它应该传回与翻译相同的词,而不是UNK。我的代码目前如下所示: 有什么想法吗?我应该改变什么 # Adding the word 'UNK' to the end of the array (stands for UNKNOWN words) X_ix_to_word.append('UNK'
# Adding the word 'UNK' to the end of the array (stands for UNKNOWN words)
X_ix_to_word.append('UNK')
# Creating the word-to-index dictionary from the array created above
X_word_to_ix = {word:ix for ix, word in enumerate(X_ix_to_word)}
# Converting each word to its index value
for i, sentence in enumerate(X):
for j, word in enumerate(sentence):
if word in X_word_to_ix:
X[i][j] = X_word_to_ix[word]
else:
X[i][j] = X_word_to_ix['UNK']
y_ix_to_word = [word[0] for word in y_vocab]
y_ix_to_word.insert(0, 'ZERO')
y_ix_to_word.append('UNK')
y_word_to_ix = {word:ix for ix, word in enumerate(y_ix_to_word)}
for i, sentence in enumerate(y):
for j, word in enumerate(sentence):
if word in y_word_to_ix:
y[i][j] = y_word_to_ix[word]
else:
y[i][j] = y_word_to_ix['UNK']
return (X, len(X_vocab)+2, X_word_to_ix, X_ix_to_word, y, len(y_vocab)+2, y_word_to_ix, y_ix_to_word)
def load_test_data(source, X_word_to_ix, max_len):
f = open(source, 'r')
X_data = f.read()
f.close()
X = [text_to_word_sequence(x)[::-1] for x in X_data.split('\n') if len(x) > 0 and len(x) <= max_len]
for i, sentence in enumerate(X):
for j, word in enumerate(sentence):
if word in X_word_to_ix:
X[i][j] = X_word_to_ix[word]
else:
X[i][j] = X_word_to_ix['UNK']
return X
#将单词“UNK”添加到数组末尾(表示未知单词)
X_ix_to_word.append('UNK'))
#从上面创建的数组创建单词索引字典
X_word_to_ix={word:ix代表ix,枚举中的单词(X_ix_to_word)}
#将每个单词转换为其索引值
对于i,枚举(X)中的句子:
对于j,枚举中的单词(句子):
如果X_word_至ix中的单词:
X[i][j]=X_单词到_ix[单词]
其他:
X[i][j]=X_word_to_ix['UNK']
y_ix_to_word=[y_vocab中单词的单词[0]
y_ix_to_word.插入(0,'零')
y_ix_to_word.append('UNK'))
y_word_to_ix={word:ix代表ix,枚举中的单词(y_ix_to_word)}
对于i,列举(y)中的句子:
对于j,枚举中的单词(句子):
如果y_单词_至_ix中的单词:
y[i][j]=y_word_to_ix[word]
其他:
y[i][j]=y_word_to_ix['UNK']
返回(X,len(X_vocab)+2,X_word_to_ix,X_ix_to_word,y,len(y_vocab)+2,y_word_to_ix,y_ix_to_word)
def load_test_数据(源、X字到X字、最大长度):
f=开放(源代码“r”)
X_data=f.read()
f、 关闭()
X=[text_to_word_sequence(X)[::-1]表示X_数据中的X。如果len(X)>0且len(X)则拆分('\n'),这不是一个容易的问题
您建议在数据预处理级别替换单词。为此,您需要进行单词对齐,以告诉您哪些源单词与目标单词匹配。有类似的工具。即使进行了对齐,也不能保证复制的源单词将在目标词汇表中
一些人试图在建模级别上解决这个问题,并在他们的网络中包含显式复制机制(如),但是这使得网络变得相当复杂,并且只提供了一点改进
这个问题最常见的解决方法是使用基于子词的词汇表,如或。使用这些方法,不常用的词会被分割成更小的单位,因此词汇表的末尾不会有任何内容。如果单词在源端和目标端都相同(这通常发生在专有名称上),它将在源语言和目标语言中以相同的方式进行分割,模型将了解到复制单词片段是它通常应该做的事情。因此,不可能将我的代码更改为将UNK替换为源语言到目标语言中的单词。如果您经过培训,然后应用FastAlign模型,这是可能的(这是一个很大的工作),但这对翻译模型没有帮助。因此,在我的代码中,没有办法将单词从源代码传递到目标代码,就像它一样?如果不应用任何东西,就没有办法。