自定义格式的酸洗数据

Pickling Data of Custom Format

我需要腌制以下形式的数据:table 多行

一个元组列表,一个列表

例如[(1,2),(2,3),(3,4)] 与 [1,2,3]

关联

我找不到一种方法来 pickle 数据并加载它,以便我得到:

import cPickle
f = open("data.pkl", 'rb')
X,Y = cPickle.load(f)

这样X只有第一列数据,Y有第二列数据。

我想分别存储第一列和第二列,但是我怎么能在一个语句中加载这样的数据呢?

a = []
a.append( [(1,2),(2,3)] )

第二列也是如此。

b = []
b.append([1,2])

那怎么腌制和去腌呢?

非常感谢。

class Bunch(dict):
    """Container object for datasets
    Dictionary-like object that exposes its keys as attributes.
    >>> b = Bunch(a=1, b=2)
    >>> b['b']
    2
    >>> b.b
    2
    >>> b.a = 3
    >>> b['a']
    3
    >>> b.c = 6
    >>> b['c']
    6
    """

    def __init__(self, **kwargs):
        super(Bunch, self).__init__(kwargs)

    def __setattr__(self, key, value):
        self[key] = value

    def __dir__(self):
        return self.keys()

    def __getattr__(self, key):
        try:
            return self[key]
        except KeyError:
            raise AttributeError(key)

import cPickle as pickle

dataset = Bunch.Bunch(data=X, target=Y,
                         target_names=target_names_input,
                        DESCR=fdescr,feature_names=labels_names)

def save_object(obj, filename):
with open(filename, 'wb') as output:
    pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)

save_object(dataset,'data.pkl')

with open('data.pkl', "rb") as f:
data = pickle.load(f)
X = data.data
Y = data.target

我假设您在 table X 的行中有某种形式的特征数据,并且您的列 Y 是目标向量。

尝试

import cPickle

FILENAME = 'foo.pkl'

X = [(1,2),(2,3),(3,4)]
Y = [1,2,3]

with open(FILENAME, 'wb') as f:
    cPickle.dump((X, Y), f)

with open(FILENAME, 'rb') as f:
    x, y = cPickle.load(f)

print(x)
print(y)