如何找到回归线与OY轴相交的点?

问题描述 投票:2回答:1

我有一个文件,其中我提供了一些数据,x和y值。我的程序绘制了这些点的回归线,但我现在需要的是找到OY轴上的值,如果它将被拉长,我的线将相交。

What my program does now:

我需要简单地使线更长,与OY轴相交,并找到该点的精确坐标。

我的代码到目前为止:

import numpy as np

import matplotlib.pyplot as plt  # To visualize

import pandas as pd  # To read data

from sklearn.linear_model import LinearRegression
data = pd.read_csv('data.csv')  # load data set

X = data.iloc[:, 0].values.reshape(-1, 1)  # values converts it into a numpy array

Y = data.iloc[:, 1].values.reshape(-1, 1)  # -1 means that calculate the dimension of rows, but have 1 column

linear_regressor = LinearRegression()  # create object for the class

linear_regressor.fit(X, Y)  # perform linear regression

Y_pred = linear_regressor.predict(X)  # make predictions

plt.scatter(X, Y)

plt.plot(X, Y_pred, color='red')

plt.show()

我的代码需要一个名为“data.csv”的文件,其中包含给定值的坐标。我的例子有值:

5,0.8
10,0.7
15,0.66
20,0.493
25,0.5
30,0.21
python-3.x matplotlib linear-regression
1个回答
2
投票

你想要这样的东西,你可以使用你的LinearRegressor对象的intercept_属性来获得x等于零的y轴截距:

import numpy as np
import matplotlib.pyplot as plt  # To visualize
import pandas as pd  # To read data
from io import StringIO
from sklearn.linear_model import LinearRegression
txtfile = StringIO("""5,0.8
10,0.7
15,0.66
20,0.493
25,0.5
30,0.21""")
data = pd.read_csv(txtfile, header=None)  # load data set

X = data.iloc[:, 0].values.reshape(-1, 1)  # values converts it into a numpy array

Y = data.iloc[:, 1].values.reshape(-1, 1)  # -1 means that calculate the dimension of rows, but have 1 column

linear_regressor = LinearRegression()  # create object for the class

linear_regressor.fit(X, Y)  # perform linear regression

Y_pred = linear_regressor.predict(X)  # make predictions

plt.scatter(X, Y)

plt.plot(X, Y_pred, color='red')

plt.plot([0, X[0]], [linear_regressor.intercept_, Y_pred[0]], c="green",  linestyle='--')

ax = plt.gcf().gca()
ax.spines['left'].set_position('zero')
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)

plt.show()

输出:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.