稀疏的一种热编码功能的内存问题

问题描述

我想为数据帧const mCategories = [ { id: 1,name: 'All',off: 'all_on',on: 'all_on',},{ id: 2,name: 'Whole Cakes',off: 'wc',on: 'wc_on',{ id: 3,name: 'Sliced Cakes',off: 'sc',on: 'sc_on',{ id: 4,name: 'Chilled Items',off: 'chilled',on: 'chilled_on',]; export default class Category extends React.Component { render() { return mCategories.map((mCategory) => ( <TouchableOpacity key={mCategory.id} > <Image source={require(`app/assets/ico/ico_category_${mCategory.on}.png`)} /> <Text>{mCategory.name}</Text> </TouchableOpacity> )); } } 中的一种热编码特征创建稀疏矩阵。但是我在下面给出的代码中遇到了内存问题。 df的形状为(450138,1508)

sparse_onehot

我收到如下所示的内存错误

sp_features = ['id','video_id','genre']
sparse_onehot = pd.get_dummies(df[sp_features],columns = sp_features)
import scipy
X = scipy.sparse.csr_matrix(sparse_onehot.values)

我尝试过MemoryError: Unable to allocate 647. MiB for an array with shape (1508,450138) and data type uint8 并遇到与上述相同的错误

有没有有效的方法来处理此问题? 预先感谢

解决方法

尝试将sparse parameter设置为True

sparsebool,默认为False 是否应使用SparseArray(True)或常规NumPy数组(False)支持虚拟编码列。

sparse_onehot = pd.get_dummies(df[sp_features],columns = sp_features,sparse = True)

与默认的表示方式相比,这将使用更多的内存效率(但速度稍慢)。