티스토리 뷰

면접

Model selection

데이터조이 2022. 6. 25. 21:11

Score, Cross-validated Scores

Score: 새로운 데이터에 대한 적합(예측) 품질은 판단할 수 있는 점수 방법. 

 

Cross-validation generators

Cross-validation: 교차 검증. 데이터를 훈련 세트와 테스트 세트로 반복적으로 분할하고 훈련 세트를 통해 훈련하고 테스트 세트를 기반으로 점수 계산. (학습/테스트 색인 목록 생성 기능 제공함.)

 

Grid-search and cross-validated estimators

매개변수 그리드에서 추정기를 학습 시키는 동안 점수를 계산하고 교차 검증 점수를 최대화하기 위해 매개변수를 선택하는 객체 제공함. 

기본적으로 5중 교차 검증.

최적의 하이퍼파라미터를 찾는 방법. 

두 개의 교차 검증 루프가 병렬로 수행 됨. GridSearchCV에 의해 감마 설정하고, cross_val_score에 의해 추정기의 예측 성능을 측정.

 

 

import pandas as pd
import numpy as np

def predict_temperatures(models, x_val_copy):
    predictions = {f'model_{i}': model.predict(x_val_copy) for i, model in enumerate(models)}
    return predictions

def create_prediction_df(temp_value, predictions):
    pred_df_i = pd.DataFrame({
        'temp13': [temp_value] * len(x_val_copy),
        'ri_MFB': predictions['ri_m'],
        'la_MFB': predictions['la_m'],
        'ri_top_median': predictions['ri_t'],
        'la_top_median': predictions['la_t'],
        'ri_top_max': predictions['ri_x'],
        'la_top_max': predictions['la_x'],
        'ri_feed': predictions['ri_r'],
        'la_feed': predictions['la_r'],
    })
    return pred_df_i

def apply_constraints(pred_df_final):
    limits = {
        'ri_MFB': (12000, 12000),
        'la_MFB': (12000, 12000),
        'ri_top_median': (107, 107),
        'la_top_median': (107, 107),
        'ri_top_max': (107, 107),
        'la_top_max': (107, 107),
        'ri_feed': (80, 80),
        'la_feed': (80, 80)
    }

    conditions = [(pred_df_final[col] < limit[0]) & (pred_df_final[col] < limit[1]) for col, limit in limits.items()]
    final = pred_df_final.loc[conditions[0] & conditions[1] & conditions[2] & conditions[3] & conditions[4] & conditions[5] & conditions[6] & conditions[7], :]

    return final

# Original code
df = pd.DataFrame()  # Assuming df is your DataFrame
val = pd.DataFrame(df.iloc[-1, :]).T
temp13_list = list(np.arange(207, 220, 0.5))
x_val = val.drop(columns=['Date', 'MFB', 'DMTTI-631.PV_median', 'DMTTI-631.PV_max', 'DMTFIC-615.cv_median'])
x_val_copy = x_val.copy()

# Assume ri_m_model, ri_t_model, ri_x_model, and ri_r_model are your models
models = {
    'ri_m': ri_m_model,
    'la_m': ri_m_model,  # Corrected model name
    'ri_t': ri_t_model,
    'la_t': ri_t_model,  # Corrected model name
    'ri_x': ri_x_model,
    'la_x': ri_x_model,  # Corrected model name
    'ri_r': ri_r_model,
    'la_r': ri_r_model,  # Corrected model name
}

# Initialize an empty list to store DataFrames for each temperature value
pred_dfs = []

# 13단 온도별로 예측값 산출
for temp_value in temp13_list:
    x_val_copy['DMTTI-638B.PV_median'] = temp_value
    
    predictions = predict_temperatures(models, x_val_copy)
    pred_df_i = create_prediction_df(temp_value, predictions)
    
    pred_dfs.append(pred_df_i)

# Concatenate all DataFrames into a single DataFrame
pred_df_final = pd.concat(pred_dfs, ignore_index=True)

# Display the resulting DataFrame
print(pred_df_final)

# 제약조건 반영한 데이터셋 도출
final = apply_constraints(pred_df_final)

# Display results
true = round(val['DMTTI-638B.PV_median'].iloc[0], 1)
topT = round(val['DMTTI-631.PV_max'].iloc[0], 1)
reco = final['temp13'].min()
topM = round(final.loc[final['temp13'] == reco, 'ri_top_max'].iloc[0], 1)

print(f"\n13단 온도 실제값   : {true}도")
print(f"최상단 온도 실제값 : {topT}도\n")
print(f"13단 온도 추천값   : {reco}도")
print(f"최상단 온도 예측값 : {topM}도")

'면접' 카테고리의 다른 글

feature selection  (0) 2022.08.04
SQL  (0) 2022.06.26
Model  (0) 2022.06.26
sklearn - K-NN, Linear, SVM  (0) 2022.06.25
데이터분석전공  (0) 2016.10.24
댓글
Total
Today
Yesterday
공지사항
최근에 올라온 글
글 보관함