โปรแกรมถดถอยเชิงเส้นอย่างง่าย

ในบทความนี้ เราจะแสดงตัวอย่างหนึ่งของ Simple Linear Regression Program

[sc_fs_faq HTML = พาดหัว 'ความจริง' = 'H2 "img ='' คำถาม = 'ง่ายถดถอยเชิงเส้นโปรแกรม' img_alt = '' css_class = ''] นำเข้าห้องสมุด
นำเข้าชุด
แยกชุดข้อมูลเป็นชุดการฝึกอบรมและการทดสอบการตั้งค่า
การฝึกอบรม แบบจำลองการถดถอยเชิงเส้นอย่างง่ายในชุดการฝึก การ
ทำนายผลชุดทดสอบ การ
แสดงภาพชุดการฝึก การ
แสดงภาพผลชุดการทดสอบ
[/sc_fs_faq]

สูตรมีดังนี้:

y = b0 + b1 * x1

y = ตัวแปรตาม (DV)
b0 = ค่าคงที่
b1 = สัมประสิทธิ์
x1 = ตัวแปรอิสระ (IV)

นี่คือตัวอย่างหนึ่งของโปรแกรม:

นำเข้าไลบรารี

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

นำเข้าชุดข้อมูล

dataset = pd.read_csv('dataset-file.csv')

x = dataset.iloc[:, :-1].values

x = dataset.iloc[:, -1].values

แทนที่ไฟล์dataset-file.csvด้วยไฟล์ของคุณและระบุพาธแบบเต็มของไฟล์

แยกชุดข้อมูลออกเป็นชุดการฝึกและชุดทดสอบ

from sklearn.model_selection import train_test_split

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.2, random_state = 0)

การฝึกโมเดลการถดถอยเชิงเส้นอย่างง่ายในชุดการฝึก

from sklearn.linear_model import LinearRegression

regressor = LinearRegression()

regressor.fit(x_train, y_train)

ทำนายผลชุดทดสอบ

y_pred = regressor.predict(x_test)

การแสดงภาพผลลัพธ์ชุดการฝึก

plt.scatter(x_train, y_train, color = 'red')

plt.plot(x_train, regressor.predit(x_train), color = 'blue')

plt.title('Name of the graph')

plt.xlabel('Name of the x label')

plt.ylabel('name of the y label')

plt.show()

การแสดงภาพผลชุดทดสอบ

plt.scatter(x_test, y_test, color = 'red')

plt.plot(x_train, regressor.predit(x_train), color = 'blue')

plt.title('Name of the graph')

plt.xlabel('Name of the x label')

plt.ylabel('name of the y label')

plt.show()

เราได้แสดงโปรแกรมการถดถอยเชิงเส้นอย่างง่าย