我正在使用 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)
最佳答案
output_sentence = []
for key in row['o'].lower():
if key not in dictionary.keys():
dictionary[key] = len(dictionary)
output_sentence.append(dictionary[key])
final_output_sentence = np.array(output_sentence).reshape(1,-1,1)
- 如果字典中不存在
键
,则使用下一个大小添加它 - 将key对应的值追加到
output_sentence
- 最后,
output_sentence
是一个列表,但由于您需要一个 3D 数组,因此请将其转换为 numpy 数组并 reshape 它。 - x.reshape(1,-1,1) => reshape x 的形状,使第 0 轴的大小为 1,第 2 轴的大小为 1,第 1 轴的大小与 x 中的元素相同。
关于python - 如何将基于列表的代码转换为基于numpy数组的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55318474/