标签: tensorflow-datasets

tf.decode_raw 和 tf.reshape 使用不同的图像大小

我正在使用以下代码生成 tfrecords 文件。

  def generate_tfrecords(data_path, labels, name):
      """Converts a dataset to tfrecords."""
      filename = os.path.join(args.tfrecords_path, name + '.tfrecords')
      writer = tf.python_io.TFRecordWriter(filename)
for index, data in enumerate(data_path):
      with tf.gfile.GFile(data, 'rb') as fid:
        encoded_jpg = fid.read()
        print(len(encoded_jpg))   # 17904
      encoded_jpg_io = io.BytesIO(encoded_jpg)
      image = pil.open(encoded_jpg_io)
      image = np.asarray(image)
      print(image.shape)    # 112*112*3
      example = tf.train.Example(features=tf.train.Features(feature={
        'height': _int64_feature(int(image.shape[0])),
        'width': _int64_feature(int(image.shape[1])),
        'depth': _int64_feature(int(3)),
        'label': _int64_feature(int(labels[index])),
        'image_raw': _bytes_feature(encoded_jpg)}))
      writer.write(example.SerializeToString())
    writer.close()
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,encoded_jpg有长度17904,图像有112*112*3不一致的形状。

当我使用以下代码解析 tfrecords 时:

