Python 变换期间从tensorflow对象中提取numpy值

Python 变换期间从tensorflow对象中提取numpy值,python,tensorflow,word-embedding,tfrecord,tf.data.dataset,Python,Tensorflow,Word Embedding,Tfrecord,Tf.data.dataset,我正在尝试使用tensorflow获取单词嵌入,并使用我的语料库创建了相邻的工作列表 我的vocab中的唯一单词数量为8000个,相邻单词列表的数量约为160万个 由于数据非常大,我正在尝试将单词列表批量写入TFRecords文件 def save_tfrecords_wordlist(toprocess_word_lists, path ): writer = tf.io.TFRecordWriter(path) for word_list in toprocess

我正在尝试使用tensorflow获取单词嵌入,并使用我的语料库创建了相邻的工作列表

我的vocab中的唯一单词数量为8000个,相邻单词列表的数量约为160万个

由于数据非常大,我正在尝试将单词列表批量写入TFRecords文件

def save_tfrecords_wordlist(toprocess_word_lists, path ):    
    writer = tf.io.TFRecordWriter(path)

    for word_list in toprocess_word_lists:
        features=tf.train.Features(
            feature={
        'word_list_X': tf.train.Feature( bytes_list=tf.train.BytesList(value=[word_list[0].encode('utf-8')] )),
        'word_list_Y': tf.train.Feature( bytes_list=tf.train.BytesList(value=[word_list[1].encode('utf-8') ]))
                }
            )
        example = tf.train.Example(features = features)
        writer.write(example.SerializeToString())
    writer.close()
定义批次 ##############################

def_parse_函数(示例proto):
features={“word_list_X”:tf.io.FixedLenFeature((),tf.string),
“单词列表”:tf.io.FixedLenFeature((),tf.string)}
parsed_features=tf.io.parse_single_示例(示例_proto,features)
"""
word_list_X=已解析的_功能['word_list_X'].numpy()
word_list_Y=已解析的_功能['word_list_Y']。numpy()
##需要帮助的是从parsed_features变量中获取numpy值,这样我就可以得到一个热编码矩阵,它可以直接发送给tensorflow进行训练
示例单词列表值为
示例单词列表(Y值为)
"""
返回已解析的_要素['word_list_X'],已解析的_要素['word_list_Y']
文件名=[path+“/JustEat\TFRecords/data.TFRecords”]
dataset=tf.data.TFRecordDataset(文件名)
dataset=dataset.map(_parse_函数)
数据集=数据集。批处理(10)
#定义嵌入的大小
嵌入尺寸=100
#定义神经网络
inp=tf.keras.Input(shape=(7958,))
x=tf.keras.layers.density(单位=embed_size,activation='linear')(inp)
x=tf.keras.layers.Dense(单位=7958,活化率='softmax')(x)
模型=tf.keras.model(输入=inp,输出=x)
compile(损失='categorical\u crossentropy',优化器='adam')
#优化网络权值
#模型拟合(x=x,y=y,批量大小=256,历代数=100)
model.fit(数据集,epochs=2)
虽然我可以使用()中的py_函数进行管理,但似乎无法从映射函数(,)内部调用.numpy()函数。 在下面的示例中,我已将解析后的数据集映射到一个函数,该函数将图像转换为
np.uint8
,以便使用matplotlib绘制图像

records\u path=data\u目录+'TFRecords'+'/data\u 0.tfrecord'
#创建数据集
dataset=tf.data.TFRecordDataset(文件名=记录\路径)
#将数据集映射到解析函数
parsed_dataset=dataset.map(parsed_fn)
转换的_数据集=解析的_数据集.map(lambda图像,标签:
tf.py_函数(func=转换_函数,
inp=[图像,标签],
Tout=[np.uint8,tf.int64]))
#获取迭代器
迭代器=tf.compat.v1.data.make_one_shot_迭代器(转换的数据集)
对于范围(5)中的i:
image,label=iterator.get_next()
plt.imshow(图片)
plt.show()
打印('标签:',标签)
输出:

解析函数:
def解析(序列化):
#用我们期望的数据名称和类型定义dict
#在TFRecords文件中查找。
特征=\
{
“image”:tf.io.FixedLenFeature([],tf.string),
“标签”:tf.io.FixedLenFeature([],tf.int64)
}
#解析序列化的数据,这样我们就可以用数据得到一个dict。
parsed_example=tf.io.parse_single_example(serialized=serialized,
特征=特征)
#以原始字节的形式获取图像。
image_raw=已解析_示例['image']
#对原始字节进行解码,使其成为类型为的张量。
image=tf.io.decode\u jpeg(图像\u原始)
#获取与图像关联的标签。
label=已解析\u示例['label']
#图像和标签现在是正确的TensorFlow类型。
返回图像、标签

相关问题:

谢谢你的回答,Dourado,实际上我想调用解析函数中的numpy,以便使用该值进行进一步处理。我所说的进一步处理的意思是,创建一个热矩阵,直接发送到张量流模型
batches = [0,250000,500000,750000,1000000,1250000,1500000,1641790]

for i in range(len(batches) - 1 ):

    batches_start = batches[i]
    batches_end = batches[i + 1]
    print( str(batches_start) + " -- " + str(batches_end ))

    toprocess_word_lists = word_lists[batches_start:batches_end]
    save_tfrecords_wordlist( toprocess_word_lists, path +"/TFRecords/data_" + str(i) +".tfrecords")
def _parse_function(example_proto):

  features = {"word_list_X": tf.io.FixedLenFeature((), tf.string),
          "word_list_Y": tf.io.FixedLenFeature((), tf.string)}
  parsed_features = tf.io.parse_single_example(example_proto, features)

  """
  word_list_X  = parsed_features['word_list_X'].numpy()
  word_list_Y  = parsed_features['word_list_Y'].numpy()

  ## need help is getting the numpy values from parsed_features variable so that i can get the one hot encoding matrix     which can be directly sent to tensorflow for training

  sample word_list_X value is <tf.Tensor: shape=(10,), dtype=string,   numpy=array([b'for', b'for', b'for', b'you', b'you', b'you', b'you', b'to',b'to', b'to'], dtype=object)>
  sample word_list_Y value is <tf.Tensor: shape=(10,), dtype=string, numpy=array([b'is', b'to', b'recommend', b'to', b'for', b'contact', b'is',b'contact', b'you', b'the'], dtype=object)>)

  """
  return parsed_features['word_list_X'],parsed_features['word_list_Y']

filenames = [ path + "/JustEat_TFRecords/data.tfrecords" ]
dataset = tf.data.TFRecordDataset(filenames)

dataset = dataset.map(_parse_function)
dataset = dataset.batch(10)

# Defining the size of the embedding
embed_size = 100

# Defining the neural network
inp = tf.keras.Input(shape=(7958,))
x = tf.keras.layers.Dense(units=embed_size, activation='linear')(inp)
x = tf.keras.layers.Dense(units=7958, activation='softmax')(x)

model =  tf.keras.Model(inputs=inp, outputs=x)
model.compile(loss = 'categorical_crossentropy', optimizer = 'adam')

# Optimizing the network weights
#model.fit( x=X, y=Y, batch_size=256,epochs= 100)
model.fit(dataset,epochs= 2)