简体   繁体   English

使用 sklearn 预测离散值

[英]Predict a discret value with sklearn

Can anyone help to teach how to predict the response of x=12?任何人都可以帮助教如何预测 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 ; LinearRegression或任何 sklearn 分类器的输入几乎总是 2D numpy arrays 形状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:由于您的回归任务只有一个变量( N_targets = 1 )和一个特征( N_features = 1 ),您只需将12包装到一个列表中(技术上类似于数组)两次:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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