주어진 데이터를 하나씩 분석하며, 라이브러리 사용법을 배워봅시다
df = pd.read_csv("FuelConsumption.csv")// 주어진 CSV를 읽는다
"FuelConsumption.csv"라는 CSV 파일을 읽어와서 pandas DataFrame 객체인 df
에 저장합니다.
여기서 pandas는 데이터 분석에 널리 사용되는 Python 라이브러리입니다.
데이터 조회
# take a look at the dataset
df.head()
df.head()
는 DataFrame의 처음 5행을 출력합니다.
이 메소드를 사용하면, 데이터셋의 구조와 각 열(column)에 들어있는 데이터를 빠르게 확인할 수 있습니다.
데이터 통계
df.describe()
df.describe()
는 DataFrame의 **각 열에 대한 기술통계(descriptive statistics)**를 출력합니다.
기술통계에는 평균, 표준편차, 최소값, 25%, 50%, 75% 백분위수(분위수), 최대값 등이 포함됩니다.
이 정보를 통해 데이터의 분포, 중심 경향, 변동 등을 파악할 수 있습니
데이터 프레임 생성
cdf = df[['ENGINESIZE','CYLINDERS','FUELCONSUMPTION_COMB','CO2EMISSIONS']]
cdf.head(9)
이 코드는 df
DataFrame에서 ‘ENGINESIZE’, ‘CYLINDERS’, ‘FUELCONSUMPTION_COMB’, 'CO2EMISSIONS’라는 이름의 열만 선택하여 새로운 DataFrame cdf
에 저장합니다.
그리고 cdf.head(9)
는 cdf
DataFrame의 처음 9행을 출력합니다
데이터 시각화
히스토리그램
viz = cdf[['CYLINDERS','ENGINESIZE','CO2EMISSIONS','FUELCONSUMPTION_COMB']]
viz.hist()
plt.show()
이 코드는 ‘CYLINDERS’, ‘ENGINESIZE’, ‘CO2EMISSIONS’, 'FUELCONSUMPTION_COMB’라는 4개의 열에 대한 히스토그램을 생성합니다.
히스토그램은 변수의 분포를 보여주는 그래프로, 데이터의 형태, 중심, 퍼진 정도를 한눈에 파악하는데 유용합니다.
plt.show()
는 그래프를 화면에 출력하는 함수입니다.
산점도
plt.scatter(cdf.FUELCONSUMPTION_COMB, cdf.CO2EMISSIONS, color='blue')
plt.xlabel("FUELCONSUMPTION_COMB")
plt.ylabel("Emission")
plt.show()// 디스플레이에 뿌려주는 함수
이 코드는 ‘FUELCONSUMPTION_COMB’(x축)와 ‘CO2EMISSIONS’(y축) 사이의 산점도를 생성합니다.
산점도는 두 변수 사이의 관계를 보여주는 그래프입니다. 여기서는 연료 소비량과 CO2 배출량 사이의 관계를 시각적으로 표현하고 있습니다.
plt.scatter(cdf.ENGINESIZE, cdf.CO2EMISSIONS, color='blue')
plt.xlabel("Engine size")
plt.ylabel("Emission")
plt.show()
데이터 분할 : 80% 훈련과 20% 테스트
msk = np.random.rand(len(df)) < 0.8
train = cdf[msk]
test = cdf[~msk]
np.random.rand() 함수를 사용하여 임의의 행을 선택하는 마스크를 만듭니다.
train 데이터로 그래프를 그립니다.
plt.scatter(train.ENGINESIZE, train.CO2EMISSIONS, color='blue')
plt.xlabel("Engine size")
plt.ylabel("Emission")
plt.show()
“Modeling” 섹션에서는 sklearn 패키지를 사용하여 데이터 모델링을 수행합니다.
from sklearn import linear_model
regr = linear_model.LinearRegression()
train_x = np.asanyarray(train[['ENGINESIZE']])
train_y = np.asanyarray(train[['CO2EMISSIONS']])
regr.fit(train_x, train_y)
# The coefficients
print ('Coefficients: ', regr.coef_)
print ('Intercept: ',regr.intercept_)
위 코드에서는 sklearn의 선형 회귀 모델(linear_model.LinearRegression()
)을 사용합니다.
훈련 데이터의 'ENGINESIZE’와 'CO2EMISSIONS’를 각각 train_x, train_y로 설정하고,
regr.fit(train_x, train_y)
를 이용해 모델을 학습시킵니다.
그 다음, 학습된 모델의 계수(Coefficients)와 절편(Intercept)를 출력합니다.
이 값들은 선형 회귀 모델의 기울기와 y절편에 해당하는 값들입니다.
단순 선형 회귀에서의 계수 와 절편 은 적합선의 매개변수입니다.
간단한 선형 회귀이기 때문에 매개변수가 두 개뿐이며, 이 매개변수들이 선의 절편과 기울기라는 것을 알고 있습니다.
plt.scatter(train.ENGINESIZE, train.CO2EMISSIONS, color='blue')
plt.plot(train_x, regr.coef_[0][0]*train_x + regr.intercept_[0], '-r')
plt.xlabel("Engine size")
plt.ylabel("Emission")
regr.coef_[0][0]*train_x + regr.intercept_[0]
는 선형 회귀 모델의 방정식입니다.
-r
옵션은 선의 색을 빨간색으로 설정합니다.
세 번째와 네 번째 줄에서는 x축과 y축에 각각 "Engine size"와 “Emission” 라는 라벨을 부여합니다.
from sklearn.metrics import r2_score
test_x = np.asanyarray(test[['ENGINESIZE']]) # 테스트 데이터의 독립 변수로 사용할 '엔진 크기' 열을 선택합니다.
test_y = np.asanyarray(test[['CO2EMISSIONS']]) # 테스트 데이터의 종속 변수로 사용할 '이산화탄소 배출량' 열을 선택합니다.
test_y_ = regr.predict(test_x) # 테스트 데이터의 독립 변수를 사용하여 모델에서 예측 값을 얻습니다.
print("Mean absolute error: %.2f" % np.mean(np.absolute(test_y_ - test_y))) # 평균 절대 오차를 계산하고 출력합니다.
print("Residual sum of squares (MSE): %.2f" % np.mean((test_y_ - test_y) ** 2)) # 잔차 제곱의 평균인 MSE를 계산하고 출력합니다.
print("R2-score: %.2f" % r2_score(test_y , test_y_)) # R2-score를 계산하고 출력합니다.
Exercise
Lets see what the evaluation metrics are if we trained a regression model using the FUELCONSUMPTION_COMB
feature.
Start by selecting FUELCONSUMPTION_COMB
as the train_x data from the train
dataframe, then select FUELCONSUMPTION_COMB
as the test_x data from the test
dataframe
train_x = train[["FUELCONSUMPTION_COMB"]]
test_x = test[["FUELCONSUMPTION_COMB"]]
Now train a Linear Regression Model using the train_x
you created and the train_y
created previously
regr = linear_model.LinearRegression()
regr.fit(train_x,train_y)
Find the predictions using the model’s predict
function and the test_x
data
predictions= regr.predict(test_x)
Finally use the predictions
and the test_y
data and find the Mean Absolute Error value using the np.absolute
and np.mean
function like done previously
print("Mean absolute error: %.2f" % np.mean(np.absolute(predictions - test_y)))
print("Residual sum of squares (MSE): %.2f" % np.mean((predictions - test_y) ** 2))
결과
Mean absolute error: 19.38
Residual sum of squares (MSE): 756.25
계산된 MAE는 19.38로, 예측 값과 실제 값 사이의 평균 절대 차이를 나타냅니다.
MSE는 756.25로, 예측 값과 실제 값 사이의 평균 제곱 차이를 나타냅니다.
이를 통해 ‘FUELCONSUMPTION_COMB’ 특성을 기반으로 CO2 배출량을 예측하는 회귀 모델의 정확도와 성능을 평가할 수 있습니다
부족한 점이나 잘못 된 점을 알려주시면 시정하겠습니다 :>
'AI' 카테고리의 다른 글
Multiple Linear Regression 실습 (0) | 2023.07.06 |
---|---|
Multiple Linear Regression (0) | 2023.07.06 |
회귀 모델에서의 손실 함수 (0) | 2023.07.05 |
Model Evaluation in Regression Models (0) | 2023.07.05 |
Supervised vs Unsupervised (0) | 2023.07.05 |