如何在 tensorflow 中将字典转换为张量 [英] How to convert a dictionary into a tensor in tensorflow
问题描述
这是我的字典:
docs = {'computer': {'1': 1, '3': 5, '8': 2},
'politics': {'0': 2, '1': 2, '3': 1}}
我想像这样创建一个 9 * 2 张量
:
I want to create a 9 * 2 tensor
like this:
[
[0, 1, 0, 5, 0, 0, 0, 0, 2],
[2, 2, 0, 1, 0, 0, 0, 0, 0, 0]
]
这里,因为最大项目是 8,所以我们有 9 行.但是,可以根据字典增加行数和列数.
Here, because the max item is 8 so we have 9 rows. But, the number of rows and columns can increase based on the dictionary.
我已经尝试使用 for-loop
来实现这一点,但由于字典很大,它根本没有效率,而且它使用我需要的列表来实现 tensor代码>.
I have tried to implement this using for-loop
though as the dictionary is big it's not efficient at all and also it implemented using the list I need that to be a tensor
.
maxr = 0
for i, val in docs.items():
for j in val.keys():
if int(j) > int(maxr):
maxr = int(j)
final_lst = []
for val in docs.values():
lst = [0] * (maxr+1)
for j, val2 in sorted(val.items()):
lst[int(j)] = val2
final_lst.append(lst)
print(final_lst)
推荐答案
如果您可以使用 pandas
和 numpy
,这里是您可以使用的方法.
If you are ok with using pandas
and numpy
, here's how you can do it.
import pandas as pd
import numpy as np
# Creates a dataframe with keys as index and values as cell values.
df = pd.DataFrame(docs)
# Create a new set of index from min and max of the dictionary keys.
new_index = np.arange( int(df.index.min()),
int(df.index.max())).astype(str)
# Add the new index to the existing index and fill the nan values with 0, take a transpose of dataframe.
new_df = df.reindex(new_index).fillna(0).T.astype(int)
# 0 1 2 3 4 5 6 7
#computer 0 1 0 5 0 0 0 0
#politics 2 2 0 1 0 0 0 0
如果你只想要数组,你可以调用array = new_df.values
.
If you just want the array, you can call array = new_df.values
.
#[[0 1 0 5 0 0 0 0]
# [2 2 0 1 0 0 0 0]]
如果你想要张量,那么你可以使用 tf.convert_to_tensor(new_df.values)
If you want tensor, then you can use tf.convert_to_tensor(new_df.values)
这篇关于如何在 tensorflow 中将字典转换为张量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!