我正在使用keras,并且总是有一个from列表,所以我想总是将所有内容都转换为numpy数组,这对我来说是非常不合逻辑的。我想这与性能有关吗?我没有其他原因吗?但是我的问题如下所示。我必须转换这部分代码:
output_sentence = []
final_output_sentence = []
for key in row['o'].lower():
temp_list = []
if key in dictionary.keys():
temp_list.append(dictionary[key])
output_sentence.append(temp_list)
else:
dictionary[key] = len(dictionary)
temp_list.append(dictionary[key])
output_sentence.append(temp_list)
final_output_sentence.append(output_sentence)
基于numpy数组的代码。我以这种方式尝试:
output_sentence = np.array([], dtype=int)
final_output_sentence = np.array([], dtype=int)
for key in row['o'].lower():
temp_list = np.array([], dtype=int)
if key in dictionary.keys():
temp_list = np.append(temp_list, dictionary[key])
output_sentence = np.append(output_sentence, temp_list)
else:
dictionary[key] = len(dictionary)
temp_list = np.append(temp_list, dictionary[key])
output_sentence = np.append(output_sentence, temp_list)
final_output_sentence = np.append(final_output_sentence, output_sentence)
但是我得到了这个[[[1], [2], [3], [2], [4]]]
,而不是这个[1 2 3 2 4]
。有什么想法可以解决这个问题吗?
更新
您如何看待以下所示的解决方案?有关性能优化的任何技巧?
output_sentence = []
for key in row['o'].lower():
temp_list = []
if key in dictionary.keys():
temp_list.append(dictionary[key])
output_sentence.append(temp_list)
else:
dictionary[key] = len(dictionary)
temp_list.append(dictionary[key])
output_sentence.append(temp_list)
final_output_sentence = np.array(output_sentence)
final_output_sentence = final_output_sentence.reshape(1, final_output_sentence.shape[0], 1)
答案 0 :(得分:1)
key
output_sentence
,请添加下一个大小output_sentence
dict
是一个列表,但是由于您需要3D数组,因此将其转换为numpy数组并重塑形状。