【问题标题】:TensorFlow Datasets load images from PathTensorFlow 数据集从路径加载图像
【发布时间】:2022-12-23 22:03:06
【问题描述】:

我有一个这样的数据集,

df = pd.read_csv('train.csv')
df.head()
>>>
   image                 label
0  /path/to/img1.jpg       1
1  /path/to/img2.jpg       0
2  /path/to/img3.jpg       0
3  /path/to/img4.jpg       1
4  /path/to/img5.jpg       1

第一列是要加载的图像的路径,第二列是与该图像关联的标签。我想用 Tensorflow 加载它。我这样做了,

ds = tf.data.Dataset.from_tensor_slices(df.values)
>>> ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type int).

我知道这个错误即将到来,因为第一列是一个字符串,第二列是一个整数,所以加载它的最有效方法是什么。

所以每次我从这个数据集中得到一个新的批次时,它应该给出所有图像和标签的张量。

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    您需要指定目标列。 它与那些问题类似,但想法是识别 6 到 33 张图片。

    [ 样本 ]:

    import tensorflow as tf
    import tensorflow_io as tfio
    
    import pandas as pd
    
    import matplotlib.pyplot as plt
    
    """""""""""""""""""""""""""""""""""""""""""""""""""""""""
    Variables
    """""""""""""""""""""""""""""""""""""""""""""""""""""""""
    # list_label_actual = [ 'Pikaploy', 'Pikaploy', 'Pikaploy', 'Pikaploy', 'Pikaploy', 'Candidt Kibt', 'Candidt Kibt', 'Candidt Kibt', 'Candidt Kibt', 'Candidt Kibt' ]
    list_label_actual = [ 'Candidt Kibt', 'Pikaploy' ]
    
    """""""""""""""""""""""""""""""""""""""""""""""""""""""""
    : Dataset
    """""""""""""""""""""""""""""""""""""""""""""""""""""""""
    variables = pd.read_excel('F:\temp\Python\excel\Book 7.xlsx', index_col=None, header=[0])
    
    list_label = [ ]
    list_Image = [ ]
    list_file_actual = [ ]
    
    for Index, Image, Label in variables.values:
        print( Label )
        list_label.append( Label )
        
        image = tf.io.read_file( Image )
        image = tfio.experimental.image.decode_tiff(image, index=0)
        list_file_actual.append(image)
        image = tf.image.resize(image, [32,32], method='nearest')
        list_Image.append(image)
    
    
    list_label = tf.cast( list_label, dtype=tf.int32 )
    list_label = tf.constant( list_label, shape=( 33, 1, 1 ) )
    list_Image = tf.cast( list_Image, dtype=tf.int32 )
    list_Image = tf.constant( list_Image, shape=( 33, 1, 32, 32, 4 ) )
    
    dataset = tf.data.Dataset.from_tensor_slices(( list_Image, list_label ))
    list_Image = tf.constant( list_Image, shape=( 33, 32, 32, 4) ).numpy()
    
    """""""""""""""""""""""""""""""""""""""""""""""""""""""""
    : Model Initialize
    """""""""""""""""""""""""""""""""""""""""""""""""""""""""
    model = tf.keras.models.Sequential([
        tf.keras.layers.InputLayer(input_shape=( 32, 32, 4 )),
        tf.keras.layers.Normalization(mean=3., variance=2.),
        tf.keras.layers.Normalization(mean=4., variance=6.),
        tf.keras.layers.Dense(256, activation='relu'),
        tf.keras.layers.Reshape((256, 32 * 32)),
        tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(196, return_sequences=True, return_state=False)),
        tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(196)),
        tf.keras.layers.Flatten(),
        tf.keras.layers.Dense(192, activation='relu'),
        tf.keras.layers.Dense(2),
    ])
    
    """""""""""""""""""""""""""""""""""""""""""""""""""""""""
    : Callback
    """""""""""""""""""""""""""""""""""""""""""""""""""""""""
    class custom_callback(tf.keras.callbacks.Callback):
        def on_epoch_end(self, epoch, logs={}):
            if( logs['accuracy'] >= 0.97 ):
                self.model.stop_training = True
        
    custom_callback = custom_callback()
    
    """""""""""""""""""""""""""""""""""""""""""""""""""""""""
    : Optimizer
    """""""""""""""""""""""""""""""""""""""""""""""""""""""""
    optimizer = tf.keras.optimizers.Nadam(
        learning_rate=0.000001, beta_1=0.9, beta_2=0.999, epsilon=1e-07,
        name='Nadam'
    )
    
    """""""""""""""""""""""""""""""""""""""""""""""""""""""""
    : Loss Fn
    """""""""""""""""""""""""""""""""""""""""""""""""""""""""                               
    lossfn = tf.keras.losses.SparseCategoricalCrossentropy(
        from_logits=False,
        reduction=tf.keras.losses.Reduction.AUTO,
        name='sparse_categorical_crossentropy'
    )
    
    """""""""""""""""""""""""""""""""""""""""""""""""""""""""
    : Model Summary
    """""""""""""""""""""""""""""""""""""""""""""""""""""""""
    model.compile(optimizer=optimizer, loss=lossfn, metrics=['accuracy'] )
    
    """""""""""""""""""""""""""""""""""""""""""""""""""""""""
    : Training
    """""""""""""""""""""""""""""""""""""""""""""""""""""""""
    history = model.fit( dataset, batch_size=100, epochs=50, callbacks=[custom_callback] )
    
    plt.figure(figsize=(6,6))
    plt.title("Actors recognitions")
    for i in range(len(list_Image)):
        img = tf.keras.preprocessing.image.array_to_img(
            list_Image[i],
            data_format=None,
            scale=True
        )
        img_array = tf.keras.preprocessing.image.img_to_array(img)
        img_array = tf.expand_dims(img_array, 0)
        predictions = model.predict(img_array)
        score = tf.nn.softmax(predictions[0])
        plt.subplot(6, 6, i + 1)
        plt.xticks([])
        plt.yticks([])
        plt.grid(False)
        plt.imshow(list_file_actual[i])
        plt.xlabel(str(round(score[tf.math.argmax(score).numpy()].numpy(), 2)) + ":" +  str(list_label_actual[tf.math.argmax(score)]))
        
    plt.show()
    
    input('...')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-15
      • 2016-08-12
      • 2020-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-01
      • 1970-01-01
      相关资源
      最近更新 更多