จากชุดของจุดข้อมูลที่กำหนด การถดถอยเชิงเส้นจะพบสมการของเส้นตรง คะแนนที่กำหนดจะเป็นไปตามเส้นตรง เมื่อใช้สูตรนี้ เราสามารถคาดเดาได้ว่าค่าใดจะเป็นค่าสำหรับจุดเฉพาะอื่นๆ ซึ่งไม่มีอยู่ในชุดปัจจุบัน
สำหรับการแก้ปัญหาการถดถอยเชิงเส้นโดยใช้จุดข้อมูลบางส่วน เราต้องปฏิบัติตามสูตรต่อไปนี้:

โดยที่ m และ c คือความชันและค่าตัดแกน y ตามลำดับ เมื่อใช้นิพจน์เหล่านี้ เราจะได้สมการของเส้นตรงในรูปแบบนี้:𝑦 =𝑚𝑥 + 𝑐
อินพุตและเอาต์พุต
Input:
The (x, y) coordinates of some points. {(1,3), (2,4), (3,5), (4,6), (5,8)}
Output:
The slope: 1.2 The Intercept: 1.6
The equation: y = 1.2x + 1.6 อัลกอริทึม
linReg(coord)
ป้อนข้อมูล: ชุดจุดพิกัดที่กำหนด
ผลลัพธ์: ความชัน m และจุดตัด y ค.
Begin for i := 1 to n, do sumX := sumX + coord[i,0] sumY := sumY + coord[i,1] sumXsq := sumXsq + (coord[i,0]*coord[i,0]) sumXY := sumXY + (coord[i,0] * coord[i,1]) done m := (n * sumXY – (sumX*sumY)) / (n * sumXsq – (sumX * sumX)) c := (sumY / n) – (m * sumX)/n End
ตัวอย่าง
#include<iostream>
#include<cmath>
#define N 5
using namespace std;
void linReg(int coord[N][2], float &m, float &c) {
float sx2 = 0, sx = 0, sxy = 0, sy = 0;
for(int i = 0; i<N; i++) {
sx += coord[i][0]; //sum of x
sy += coord[i][1]; //sum of y
sx2 += coord[i][0]*coord[i][0]; //sum of x^2
sxy += coord[i][0]*coord[i][1]; //sum of x*y
}
// finding slope and intercept
m = (N*sxy-(sx*sy))/(N*sx2-(sx*sx));
c = (sy/N)-(m*sx)/N;
}
main() {
// this 2d array holds coordinate points
int point[N][2] = {{1,3},{2,4},{3,5},{4,6},{5,8}};
float m, c;
linReg(point, m, c);
cout << "The slope: " << m << " The Intercept: " << c << endl;
cout << "The equation: " << "y = "<< m <<"x + "<< c;
} ผลลัพธ์
The slope: 1.2 The Intercept: 1.6 The equation: y = 1.2x + 1.6