Kin*_*gua 5 python numpy python-3.x pandas scikit-learn
我正在使用 Pandas 在内存中加载二维数据集,并执行 4 个简单的机器学习预处理任务,例如添加/删除列、重新索引、训练/测试拆分。
#Read file
MLMe = pd.read_table("data/dtCTG.txt", ",")
#Label target column to "class"
MLMe.rename(columns={'NSP' : 'class'}, inplace=True)
#Create train/test indices
MLMe_class = MLMe['class'].values
training_indices, validation_indices = training_indices, testing_indices = train_test_split(
MLMe.index, stratify = MLMe_class, train_size=0.75, test_size=0.25)
#Create train/test data sets
X_train = MLMe.drop('class',axis=1).loc[training_indices].values
y_train = MLMe.loc[training_indices,'class'].values
X_test = MLMe.drop('class',axis=1).loc[validation_indices].values
y_test = MLMe.loc[validation_indices, 'class'].values
#Final datasets to be used for training
X_train, y_train, X_test, y_test
Run Code Online (Sandbox Code Playgroud)
现在,当我将 X_train、y_train 数据帧传递给某些库时,我收到一条错误消息,指出缓冲区不再是 C 连续的。
BufferError: memoryview: underlying buffer is not C-contiguous
Run Code Online (Sandbox Code Playgroud)
我的问题是: 如何制作 X_train、y_train C 连续缓冲区? 我尝试使用 C 和 F 选项进行整形,但没有运气。
编辑:以下是数据帧的形状、dtype 和标志:
X_train.shape, y_train.shape, X_test.shape, y_test.shape
((1104, 9), (1104,), (369, 9), (369,))
X_train.dtype, y_train.dtype, X_test.dtype, y_test.dtype
(dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'))
X_train.flags, y_train.flags, X_test.flags, y_test.flags
( C_CONTIGUOUS : False
F_CONTIGUOUS : True
OWNDATA : False
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False,
C_CONTIGUOUS : True
F_CONTIGUOUS : True
OWNDATA : True
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False,
C_CONTIGUOUS : False
F_CONTIGUOUS : True
OWNDATA : False
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False,
C_CONTIGUOUS : True
F_CONTIGUOUS : True
OWNDATA : True
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
)
Run Code Online (Sandbox Code Playgroud)
我们无法直接控制 DataFrame 如何存储其值,这些值可以是 c 连续的,也可以不是。ascontiguousarray但是,通过在底层 numpy 数组上使用 numpy 函数,可以轻松获取 C 连续数据,该数据由value数组的属性返回。您可以自己测试一下:
X_train.flags.c_contiguous # Checks if the array is C-contiguous
#>>> False
X_train = np.ascontiguousarray(X_train) # Converts the array to C-contiguous
X_train.flags.c_contiguous
#>>> True
Run Code Online (Sandbox Code Playgroud)
numpy.ascontiguousarray可以在此处找到该
文档: https ://numpy.org/doc/stable/reference/ generated/numpy.ascontigouslyarray.html
| 归档时间: |
|
| 查看次数: |
1099 次 |
| 最近记录: |