Timothy Pulliam
Timothy Pulliam

Reputation: 142

Randomly sample data from sklearn dataset

I have a bunches object from sklearn that looks like this.

from sklearn.datasets import load_boston
import scipy
import numpy as np

boston = load_boston()
n_samples = boston.data.shape[0]

print(boston.keys())
dict_keys(['data', 'target', 'feature_names', 'DESCR', 'filename'])

I want to randomly sample 30 samples and 30 targets from the data and target keys.

    X, y = [np.array([boston.data[i]]), np.array([boston.target[i]) for i in np.random(choice(n_samples, 30)])
                                                            ^
SyntaxError: invalid syntax

This is all so I can plot a regression using the first feature

slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(X[:][0], y)
regression = intercept + slope*X[:][0]

boston.data and boston.target are both numpy arrays. How can I accomplish this?

print(type(boston.data))
<class 'numpy.ndarray'>

print(type(boston.target))
<class 'numpy.ndarray'>

Upvotes: 0

Views: 2275

Answers (1)

SmellsLikeCake
SmellsLikeCake

Reputation: 65

You have a couple of typos (e.g. it's random.choice) and you're also overwriting your arrays. This should work:

x = []
y = []
for i in np.random.choice(n_samples, 30):
    x.append(boston.data[i])
    y.append(boston.target[i])

Upvotes: 1

Related Questions