21 Şubat 2023 Salı

Writing ensemble model code with ChatGPT

Utilizing ChatGPT may be the next great skill, as it has the potential to eliminate the need for advanced knowledge of coding.

Here is an example of how I used ChatGPT to create an ensemble model for a classification project:











18 Ocak 2023 Çarşamba

İki dataframe arasındaki farklı (birbirlerinde olmayan) kolonları bulmak

Birbirine benzer veriler içeren iki dataframe'den (örneğin aynı projedeki test ve train verileri) birinde olup diğerinde olmayan kolonun -ya da kolonların- adını bulmak için gereken kod aşağıda. Örneğimizde doğal olarak bağımlı değişken (dependent variable) yani "y" durumundaki satış fiyatı kolonu sonuç olarak karşımıza çıkıyor. (+ Öncesinde train_cols ve test_cols'u tanımlıyoruz.)




train_cols=train_data.columns
test_cols=test_data.columns

list_difference = []
for item in train_cols:
    if item not in test_cols:
        list_difference.append(item)
print(list_difference)

31 Aralık 2022 Cumartesi

XGBoost Parameters

In this blogpost, I will write down and update my notes on XGBoost parameters.

First five excellent videos on XGBoost from Statquest channel:

XGBoost Part 1 (of 4): Regression

XGBoost Part 2 (of 4): Classification

XGBoost Part 3 (of 4): Mathematical Details

XGBoost Part 4 (of 4): Crazy Cool Optimizations

XGBoost in Python from Start to Finish

and a bonus here from Pedram Jahangiry's Youtube channel.

Here is a nice introductory thread on twitter on this topic by Martin Bel.

11 Aralık 2022 Pazar

error 'DataFrame' object has no attribute 'Column_Name' hatasının çözümü

Bazen herhangi bir kolonda bir işlem yapmak istediğimizde "error 'DataFrame' object has no attribute 'Column_Name' " şeklinde bir uyarı çıkıyor. Bu durumda, özellikle de başka kolonlarda yapabildiğimiz ama bu kolonlarda yapamadığımız dönüşümlerin muhtemel bir sebebi, söz konusu kolonun adının aslında farklı olması ve bunu bizim tespit edemememiz. Aşağıda bunun aslında basit ama gözden kaçabilen tespiti ve çözüm yolu var. Özet olarak önce kolon isimlerine bir göz atıp ilk başta göremediğimiz ara tuşlarını tespit ediyoruz ve bunları ikinci kodla düzeltiyoruz.

Kod:

data_train.columns

data_train = data_train.rename(columns={'ChargedOff_Amount ': 'ChargedOff_Amount',
                                        'Gross_Amount_Disbursed  ': 'Gross_Amount_Disbursed',
                                        'Borrower_Name ': 'Borrower_Name',
                                        'Classification_Code ': 'Classification_Code',
                                        'Jobs_Created ': 'Jobs_Created',
                                        'Year_Of_Commitment ': 'Year_Of_Commitment'
                                        })

Kaynak: stackoverflow - How to resolve AttributeError: 'DataFrame' object has no attribute

Converting numerical value to category

Sometimes we may need to numerical values (integers) to categorical values (object/strings) because there is no point in running a regression as if thesee numbers represent a mathematical value or have a ranking (such as sector codes in a bank loan data). Here's how it's done:

Code:

# There columns should not be integers, but objects.
# These are Primary_Loan_Digit and Code_Franchise
data_train['Primary_Loan_Digit'] = pd.Categorical(data_train.Primary_Loan_Digit)
data_train['Code_Franchise'] = pd.Categorical(data_train.Code_Franchise)
data_test['Primary_Loan_Digit'] = pd.Categorical(data_test.Primary_Loan_Digit)
data_test['Code_Franchise'] = pd.Categorical(data_test.Code_Franchise)
data_train.dtypes

Türkçe:

Sayısal veriyi kategorik veriye dönüştürmek

10 Aralık 2022 Cumartesi

Bir kolonun verilerini kırparak yeni kolon oluşturmak & kategori kolonunu sayı kolonuna çevirmek

