【问题标题】:Dataset with jpg import to jupyter notebook将 jpg 导入到 jupyter 笔记本的数据集
【发布时间】:2021-01-09 17:01:21
【问题描述】:

我必须使用 tensorflow 和 keras 通过 jupyter notebook 使用 python 构建机器学习模型。我有一个包含 1000 张图片的数据集。其中 800 个用于训练模型,200 个用于测试和验证。它用于性别和年龄预测模型。现在如何导入我的数据集或如何在 upyter notebook 或 google colab 中写入路径以导入我的数据集。

我所做的是为我的项目导入包。

from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.utils import to_categorical, plot_model
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import BatchNormalization, Conv2D, MaxPooling2D, Activation, Flatten, Dropout, Dense
from tensorflow.keras import backend as K
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import numpy as np
import random
import cv2
import os
import glob
import pandas as pd

亲切的问候。

【问题讨论】:

    标签: python tensorflow keras jupyter-notebook


    【解决方案1】:

    如果数据集在您的本地系统中,您可以通过两种方式在 google colab 中上传数据集。

    1. 您可以将数据集上传到您的 Google 云端硬盘。

    共享文件的最简单方法是将您的 Google 云端硬盘装载到您的 Google Colab 笔记本中。

    为此,请在代码单元格中运行以下命令:

    from google.colab import drive
    drive.mount('/content/drive')
    

    它会要求您访问允许“Google 文件流”的链接以访问您的驱动器。之后,将显示一个长的字母数字身份验证代码,需要将其输入到 Colab 的笔记本中。

    之后,您的云端硬盘文件将被挂载,您可以使用侧面板中的文件浏览器浏览它们。

    1. 您可以通过浏览到本地文件系统手动上传文件

    此方法上传时间较长。

    from google.colab import files
    uploaded = files.upload()
    

    这里有两个例子供你参考:

    【讨论】:

      【解决方案2】:

      这里我在 Tensorflow 中以简单的方式解释如何直接从 TXT 文件加载图像和标签。希望这可以帮到你。以下代码说明了我是如何做到的。但是,这并不意味着它是最好的方法,并且这种方法将有助于执行额外的步骤。

      例如,我在单个整数值 {0,1} 中加载标签,而文档使用单个热向量 [0,1]。

      #Learning how to import images and labels from a TXT file
      #
      #TXT file format
      #
      #path/to/imagefile_1 label_1
      #path/to/imagefile_2 label_2
      #...                 ...
      #where label_X is either {0,1}
      
      #Importing Libraries
      import os
      import tensorflow as tf
      import matplotlib.pyplot as plt
      from tensorflow.python.framework import ops
      from tensorflow.python.framework import dtypes
      #File containing the path to images and the labels [path/to/images label]
      
      filename = '/path/to/List.txt'
      
      #Lists where to store the paths and labels
      
      filenames = []
      labels = []
      
      #Reading file and extracting paths and labels
      with open(filename, 'r') as File:
          infoFile = File.readlines() #Reading all the lines from File
          for line in infoFile: #Reading line-by-line
              words = line.split() #Splitting lines in words using space character as separator
              filenames.append(words[0])
              labels.append(int(words[1]))
      
      NumFiles = len(filenames)
      
      #Converting filenames and labels into tensors
      tfilenames = ops.convert_to_tensor(filenames, dtype=dtypes.string)
      tlabels = ops.convert_to_tensor(labels, dtype=dtypes.int32)
      
      #Creating a queue which contains the list of files to read and the value of the labels
      filename_queue = tf.train.slice_input_producer([tfilenames, tlabels], num_epochs=10, shuffle=True, capacity=NumFiles)
      
      #Reading the image files and decoding them
      rawIm= tf.read_file(filename_queue[0])
      decodedIm = tf.image.decode_png(rawIm) # png or jpg decoder
      
      #Extracting the labels queue
      label_queue = filename_queue[1]
      
      #Initializing Global and Local Variables so we avoid warnings and errors
      init_op = tf.group(tf.local_variables_initializer() ,tf.global_variables_initializer())
      
      #Creating an InteractiveSession so we can run in iPython
      
      sess = tf.InteractiveSession()
      
      with sess.as_default():
          sess.run(init_op)
          
          # Start populating the filename queue.
          coord = tf.train.Coordinator()
          threads = tf.train.start_queue_runners(coord=coord)
      
          for i in range(NumFiles): #length of your filenames list
              nm, image, lb = sess.run([filename_queue[0], decodedIm, label_queue])
              
              print image.shape
              print nm
              print lb
              
              #Showing the current image
              plt.imshow(image)
              plt.show()
      
          coord.request_stop()
          coord.join(threads)
      

      【讨论】:

        【解决方案3】:

        如果您使用 pandas 来定位 CSV 文件,请尝试提供完整路径

        df = pd.read_csv(r"C:\Users\mahe\Desktop\homeprices.csv")
        

        这样使用 或者

        import matplotlib.pyplot as plt
        import os
        import cv2
        from tqdm import tqdm
        
        DATADIR = "X:/Datasets/PetImages" #(give your full path)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-11-20
          • 2017-12-04
          • 2020-11-22
          • 1970-01-01
          • 1970-01-01
          • 2020-09-09
          • 2018-03-13
          • 1970-01-01
          相关资源
          最近更新 更多