【问题标题】:Accessing data from python dictionary从 python 字典中访问数据
【发布时间】:2018-09-21 12:04:18
【问题描述】:
import numpy as np

def unpickle(file):
   import pickle
   with open(file, 'rb') as fo:
   dict = pickle.load(fo, encoding='bytes')
   return dict

 train = []
for j in range (1,6):
train.append(unpickle('/Users/sachalabdullah/Desktop/cifar-10-batches-py/data_batch_'+str(j)))

test = unpickle ("/Users/sachalabdullah/Desktop/cifar-10-batches-py/test_batch”)

我已经加载了 CIFAR_10,因为我是 python 新手,我不知道如何从字典中访问数据。

还有一件事让我感到困惑,我在train 中附加了所有五批训练数据,假设我只能访问数据集中的标签和图像,所以如果我正在访问它,我将从全部五个批次,或者我需要为每个批次分别访问图像和标签?

是否有任何与此等效的 Matlab,如果我想从矩阵中获取第 1 列和第 2 列,我会做 A(:, [1,2]) ,或者没有?

【问题讨论】:

    标签: python python-3.x machine-learning computer-vision classification


    【解决方案1】:

    要访问字典中的键:

    mydict={'mykey':['value1','value2']}
    
    #access mykey from mydict:
    mydict['mykey']
    

    要将数据正确加载到字典中,我会这样做:

    def unpickle(file):
       import pickle
       dict={}
       with open(file, 'rb') as fo:
       dict[fo] = pickle.load(fo, encoding='bytes')
       return dict
    
    #how to access the data in your train[j] dict:
    [v for v in train[j].values()]
    

    获取矩阵前两行的python等价物:

    A=np.matrix([[1, 2, 3], [3, 4, 5], [5, 6, 7]])
    A[:,[0,1]]
    

    请记住,python 的索引从 0 开始。 matlab 索引从 1 开始。

    【讨论】:

      【解决方案2】:

      首先创建您的转储文件。

      file = open('filename', 'r')
      obj = file.read()
      pickle.dump(obj, open('file.pickle', 'wb'))
      

      然后

      with open(file.pickle, 'rb') as fo:
         dict = pickle.load(fo, encoding='bytes')
      

      【讨论】:

        猜你喜欢
        • 2021-12-22
        • 2016-06-26
        • 2021-12-31
        • 1970-01-01
        • 1970-01-01
        • 2020-10-03
        • 1970-01-01
        • 1970-01-01
        • 2011-07-21
        相关资源
        最近更新 更多