吴裕雄 python 神经网络——TensorFlow 数据集基本使用方法

import tempfile
import tensorflow as tf

input_data = [1, 2, 3, 5, 8]
dataset = tf.data.Dataset.from_tensor_slices(input_data)

# 定义迭代器。
iterator = dataset.make_one_shot_iterator()

# get_next() 返回代表一个输入数据的张量。
x = iterator.get_next()
y = x * x

with tf.Session() as sess:
    for i in range(len(input_data)):
        print(sess.run(y))

# 创建文本文件作为本例的输入。
with open("E:\\temp\\test1.txt", "w") as file:
    file.write("File1, line1.\n")
    file.write("File1, line2.\n")
with open("E:\\temp\\test2.txt", "w") as file:
    file.write("File2, line1.\n")
    file.write("File2, line2.\n")

# 从文本文件创建数据集。这里可以提供多个文件。
input_files = ["E:\\temp\\test1.txt", "E:\\temp\\test2.txt"]
dataset = tf.data.TextLineDataset(input_files)

# 定义迭代器。
iterator = dataset.make_one_shot_iterator()

# 这里get_next()返回一个字符串类型的张量,代表文件中的一行。
x = iterator.get_next()
with tf.Session() as sess:
    for i in range(4):
        print(sess.run(x))

# 解析一个TFRecord的方法。
def parser(record):
    features = tf.parse_single_example(
        record,
        features={
            ‘image_raw‘:tf.FixedLenFeature([],tf.string),
            ‘pixels‘:tf.FixedLenFeature([],tf.int64),
            ‘label‘:tf.FixedLenFeature([],tf.int64)
        })
    decoded_images = tf.decode_raw(features[‘image_raw‘],tf.uint8)
    retyped_images = tf.cast(decoded_images, tf.float32)
    images = tf.reshape(retyped_images, [784])
    labels = tf.cast(features[‘label‘],tf.int32)
    #pixels = tf.cast(features[‘pixels‘],tf.int32)
    return images, labels

# 从TFRecord文件创建数据集。这里可以提供多个文件。
input_files = ["E:\\MNIST_data\\output.tfrecords"]
dataset = tf.data.TFRecordDataset(input_files)

# map()函数表示对数据集中的每一条数据进行调用解析方法。
dataset = dataset.map(parser)

# 定义遍历数据集的迭代器。
iterator = dataset.make_one_shot_iterator()

# 读取数据,可用于进一步计算
image, label = iterator.get_next()

with tf.Session() as sess:
    for i in range(10):
        x, y = sess.run([image, label])
        print(y)

# 从TFRecord文件创建数据集,具体文件路径是一个placeholder,稍后再提供具体路径。
input_files = tf.placeholder(tf.string)
dataset = tf.data.TFRecordDataset(input_files)
dataset = dataset.map(parser)

# 定义遍历dataset的initializable_iterator。
iterator = dataset.make_initializable_iterator()
image, label = iterator.get_next()

with tf.Session() as sess:
    # 首先初始化iterator,并给出input_files的值。
    sess.run(iterator.initializer,feed_dict={input_files: ["E:\\MNIST_data\\output.tfrecords"]})
    # 遍历所有数据一个epoch。当遍历结束时,程序会抛出OutOfRangeError。
    while True:
        try:
            x, y = sess.run([image, label])
        except tf.errors.OutOfRangeError:
            break 

原文地址:https://www.cnblogs.com/tszr/p/10885418.html

时间: 2024-07-31 17:55:43

吴裕雄 python 神经网络——TensorFlow 数据集基本使用方法的相关文章

吴裕雄 python 神经网络——TensorFlow 数据集高层操作

import tempfile import tensorflow as tf train_files = tf.train.match_filenames_once("E:\\output.tfrecords") test_files = tf.train.match_filenames_once("E:\\output_test.tfrecords") # 解析一个TFRecord的方法. def parser(record): features = tf.pa

吴裕雄 python 神经网络——TensorFlow pb文件保存方法

import tensorflow as tf from tensorflow.python.framework import graph_util v1 = tf.Variable(tf.constant(1.0, shape=[1]), name = "v1") v2 = tf.Variable(tf.constant(2.0, shape=[1]), name = "v2") result = v1 + v2 init_op = tf.global_varia

吴裕雄 python 神经网络——TensorFlow 使用卷积神经网络训练和预测MNIST手写数据集

import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_data #设置输入参数 batch_size = 128 test_size = 256 # 初始化权值与定义网络结构,建构一个3个卷积层和3个池化层,一个全连接层和一个输出层的卷积神经网络 # 首先定义初始化权重函数 def init_weights(shape): return tf.Variabl

吴裕雄 python 神经网络——TensorFlow实现回归模型训练预测MNIST手写数据集

import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("E:\\MNIST_data\\", one_hot=True) #构建回归模型,输入原始真实值(group truth),采用sotfmax函数拟合,并定义损失函数和优化器 #定义回归模型 x = tf.placeholder(tf.float32,

吴裕雄 python 神经网络——TensorFlow训练神经网络:不使用激活函数

import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data INPUT_NODE = 784 # 输入节点 OUTPUT_NODE = 10 # 输出节点 LAYER1_NODE = 500 # 隐藏层数 BATCH_SIZE = 100 # 每次batch打包的样本个数 # 模型相关的参数 LEARNING_RATE_BASE = 0.01 LEARNING_RATE_DECAY = 0.

吴裕雄 python 神经网络——TensorFlow 输入数据处理框架

import tensorflow as tf files = tf.train.match_filenames_once("E:\\MNIST_data\\output.tfrecords") filename_queue = tf.train.string_input_producer(files, shuffle=False) # 读取文件. reader = tf.TFRecordReader() _,serialized_example = reader.read(filen

吴裕雄 python 神经网络——TensorFlow 图像预处理完整样例

import numpy as np import tensorflow as tf import matplotlib.pyplot as plt def distort_color(image, color_ordering=0): if color_ordering == 0: image = tf.image.random_brightness(image, max_delta=32./255.) image = tf.image.random_saturation(image, low

吴裕雄 python 神经网络——TensorFlow训练神经网络:MNIST最佳实践

import os import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data INPUT_NODE = 784 OUTPUT_NODE = 10 LAYER1_NODE = 500 def get_weight_variable(shape, regularizer): weights = tf.get_variable("weights", shape, initializer

吴裕雄 python 神经网络——TensorFlow TFRecord样例程序

import numpy as np import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # 定义函数转化变量类型. def _int64_feature(value): return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) def _bytes_feature(value): return tf.