我试图理解这里的代码。
f = open('/Users/nk/Vocab.txt','r')
vocab_temp = f.read().split()
f.close()
col = len(vocab_temp)
print("Training column size:")
print(col)
row = run('cat '+'/Users/nk/X_train.txt'+" | wc -l").split()[0]
print("Training row size:")
print(row)
matrix_tmp = np.zeros((int(row),col), dtype=np.int64)
print("Train Matrix size:")
print(matrix_tmp.size)
label_tmp = np.zeros((int(row)), dtype=np.int64)
f = open('/Users/nk/X_train.txt','r')
count = 0
for line in f:
line_tmp = line.split()
#print(line_tmp)
for word in line_tmp[0:]:
if word not in vocab_temp:
continue
matrix_tmp[count][vocab_temp.index(word)] = 1
count = count + 1
f.close()
据我了解,col
基本上是词汇表中的单词,row
是训练集中的文本数据。
我还了解到,在循环中,代码实际上是检查词汇表中存在的单词是否存在于训练集中。有人可以解释一下 continue
之后的行会做什么吗?
最佳答案
matrix_tmp[count][vocab_temp.index(word)] = 1
如果您查看代码,就会发现每行 count
都会增加 1。因此,matrix_tmp[count]
是每行的单词向量。
现在,考虑 vocab_temp.index(word)
,您可以在第二行中看到 vocab_temp
保留由 f.read 生成的向量().split()
.
事实上,它从 vocab_temp
中获取索引,它实际上获取了矩阵的位置(矩阵中单词 word
所在的索引)并设置它到 1(单词 word
出现在 index
位置)。
关于python - 这个向量是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34903222/