Scikit-learn
파이썬 기반의 오픈소스 머신러닝 라이브러리
데이터 분석과 예측모델을 구축하기 위한 간결하고 효율적인 도구 모음을 제공한다.
선형회귀를 왜 사용하는가
공부시간 - 시험점수
이 둘의 관계는 '공부를 많이 할 수록 점수가 오른다' 라는 직선의 관계를 가지고 있다.
이럴 때 사용하는 것이 선형회귀(Linear Regression)이다.
데이터 준비
import numpy as np
X = np.array([[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]])
y = np.array([40, 45, 50, 55, 60, 65, 70, 78, 85, 90])
x -> 공부한 시간 (입력값 == Feature)
y -> 시험 점수 (정답 데이터 == Label)
학습데이터와 테스트 데이터 분리
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=42
)
학습데이터와 테스트 데이터를 분리하는 이유
-> 모델이 외운 것인지, 진짜로 예측하는지 확인하기 위해서이다.
학습용 데이터는 모델이 배우는 용도이며
테스트용 데이터는 성능을 검증 하는 용도이다.
random_state를 쓰는 이유 => 결과를 항상 동일하게 만들기 위해
모델 생성 및 학습
from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit(X_train, y_train)
LinearRegression()을 통해 선형 회귀 모델을 생성하고
fit()데이터를 통해 모델이 규칙을 학습한다.
다음 과정에서 모델은 y = ax + b 식을 찾는다
예측
y_pred = model.predict(X_test)
print("테스트 데이터 예측 결과:", y_pred)
학습한 모델을 통해 처음보는 데이터의 점수를 예측한다.
새로운 데이터 예측
new_hours = np.array([[7], [9]])
predicted_scores = model.predict(new_hours)
print("공부 7시간 → 예상 점수:", round(predicted_scores[0], 1))
print("공부 9시간 → 예상 점수:", round(predicted_scores[1], 1))
머신러닝의 진짜 목적은 -> 미래 데이터를 예측하는 것이다.
결과 시각화
import matplotlib.pyplot as plt
plt.figure(figsize=(8,5))
plt.scatter(X, y, color='blue', label='실제 데이터')
plt.plot(X, model.predict(X), color='red', label='예측선 (y = a*x + b)')
plt.scatter(new_hours, predicted_scores, color='green', marker='x', s=100, label='새로운 예측값')
plt.title("공부시간에 따른 시험 점수 예측")
plt.xlabel("공부 시간 (시간)")
plt.ylabel("시험 점수")
plt.legend()
plt.grid(True)
plt.show()

'Programing' 카테고리의 다른 글
| [speakLogs] #1 npm 설치하기 (0) | 2026.03.30 |
|---|---|
| [speakLogs] #0 개인프로젝트 기획 (0) | 2026.03.23 |
| 도메인기준 vs 계층형 기준 폴더구조의 장단점 (0) | 2026.03.23 |
| JpaRepository (0) | 2026.03.09 |
| [uniQdata/Java] org.postgresql.util.PSQLException: FATAL: role "postgres" does not exist (0) | 2026.03.09 |