python - 如何将基于列表的代码转换为基于numpy数组的代码?

标签 python arrays python-3.x numpy keras

我正在使用 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/

相关文章:

c# - C#返回类数组中单个变量的数组

javascript - 如何从多维数组中过滤产品?

python-3.x - Psycopg2 用一个查询更新多行

python - Django Rest Framework Serializer中,如何获取图片的完整路径?

python - 从 Python 中查找系统硬盘驱动器?

python - 使用 urllib2 登录网站 - Python 2.7

Python 3 相当于 Python 2 str.decode ('hex' )

python - 在数据框中插入缺失的数字

java - 基于多个输入使用 hamcrest 和 lambdaj 比较对象

python - 如何有效地在迭代器上迭代 "n-wise"