I'm having difficulty converting a structured array loaded from a CSV using np.genfromtxt
into a np.array
in order to fit the data to a Scikit-Learn estimator. The problem is that at some point a cast from the structured array to a regular array will occur resulting in a ValueError: can't cast from structure to non-structure
. For a long time, I had been using .view
to perform the conversion but this has resulted in a number of deprecation warnings from NumPy. The code is as follows:
import numpy as np
from sklearn.ensemble import GradientBoostingClassifier
data = np.genfromtxt(path, dtype=float, delimiter=',', names=True)
target = "occupancy"
features = [
"temperature", "relative_humidity", "light", "C02", "humidity"
]
# Doesn't work directly
X = data[features]
y = data[target].astype(int)
clf = GradientBoostingClassifier(random_state=42)
clf.fit(X, y)
The exception being raised is: ValueError: Can't cast from structure to non-structure, except if the structure only has a single field.
My second attempt was to use a view as follows:
# View is raising deprecation warnings
X = data[features]
X = X.view((float, len(X.dtype.names)))
y = data[target].astype(int)
Which works and does exactly what I want it to do (I don't need a copy of the data), but results in deprecation warnings:
FutureWarning: Numpy has detected that you may be viewing or writing to
an array returned by selecting multiple fields in a structured array.
This code may break in numpy 1.15 because this will return a view
instead of a copy -- see release notes for details.
At the moment we're using tolist()
to convert the structured array to a list and then to a np.array
. This works, however it seems terribly inefficient:
# Current method (efficient?)
X = np.array(data[features].tolist())
y = data[target].astype(int)
There has to be a better way, I'd appreciate any advice.
NOTE: The data for this example is from the UCI ML Occupancy Repository and the data appears as follows:
array([(nan, 23.18, 27.272 , 426. , 721.25, 0.00479299, 1.),
(nan, 23.15, 27.2675, 429.5 , 714. , 0.00478344, 1.),
(nan, 23.15, 27.245 , 426. , 713.5 , 0.00477946, 1.), ...,
(nan, 20.89, 27.745 , 423.5 , 1521.5 , 0.00423682, 1.),
(nan, 20.89, 28.0225, 418.75, 1632. , 0.00427949, 1.),
(nan, 21. , 28.1 , 409. , 1864. , 0.00432073, 1.)],
dtype=[('datetime', '<f8'), ('temperature', '<f8'), ('relative_humidity', '<f8'),
('light', '<f8'), ('C02', '<f8'), ('humidity', '<f8'), ('occupancy', '<f8')])