matplotlib 多项式回归曲线

1bqhqjot  于 12个月前  发布在  其他
关注(0)|答案(3)|浏览(84)

我试图为我的数据创建一个2度的回归曲线。当我创建我的图表时,我得到了一个有趣的锯齿形东西:

但我想把我的数据建模成一条实际的曲线,看起来就像散点图的连接版本。

有什么建议/更好的方法吗?

degree = 2
p = np.poly1d(np.polyfit(data['input'],y, degree))
plt.plot(data['input'], p(data['input']), c='r',linestyle='-')
plt.scatter(data['input'], p(data['input']), c='b')

在这里,数据[['input']是与y具有相同维度的列向量。
编辑:我也试过这样做:

X, y = np.array(data['input']).reshape(-1,1), np.array(data['output'])
lin_reg=LinearRegression(fit_intercept=False)
lin_reg.fit(X,y)

poly_reg=PolynomialFeatures(degree=2)
X_poly=poly_reg.fit_transform(X)
poly_reg.fit(X_poly,y)
lin_reg2=LinearRegression(fit_intercept=False)
lin_reg2.fit(X_poly,y)

X_grid=np.arange(min(X),max(X),0.1)
X_grid=X_grid.reshape((len(X_grid),1))
plt.scatter(X,y,color='red')
plt.plot(X,lin_reg2.predict(poly_reg.fit_transform(X)),color='blue')
plt.show()

这给了我这个图表。

散点图是我的数据,蓝色之字形是一条二次曲线,用来模拟数据。帮助?

4xy9mtcn

4xy9mtcn1#

在你的图中,你只需要用直线从一点到另一点进行绘制(其中y值是来自polyfit函数的近似y)。
我会跳过polyfit函数(因为你有你感兴趣的所有y值),只需要用B样条函数scipy插值data['input']y,然后用你感兴趣的x范围绘制新的y值。

import numpy as np
import matplotlib.pyplot as plt
import scipy.interpolate as interp

仅从点到点绘制(锯齿形)

x = np.array([1, 2, 3, 4])
y = np.array([75, 0, 25, 100])
plt.plot(x, y)

插值点

x_new = np.linspace(1, 4, 300)
a_BSpline = interp.make_interp_spline(x, y)
y_new = a_BSpline(x_new)
plt.plot(x_new, y_new)

试试这个,然后用你的数据调整!:)

svmlkihl

svmlkihl2#

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures

#improve degree = 3
p_reg = PolynomialFeatures(degree = 3)
X_poly = p_reg.fit_transform(X)

#again create new linear regression obj
reg2 = LinearRegression()
reg2.fit(X_poly,y)
plt.scatter(X, y, color = 'b')
plt.xlabel('Level')
plt.ylabel('Salary')
plt.title("Truth or Bluff")

# predicted values
plt.plot(X, reg2.predict(X_poly), color='r')
plt.show()

With Degree 3
With Degree 4

agxfikkp

agxfikkp3#

因为你没有给我们看你的数据,我假设你的自变量不是单调的。
下面是我的代码
1.它计算两个数据向量,其中 y = y(x)x 不是单调的
1.它计算一个拟合数据的二次多项式
1.它在上图的左侧绘制了 x与y 的散点图和 x与y=p(x) 的线图,其中 y 是根据最佳拟合多项式计算的
1.它排序 x → xs
1.在上图的右边部分,它再次绘制了相同的散点图和 xs vs y=p(xs) 的线图。
.

import matplotlib.pyplot as plt
import numpy as np
np.random.seed(0)

# x is not monotonic
x = np.random.random(60)
# y is quadratic with a quartic "error"
y = 0.3+1.2*x-1.4*(x-0.5)**2 - x**4/3
# find the 2nd degree poly1d object that best fits data
p = np.poly1d(np.polyfit(x, y, 2))

fig, (ax0, ax1) = plt.subplots(1,2,figsize=(8,4),layout='constrained')
s=6 ; lw=0.75
# what you did?
ax0.scatter(x, y, c='k', s=s)
ax0.plot(x, p(x), lw=lw)
# what you want?
xs = np.sort(x)
ax1.scatter(x, y, c='k', s=s)
ax1.plot(xs, p(xs), lw=lw)
#
plt.show()

相关问题