чтение набора данных TFRecords ProteinNet - PullRequest
0 голосов
/ 13 февраля 2019

Я пытался читать и использовать набор данных ProteinNet с небольшим успехом, статья об этом здесь , репозиторий github здесь .

данные огромны (9 ГБ несжатые в TFRecords версии 11), поэтому сейчас я просто хочу использовать инструменты визуализации, чтобы лучше понять их, но читатель github (parser.py) использует устаревшие функции тензорного потока.вот оно:

__author__ = "Mohammed AlQuraishi"
__copyright__ = "Copyright 2018, Harvard Medical School"
__license__ = "MIT"

import tensorflow as tf
NUM_AAS = 20
NUM_DIMENSIONS = 3

def masking_matrix(mask, name=None):

    with tf.name_scope(name, 'masking_matrix', [mask]) as scope:
        mask = tf.convert_to_tensor(mask, name='mask')

        mask = tf.expand_dims(mask, 0)
        base = tf.ones([tf.size(mask), tf.size(mask)])
        matrix_mask = base * mask * tf.transpose(mask)

        return matrix_mask


def read_protein(filename_queue, max_length, num_evo_entries=21, name=None):
    """ Reads and parses a ProteinNet TF Record. 

        Primary sequences are mapped onto 20-dimensional one-hot vectors.
        Evolutionary sequences are mapped onto num_evo_entries-dimensional real-valued vectors.
        Secondary structures are mapped onto ints indicating one of 8 class labels.
        Tertiary coordinates are flattened so that there are 3 times as many coordinates as 
        residues.

        Evolutionary, secondary, and tertiary entries are optional.

    Args:
        filename_queue: TF queue for reading files
        max_length:     Maximum length of sequence (number of residues) [MAX_LENGTH]. Not a 
                        TF tensor and is thus a fixed value.

    Returns:
        id: string identifier of record
        one_hot_primary: AA sequence as one-hot vectors
        evolutionary: PSSM sequence as vectors
        secondary: DSSP sequence as int class labels
        tertiary: 3D coordinates of structure
        matrix_mask: Masking matrix to zero out pairwise distances in the masked regions
        pri_length: Length of amino acid sequence
        keep: True if primary length is less than or equal to max_length
    """

    with tf.name_scope(name, 'read_protein', []) as scope:
        reader = tf.TFRecordReader()
        _, serialized_example = reader.read(filename_queue)

        context, features = tf.parse_single_sequence_example(serialized_example,
                                context_features={'id': tf.FixedLenFeature((1,), tf.string)},
                                sequence_features={
                                    'primary':      tf.FixedLenSequenceFeature((1,),               tf.int64),
                                    'evolutionary': tf.FixedLenSequenceFeature((num_evo_entries,), tf.float32, allow_missing=True),
                                    'secondary':    tf.FixedLenSequenceFeature((1,),               tf.int64,   allow_missing=True),
                                    'tertiary':     tf.FixedLenSequenceFeature((NUM_DIMENSIONS,),  tf.float32, allow_missing=True),
                                    'mask':         tf.FixedLenSequenceFeature((1,),               tf.float32, allow_missing=True)})
        id_ = context['id'][0]
        primary =   tf.to_int32(features['primary'][:, 0])
        evolutionary =          features['evolutionary']
        secondary = tf.to_int32(features['secondary'][:, 0])
        tertiary =              features['tertiary']
        mask =                  features['mask'][:, 0]

        pri_length = tf.size(primary)
        keep = pri_length <= max_length

        one_hot_primary = tf.one_hot(primary, NUM_AAS)

        # Generate tertiary masking matrix--if mask is missing then assume all residues are present
        mask = tf.cond(tf.not_equal(tf.size(mask), 0), lambda: mask, lambda: tf.ones([pri_length]))
        ter_mask = masking_matrix(mask, name='ter_mask')

        return id_, one_hot_primary, evolutionary, secondary, tertiary, ter_mask, pri_length, keep

Используется устаревшая функция:

tf.TFRecordReader ()

, которая, очевидно, должна быть заменена на

tf.data.TFRecordDataset (имя файла)

, хотя мое отсутствие знаний о TFRecords и отсутствие документации по манекенам на нем сделали так, что я ничего не мог прочитать онабор данных.

Как я могу обновить функцию read_protein (), чтобы она работала, и как мне перейти от TFRecords к простым тензорам?Я совершенно новичок в этом типе файлов.

Я могу предоставить образец набора данных, если это необходимо, так как я понимаю, что 9 ГБ нелегко загрузить.

1 Ответ

0 голосов
/ 13 февраля 2019

Вы можете получить доступ к индивидуальному сериализованному примеру с помощью

for str_rec in tf.python_io.tf_record_iterator('filename.tfrecords'):
    example = tf.train.Example()
    example.ParseFromString(str_rec)

Затем внутри цикла вы можете получить доступ к «основной» функции следующим образом

primary = int(example.features.feature['primary'].int64_list.value[0])

Как правило, вам нужно знать, какданные были закодированы в tfrecords.Подробнее об этом здесь https://www.tensorflow.org/tutorials/load_data/tf_records

...