簡體   English   中英

具有 2 個特征的 Scikitlearn 線性回歸

[英]Scikitlearn Linear Regression with 2 features

我是 scikit 學習的新手,正在嘗試擬合一個簡單的線性回歸 model。我有一個包含 2 列 c1 和 c1^2 的矩陣 X,並且我有相應的 y 值。 我嘗試使用 scikit learn 來擬合一個簡單的 OLS model,但最后我變得很奇怪 plot。 關於我做錯了什么的任何想法?

X = np.array([[ -0.016746535778021,   0.280446460564527],
  [-0.014577470749242,   0.212502653445002],
   [0.034515758657299,   1.191337595688933],
  [-0.047010075743201,   2.209947221381472],
   [0.036975119046363,   1.367159428492700],
  [-0.040686110015367,   1.655359548182586],
  [-0.004472010975766,   0.019998882167376],
  [0.026533634894789 ,  0.704033780729957],
  [-0.042797683100180,   1.831641678743394],
   [0.025374099383528,   0.643844919525139],
  [-0.031109553977308,   0.967804348667025],
   [0.027311768635213,   0.745932705983427],
  [-0.003263862013657,   0.010652795244191],
  [-0.001818276487116,   0.003306129383598],
  [-0.040719662402516,   1.658090906174888],
  [-0.050013243645495,   2.501324539943689],
  [-0.017411771548016,   0.303169788440313],
   [0.003588193696644,   0.012875134004637],
   [0.007085480261971,   0.050204030542776,],
   [0.046282369018539,   2.142057681968212],
   [0.014612289091657,   0.213518992498145]])*1e3

y = np.array([4.1702,
    4.0673,
   31.8731,
   10.6237,
   31.8360,
    4.9594,
    4.4516,
   22.2763,
   -0.0000,
   20.5038,
    3.8583,
   19.3651,
    4.8838,
   11.0972,
    7.4617,
    1.4769,
    2.7192,
   10.9269,
    8.3487,
   52.7819,
   13.3573])

from sklearn.linear_model import LinearRegression as LR

model1 = LR().fit(X,y)

import matplotlib.pyplot as plt

plt.plot(X[:,0],model1.predict(X))
plt.scatter(X[:,0],y,color = 'red')
plt.show()

陰謀

plt.plot() function 按照您給出的順序繪制線條。為了繪制回歸線,您需要按照 X 的最小值到最大值的順序輸入 X 值和預測值。最簡單的方法是:

predictions = model1.predict(X)
order = X[:,0].argsort()
predictions = predictions[order]
x = X[:,0][order]


plt.plot(x,predictions)
plt.scatter(X[:,0],y,color = 'red')
plt.show()

在此處輸入圖像描述

這是你要的嗎?

import numpy as np
from sklearn.linear_model import LinearRegression as LR
import matplotlib.pyplot as plt


model1 = LR().fit(X,y)

preds = model1.predict(X)


plt.scatter(preds, y)

xpoints = ypoints = plt.xlim()
plt.plot(xpoints, ypoints, linestyle='--', color='k')
plt.show()

線性擬合

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM