python - 如何对大文件应用单热编码?

标签 python python-2.7 csv pandas machine-learning

我有 3 Gb 训练文件和 350 Mb 测试文件,6 Gb RAM。这些文件似乎不太大,无法将它们保存在内存中,但我什至无法附加它们(发生内存错误)。

我目前的做法是这样的:

# reading files
      dtypes = {'Semana' : 'int32',
                          'Agencia_ID' :'int32',
                          'Canal_ID' : 'int32',
                          'Ruta_SAK' : 'int32',
                          'Cliente-ID' : 'int32',
                          'Producto_ID':'int32',
                          'Venta_hoy':'float32',
                          'Venta_uni_hoy': 'int32',
                          'Dev_uni_proxima':'int32',
                          'Dev_proxima':'float32',
                          'Demanda_uni_equil':'int32'}

train = pd.read_csv('train.csv', dtype  = dtypes, usecols=["Semana", "Agencia_ID", "Canal_ID", 'Ruta_SAK',  'Cliente_ID', 'Producto_ID','Demanda_uni_equil'])
test = pd.read_csv('test.csv',dtype  = dtypes)
ids = test['id']
test.drop(['id'], axis =1, inplace = True)

shapeTrain = train.shape[0]
shapeTest = test.shape[0]

train = train.append(test) # raises memory error

#applying one-hot encoding
train = pd.concat([train, pd.get_dummies(train['Semana'],sparse=True)], axis=1, join_axes=[train.index])
train.drop([11,'Semana'],axis=1, inplace = True)

train = pd.concat([train, pd.get_dummies(train['Producto_ID'],sparse=True)], axis=1, join_axes=[train.index])
train.drop([123,'Producto_ID'],axis=1, inplace = True)


train = pd.concat([train, pd.get_dummies(train['Canal_ID'],sparse=True)], axis=1, join_axes=[train.index])
train.drop([11,'Canal_ID'],axis=1, inplace = True)

# separating back to train and test
test = train[shapeTrain:shapeTrain+shapeTest]
train = train[0:shapeTrain]

test['id'] = ids

train.to_csv('train_1.csv', index=False)
test.to_csv('test_1.csv', index=False)

我看到了 2 种解决方法:

1) 以某种方式遍历文件:

df_train = pd.read_csv('train.csv', chunksize=1500)
for chunk in df_train:
    #apply one-hot encoding

2) 通过仅将 one-hot 编码应用于训练然后进行测试来减少列的数量,但对于新的分类值将所有列设置为 0。

3) 使用the hashing trick !

我该如何解决这个问题?

最佳答案

如何在加载时指定数据类型:

types = {'col1': np.dtype(type),
     'col2': np.dtype(type),
     'col3' : np.dtype(type),
     'col4': np.dtype(type),
     'col5': np.dtype(type) }

train = pd.read_csv('train.csv', dtype=types)

运行 train.info() 如果你能够加载它并检查内存使用情况。

关于python - 如何对大文件应用单热编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38218796/

相关文章:

python - 如何从具有多行的 2 个不同数据集创建可视化?

excel - 如何使用 "|"分隔和 utf-8 代码将 Excel 导出到 csv 文件

python - 为什么在附加 Pandas 数据框时列顺序会发生变化?

python - page() 接受 1 个位置参数,但给出了 2 个

python - Pandas:从互斥选择的多列中获取一行中特定单个值的列索引/标签

linux - 在 django 应用程序中获取 python2.7 路径以进行子进程调用

python-2.7 - 导入错误 : No module named vaderSentiment

powershell - 如何使用powershell设置为可变csv列?

python - 更改类变量 : good practice or not? (Python)

python - 使用 python 删除尾随空格