简体   繁体   中英

Predict a discret value with sklearn

Can anyone help to teach how to predict the response of x=12? what is the command or instruction to enter?

from sklearn.linear_model import LinearRegression
import numpy as np
#Data

x = np.array([6, 8, 10, 14, 18]).reshape((-1, 1))
y = np.array([7, 9, 13, 17, 18])

#Instantion of the model

model_linearReg=LinearRegression()
model_linearReg.fit(x,y)

#Precision of the model

precision=model_linearReg.score(x,y)
print(precision*100)

#prediction of the model

prediction=model_linearReg.predict(x)
print(prediction)

Inputs for LinearRegression or any sklearn classifier almost always are 2D numpy arrays with the shape N_targets x N_features ; since your regression task just has one variable ( N_targets = 1 ) and one feature ( N_features = 1 ) you just need to wrap 12 into a list (technically array-like ) twice:

import numpy as np
from sklearn.linear_model import LinearRegression

x = np.array([6, 8, 10, 14, 18]).reshape((-1, 1))
y = np.array([7, 9, 13, 17, 18])

lr = LinearRegression().fit(x, y)
print(lr.predict([[12]])) # [13.56896552]
# probably want to unwrap as well
print(lr.predict([[12]])[0]) # 13.56896551724138

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM