如何在此数据帧上强制直线和方程通过 0?我只知道如何制作一条最适合的线和匹配的方程。下面是没有通过 0 强制截距的最佳拟合线的代码。任何获得强制截距的帮助都将受到赞赏!
import seaborn as sns
import scipy as sp
r, p = sp.stats.pearsonr(x=df['mass(mg)'], y=df['Abs'])
sns.regplot(x=df['mass(mg)'],y=df['Abs']).set(Title='biuret standard plot')
def equation(x,y):
x_mean = x.mean()
y_mean = y.mean()
B1_num = ((x - x_mean) * (y - y_mean)).sum()
B1_den = ((x - x_mean)**2).sum()
B1 = B1_num / B1_den
B0 = y_mean - (B1*x_mean)
reg_line = 'y = {} + {}β'.format(B0, round(B1, 3))
return (B0, B1, reg_line)
equation(df['mass(mg)'],df['Abs'])
最佳答案
Seaborn 的线性回归不会让您这样做。
因此,如果您试图让直线穿过原点,即 (0,0),那么您的方程为 y=mx。如果你这样做的话就没有B0。因此,我们使用 numpy.linalf.lstq 进行最小二乘并强制其通过原点。我们还添加 0 坐标以便它可以绘制。考虑您的质量和 Abs 值,请参见下文:
import numpy as np
import matplotlib.pyplot as plt
# I'm adding a 0 in both x and y axis to force a line drawn.
x = np.array([0, 5, 4, 3, 2, 1, 0.5])
y = np.array([0, 0.596, 0.464, 0.333, 0.201, 0.121, 0.062])
# We only need a*x. so to figure out a we use lstsq from numpy
# Our x matrix is one dimensional, it needs to be two dimensional to use lstsq so:
x = x[:,np.newaxis]
a, _, _, _ = np.linalg.lstsq(x, y)
plt.plot(x, y, 'bo')
plt.plot(x, a*x, 'r-')
plt.xlim([0, 6])
plt.ylim([0, 0.7])
plt.show()
print(f"y = {a} x + 0")
哪些输出:
随意添加标签等。
希望这对您有所帮助,如果有帮助,请将其标记为答案!
关于python - 如何在 python 线性回归图上强制截距?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71096762/