Bir dataframe'de "Rs." ile başlayan bir para birimi karşıma çıktı. Rs. (hint rupisi) benim için önemsiz olduğundan bu ilk üç karakteri kırpmam lazım. Karakterleri kırpma işini şuradaki ilk satırla yapıyorum:

Ama karakterleri kırpmak string'i nümerik hale getirmek anlamına gelmiyor ve kolon bu nedenle kategorik değişken olarak görünüyor. Dolayısıyla bunu ayrıca sayısal değişken haline getirmem lazım.

Bunu da şu kodla yapıyorum. Dikkat edilmesi gereken kısım ".astype(float)" kısmı. Bunu yazmayınca hata veriyor. (ValueError: invalid literal for int () with base 10)

Böylece bu kısmı hallediyoruz. Bunun sayısal değişkene döndüğünü görmek için num_cols ve cat_cols belirleyici kodunu tekrar çalıştırıyorum.


Ve num_cols'u kontrol edip "Loan_Approved_Gross_New" kolonunun dönüştüğünü görüyorum.


Bir de tarih (date) kolonu string olarak girildiğinden, object türünde görünüyor. Bunu da ikinci satırdaki kodla "date" türüne çeviriyorum:


Kodlar:

data_train['Gross_Amount_Balance_New'] = data_train['Gross_Amount_Balance'].str[3:]

data_train['Date_Of_Disbursement_New'] = pd.to_datetime(data_train['Date_Of_Disbursement'])

data_train['Loan_Approved_Gross_New'] = data_train['Loan_Approved_Gross_New'].astype(float).astype(int)


# group cat and num cols
from sklearn.compose import make_column_selector as selector
num_cols_selector = selector(dtype_exclude=object)
cat_cols_selector = selector(dtype_include=object)
num_cols = num_cols_selector(data_train)
cat_cols = cat_cols_selector(data_train)
cat_cols=data_train.select_dtypes(include=['object']).columns
for column in cat_cols:
    print("For column:",column)
    print(data_train[column].unique())
    print('-'*50)

Kaynaklar:

StackOverflow - Pandas make new column from string slice of another column

String'i tarih türüne çevirme: SparkByExamples






17 Kasım 2022 Perşembe

Creating tables for model comparison

In this post, I will compile codes to compare different models' results. The post will hopefully lengthen as I add new ones..

Here is the first one comparing a decision tree, rf, and other tuned regressors:

The code creates this table:
Code:

models_test_comp_df = pd.concat(
    [
        dt_regressor_perf_test.T,
        regressor_perf_test.T,
        bagging_estimator_perf_test.T,
        dtree_tuned_regressor_perf_test.T,
        bagging_tuned_regressor_perf_test.T,
        rf_tuned_regressor_perf_test.T
    ],
    axis=1,
)
models_test_comp_df.columns = [
    "Decision tree regressor",
    "Random Forest regressor",
    "Bagging regressor",
    "Tuned Decision Tree regressor",
    "Tuned Bagging Tree regressor",
    "Tuned Random Forest Regressor"]
print("Test performance comparison:")
models_test_comp_df


A second code to retrieve a table for a similar comparison: (table not included this time)


# defining list of models you have trained
models = [lr, dtree, ridge_model, dtree_tuned, rf_model, rf_model_tuned]
# defining empty lists to add train and test results
r2_train = []
r2_test = []
rmse_train= []
rmse_test= []
# looping through all the models to get the rmse and r2 scores
for model in models:
    # accuracy score
    j = get_model_score(model,False)
    r2_train.append(j[0])
    r2_test.append(j[1])
    rmse_train.append(j[2])
    rmse_test.append(j[3])
-------
comparison_frame = pd.DataFrame({'Model':['Linear Regression','Decision Tree','Ridge Model','Tuned Decision Tree','Random Forest','Tuned Random Forest'], 
                                          'Train_r2': r2_train,'Test_r2': r2_test,
                                          'Train_RMSE':rmse_train,'Test_RMSE':rmse_test}) 
comparison_frame