Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simultaneous predictions

I have fitted a linear model using sklearn.linear_model.LinearRegression

Lets call it model

I have a list of X_1, X_2, ..., X_n

And what I do is predict them each one by one like:

for X_i in list:
    model.predict(X_i)

Is there a faster way to do this? Maybe I can concatenate all X_i together and then predict them all at once?

like image 583
Markoff Chainz Avatar asked Jun 20 '26 01:06

Markoff Chainz


2 Answers

You can call predict with a numpy.array and get back a numpy.array of predictions:

Take a look at this MVCE, using fit to odd numbers of X for y = 2X to predict even numbers of X:

from sklearn.linear_model import LinearRegression
import numpy as np

X = [1, 3, 5, 7, 9]
y = [2, 6, 10, 14, 18]
lr = LinearRegression()
X = np.array(X)
# However, you need to reshape your X array to be 2-D instead of 1-D.
X = X[:, None]

lr.fit(X, y)

X_pred = [2, 4, 6, 8]
# Combine numpy array and reshape into one statement
X_pred = np.array(X_pred)[:, None] 

y_pred = lr.predict(X_pred)
y_pred

Output:

array([4.,  8., 12., 16.])
like image 200
Scott Boston Avatar answered Jun 22 '26 19:06

Scott Boston


Assuming X1 ... XN are numpy arrays you can concatenate them like this:

X = np.concatenate((X1, X2, X3), axis=0) 

And pass this array to fit/predict.

like image 22
Szymon Maszke Avatar answered Jun 22 '26 17:06

Szymon Maszke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!