def _parse_function(example_proto):
     features = {'height':  tf.FixedLenFeature((), …
Run Code Online (Sandbox Code Playgroud)

tensorflow tensorflow-datasets

3
推荐指数
1
解决办法
1228
查看次数

TensorFlow:使用自己的数据集实现单层感知器/多层感知器

我是TensorFlow 的新手我寻找了使用 tensorflow 实现多层感知器的示例,但我 得到了关于 MNIST 图像数据集的示例,除了 MNIST 之外,我能否使用相同的优化和成本函数构建神经网络模型并训练数据数字格式,意思是,我可以使用 tensorflow 训练我自己的数字数据集吗?

有没有训练新数据集的例子?.

python perceptron neural-network tensorflow tensorflow-datasets

3
推荐指数
1
解决办法
3006
查看次数

如何在 Tensorflow String Tensor 上执行字符串查找和替换?

我目前正在使用 Tensorflow 数据集 api 对指定路径上的图像执行一些增强。文件名本身包含说明是否扩充文件的信息。所以我想要做的是从数据集中读取文件,对于每个文件,在文件名中执行查找,如果找到特定的子字符串,则设置一个 bool 标志并将子字符串替换为“”。

我得到的错误是:

AttributeError: 'Tensor' 对象没有属性 'find'

我无法使用 dtype 字符串条目对张量执行“查找”,因为 find 不是张量的一部分,所以我试图弄清楚如何执行上述操作。我在下面分享了一些代码,我认为这些代码展示了我正在尝试做的事情。性能很重要,因此如果有人发现我将通过 Dataset API 错误地执行此操作,我更愿意以正确的方式执行此操作。

def preproc_img(filenames):
  def parse_fn(filename):
    augment_inst = False
    if cfg.SPLIT_INTO_INST:
      #*****************************************************
      #*** THIS IS WHERE THE LOGIC IS CURRENTLY BREAKING ***
      #*****************************************************
      if filename.find('_data_augmentation') != -1:
        augment_inst = True
        filename = filename.replace('_data_augmentation', '')

    image_string = tf.read_file(filename)
    img = tf.image.decode_image(image_string, channels=3)
    return dict(zip([filename], [img]))   

  dataset = tf.data.Dataset.from_tensor_slices(filenames)
  dataset = dataset.map(parse_fn)
  iterator = dataset.make_one_shot_iterator()
  return iterator.get_next()


def perform_train():
  if __name__ == '__main__':
    filenames …
Run Code Online (Sandbox Code Playgroud)

tensorflow tensorflow-datasets

3
推荐指数
1
解决办法
4253
查看次数

如何在第一个时期正确地缓存数据(Tensorflow,数据集)?

我正在尝试将cache转换用于dataset。这是我当前的代码(简体):

dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=1)
dataset = dataset.apply(tf.contrib.data.shuffle_and_repeat(buffer_size=5000, count=1))
dataset = dataset.map(_parser_a, num_parallel_calls=12)
dataset = dataset.padded_batch(
    20, 
    padded_shapes=padded_shapes,
    padding_values=padding_values
)
dataset = dataset.prefetch(buffer_size=1)
dataset = dataset.cache()
Run Code Online (Sandbox Code Playgroud)

在第一个时期之后,我收到以下错误消息:

调用迭代器没有完全读取我们尝试缓存的数据集。为了避免序列的意外截断,将丢弃当前的[部分缓存]序列。如果您的序列与相似,则会发生这种情况dataset.cache().take(k).repeat()。相反,请交换订单(即dataset.take(k).cache().repeat()

然后,代码继续进行,仍然从硬盘驱动器而不是从缓存读取数据。那么,应该在哪里放置dataset.cache()以避免该错误?谢谢。

tensorflow tensorflow-datasets

3
推荐指数
1
解决办法
2452
查看次数

限制 tf.data.Dataset 中的项目数

tl;博士; 我可以限制 a 中的元素数量tf.data.Dataset吗?

A 有一个训练和评估循环来处理整个给定的dataset. 这对于测试来说并不理想,因为遍历整个数据集需要很长时间。我可以通过创建 Mock 数据集或限制元素的数量来测试此代码,dataset因此代码仅通过前 10 个数据点。我该如何做第二个?

谢谢

testing tensorflow tensorflow-datasets

3
推荐指数
1
解决办法
437
查看次数

Tensorflow:张量上的矩阵大小不兼容错误

我正在尝试使用 Tensorflow 对单变量数值数据集进行二元分类。我的数据集包含 6 个特征/变量,包括大约 90 个实例的标签。这是我的数据的预览:

sex,age,Time,Number_of_Warts,Type,Area,Result_of_Treatment
1,35,12,5,1,100,0
1,29,7,5,1,96,1
1,50,8,1,3,132,0
1,32,11.75,7,3,750,0
1,67,9.25,1,1,42,0
Run Code Online (Sandbox Code Playgroud)

我正在使用 sklearn 的 train_test_split 函数拆分我的数据,如下所示:

X_train, X_test, y_train, y_test = train_test_split(data, y, test_size=0.33, random_state=42)
Run Code Online (Sandbox Code Playgroud)

然后我使用以下代码将我的数据转换为张量:

X_train=tf.convert_to_tensor(X_train)
X_test = tf.convert_to_tensor(X_test)

y_train=tf.convert_to_tensor(y_train)
y_test = tf.convert_to_tensor(y_test)
Run Code Online (Sandbox Code Playgroud)

在此之后,我开始构建一个简单的顺序模型。

from keras import models
from keras import layers

from keras import models
from keras import layers

model = models.Sequential()
model.add(layers.Dense(16, activation='relu', input_shape=(60,)))
model.add(layers.Dense(16, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))

model.compile(optimizer=optimizers.RMSprop(lr=0.001),
          loss='binary_crossentropy',
          metrics=['accuracy'])
Run Code Online (Sandbox Code Playgroud)

当我调用 fit 函数时发生错误

 history = model.fit(X_train,y_train,epochs=10,steps_per_epoch=200)

 InvalidArgumentError: Matrix size-incompatible: In[0]: [60,6], In[1]: [60,16]
 [[{{node …
Run Code Online (Sandbox Code Playgroud)

python machine-learning supervised-learning tensorflow tensorflow-datasets

3
推荐指数
1
解决办法
6006
查看次数

为 TensorFlow 预制估计器定义输入函数

我正在尝试使用预制的估计器tf.estimator.DNNClassifier在 MNIST 数据集上使用。我从tensorflow_dataset.

我遵循以下四个步骤:首先构建数据集管道并定义输入函数:

## Step 1
mnist, info = tfds.load('mnist', with_info=True)

ds_train_orig, ds_test = mnist['train'], mnist['test']

def train_input_fn(dataset, batch_size):
    dataset = dataset.map(lambda x:({'image-pixels':tf.reshape(x['image'], (-1,))}, 
                                    x['label']))
    return dataset.shuffle(1000).repeat().batch(batch_size)
Run Code Online (Sandbox Code Playgroud)

然后,在步骤 2 中,我使用单个键和形状 784 定义特征列:

## Step 2:
image_feature_column = tf.feature_column.numeric_column(key='image-pixels',
                                                        shape=(28*28))

image_feature_column
NumericColumn(key='image-pixels', shape=(784,), default_value=None, dtype=tf.float32, normalizer_fn=None)
Run Code Online (Sandbox Code Playgroud)

第 3 步,我将估算器实例化如下:

## Step 3:
dnn_classifier = tf.estimator.DNNClassifier(
    feature_columns=image_feature_column,
    hidden_units=[16, 16],
    n_classes=10)
Run Code Online (Sandbox Code Playgroud)

最后,通过调用.train()方法使用估计器的步骤 4 :

## Step 4:
dnn_classifier.train(
    input_fn=lambda:train_input_fn(ds_train_orig, batch_size=32),
    #lambda:iris_data.train_input_fn(train_x, train_y, args.batch_size),
    steps=20)
Run Code Online (Sandbox Code Playgroud)

但这会导致以下错误。看起来问题出在数据集上。

--------------------------------------------------------------------------- …
Run Code Online (Sandbox Code Playgroud)

python tensorflow tensorflow-datasets tensorflow-estimator

3
推荐指数
1
解决办法
2997
查看次数

为什么使用 tensorflow2.0 的同一数据集的训练准确度和验证准确度不同?

我正在使用 tensorflow2.0 和 tensorflow_datasets 进行训练。但我不明白:为什么训练准确度和损失与验证准确度和损失不同?

这是我的代码:

import tensorflow as tf
import tensorflow_datasets as tfds

data_name = 'uc_merced'
dataset = tfds.load(data_name)
# the train_data and the test_data are same dataset
train_data, test_data = dataset['train'], dataset['train'] 

def parse(img_dict):
    img = tf.image.resize_with_pad(img_dict['image'], 256, 256)
    #img = img / 255.
    label = img_dict['label']
    return img, label

train_data = train_data.map(parse)
train_data = train_data.batch(96)

test_data = test_data.map(parse)
test_data = test_data.batch(96)

strategy = tf.distribute.MirroredStrategy()
with strategy.scope():
    model = tf.keras.applications.ResNet50(weights=None, classes=21, 
            input_shape=(256, 256, 3))
    model.compile(optimizer='adam',
            loss='sparse_categorical_crossentropy',
            metrics=['accuracy'])

model.fit(train_data, …
Run Code Online (Sandbox Code Playgroud)

keras tensorflow tensorflow-datasets tf.keras tensorflow2.0

3
推荐指数
1
解决办法
1827
查看次数

RuntimeError: __iter__() 仅在 tf.function 内部或在启用急切执行时受支持

我是 tensorflow 的新手并试图学习它。尝试在 Tensorflow 2.2.0 中运行估算器 LinearClassifier。

  1. 导入所有模块并读入 tfRecords
import tensorflow as tf
print(tf.version.VERSION)
import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
print (tf.executing_eagerly())
tf.executing_eagerly()
tf.compat.v1.enable_eager_execution()

path = 'train.tfrecord'
filenames = [(path + "/" + name) for name in os.listdir(path) if name.startswith("part")]
print (filenames)
Run Code Online (Sandbox Code Playgroud)
  1. 定义解析函数
def _parse_function(example_proto):
    features = {
        'Age': tf.io.FixedLenFeature([], tf.string),
        'EstimatedSalary': tf.io.FixedLenFeature([], tf.string),
        'Purchased': tf.io.FixedLenFeature([], tf.string)
    }
    tf_records = tf.io.parse_single_example(example_proto, features)
    features_dict = {
        'Age': tf_records['Age'],
        'EstimatedSalary': tf_records['EstimatedSalary']
    }
    return features_dict, tf_records['Purchased']
Run Code Online (Sandbox Code Playgroud)
  1. 定义传入估计器的输入函数
def input_fn():
    dataset = tf.data.TFRecordDataset(filenames = filenames) …
Run Code Online (Sandbox Code Playgroud)

tensorflow tensorflow-datasets tensorflow2.0

3
推荐指数
1
解决办法
5323
查看次数

如何加载 Tensorflow 数据集“Iris”并将标签更改为单热编码

我正在尝试直接从 tensorflow 数据集加载“iris”数据集,但我被卡住了。我习惯于使用 CSV。

import tensorflow as tf
import tensorflow_datasets as tfds

data = tfds.load("iris",split='train[:80%]', as_supervised=True)
data = data.batch(10)
features, labels = data
Run Code Online (Sandbox Code Playgroud)

我不知道我应该如何分离特征 X,y。标签与特征的张量不同,但我不知道如何访问它们以使用它们。我想对标签进行热编码并将它们输入模型,但我被困在这里。

tensorflow 文档很少提供有关如何执行此操作的信息。任何帮助深表感谢

python tensorflow tensorflow-datasets iris-dataset tensorflow2.0

3
推荐指数
1
解决办法
1235
查看次数