Skip to main content
 首页 » 编程设计

python之为什么 numpy 形状是空的

2025年05月04日15zhoujg

我有以下内容

(Pdb) training 
array(<418326x223957 sparse matrix of type '<type 'numpy.float64'>' 
    with 165657096 stored elements in Compressed Sparse Row format>, dtype=object) 
(Pdb) training.shape 
() 

为什么没有形状信息?

编辑:这就是我所做的:

training, target, test, projectids = generate_features(outcomes, projects, resources) 
target = np.array([1. if i == 't' else 0. for i in target]) 
projectids = np.array([i for i in projectids]) 
 
print 'vectorizing training features' 
d = DictVectorizer(sparse=True) 
training = d.fit_transform(training[:10].T.to_dict().values()) 
#test_data = d.fit_transform(training.T.to_dict().values()) 
test_data = d.transform(test[:10].T.to_dict().values()) 
 
print 'training shape: %s, %s' %(training.shape[0], training[1]) 
print 'test shape: %s, %s' %(test_data.shape[0], test_data[1]) 
 
print 'saving vectorized instances' 
with open(filename, "wb") as f: 
    np.save(f, training) 
    np.save(f, test_data) 
    np.save(f, target) 
    np.save(f, projectids) 

此时,我训练的形状仍然是(10, 121)。

稍后,我只是通过

重新初始化 4 个变量
with open("../data/f1/training.dat", "rb") as f: 
    training = np.load(f) 
    test_data = np.load(f) 
    target = np.load(f) 
    projectids = np.load(f) 

但是形状不见了。

请您参考如下方法:

里面有形状信息

array(<418326x223957 sparse matrix of type '<type 'numpy.float64'>' 
    with 165657096 stored elements in Compressed Sparse Row format>, dtype=object) 

这是一个包含一项的数组,维度为 0,因此形状为 () .那一项是dtype=object .具体来说,它是一个稀疏数组 - 尺寸显示在显示屏上 <418...x22... .

我正要询问 DictVectorizer和 fit_transform ,但这没关系。更改值的是保存和加载操作。

我的猜测是您没有加载刚刚编写的文件。


你的 np.save(f,training)将稀疏矩阵包装在 np.array 中使用 dtype object .这就是您在加载时看到的。

training = training.item() 

从数组包装器中取出稀疏矩阵。

是418326x223957 training 的形状完整的数据集,(10, 121)减少调试集的形状?