Regression ระดับกลางด้วย statsmodels ใน Python
Maarten Van den Broeck
Content Developer at DataCamp


กราฟเส้นของสมการกำลังสอง
x = np.arange(-4, 5, 0.1)
y = x ** 2 - x + 10
xy_data = pd.DataFrame({"x": x,
"y": y})
sns.lineplot(x="x",
y="y",
data=xy_data)

$y = x ^ 2 - x + 10$
$\frac{\partial y}{\partial x} = 2 x - 1$
$0 = 2 x - 1$
$x = 0.5$
$y = 0.5 ^ 2 - 0.5 + 10 = 9.75$
ไม่ต้องกังวลหากยังไม่เข้าใจส่วนนี้ ไม่จำเป็นต้องใช้ในแบบฝึกหัด

from scipy.optimize import minimize
def calc_quadratic(x):
y = x ** 2 - x + 10
return y
minimize(fun=calc_quadratic,
x0=3)
fun: 9.75
hess_inv: array([[0.5]])
jac: array([0.])
message: 'Optimization terminated successfully.'
nfev: 6
nit: 2
njev: 3
status: 0
success: True
x: array([0.49999998])
กำหนดฟังก์ชันสำหรับคำนวณเมตริก sum of squares
เรียกใช้ minimize() เพื่อหาค่าสัมประสิทธิ์ที่ทำให้ฟังก์ชันนี้มีค่าต่ำที่สุด
def calc_sum_of_squares(coeffs):
intercept, slope = coeffs
# More calculation!
minimize(
fun=calc_sum_of_squares,
x0=0
)
Regression ระดับกลางด้วย statsmodels ใน Python