исправь ошибку. Напиши исправленный код полностью:
import pandas as pd
import numpy as np
from sklearn import preprocessing
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import seaborn as sns
from imblearn.over_sampling import SMOTE
import statsmodels.api as sm
from sklearn.feature_selection import RFE
from sklearn.metrics import confusion_matrix, classification_report, roc_auc_score, roc_curve

# Загрузка данных
data = pd.read_csv('banking.csv', header=0).dropna()
print(data.shape)
print(list(data.columns))
print(data['education'].unique())

# Группировка образования
data['education'] = np.where(data['education'].isin(['basic.4y', 'basic.6y', 'basic.9y']), 'Basic', data['education'])

# Автоматизированный анализ данных
print(data['y'].value_counts())
count_no_sub = len(data[data['y'] == 0])
count_sub = len(data[data['y'] == 1])
pct_of_no_sub = count_no_sub / (count_no_sub + count_sub)
pct_of_sub = count_sub / (count_no_sub + count_sub)
print("Percentage of no subscription is", pct_of_no_sub * 100)
print("Percentage of subscription", pct_of_sub * 100)
sns.countplot(x='y', data=data, palette='hls', hue='y', legend=False)
plt.show()

# Создание бинарных переменных
cat_vars = ['job', 'marital', 'education', 'default', 'housing', 'loan', 'contact', 'month', 'day_of_week', 'poutcome']
for var in cat_vars:
    cat_list = pd.get_dummies(data[var], prefix=var)
    data = data.join(cat_list)

# Итоговые переменные
cat_vars = ['job', 'marital', 'education', 'default', 'housing', 'loan', 'contact', 'month', 'day_of_week', 'poutcome']
data_vars = data.columns.values.tolist()
to_keep = [i for i in data_vars if i not in cat_vars]
data_final = data[to_keep]
print(data_final.columns.values)

# Балансировка датасета
X = data_final.loc[:, data_final.columns != 'y']
y = data_final.loc[:, data_final.columns == 'y']
os = SMOTE(random_state=0)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
columns = X_train.columns
os_data_X, os_data_y = os.fit_resample(X_train, y_train)
os_data_X = pd.DataFrame(data=os_data_X, columns=columns)
os_data_y = pd.DataFrame(data=os_data_y, columns=['y'])
print("Length of oversampled data is ", len(os_data_X))
print("Number of no subscription in oversampled data", len(os_data_y[os_data_y['y'] == 0]))
print("Number of subscription", len(os_data_y[os_data_y['y'] == 1]))
print("Proportion of no subscription data in oversampled data is ", len(os_data_y[os_data_y['y'] == 0]) / len(os_data_X))
print("Proportion of subscription data in oversampled data is ", len(os_data_y[os_data_y['y'] == 1]) / len(os_data_X))

# Создание модели логистической регрессии
logreg = LogisticRegression(max_iter=1000)

# Отбор значимых признаков
rfe = RFE(estimator=logreg, n_features_to_select=20, step=0.9999)
rfe.fit(os_data_X, os_data_y.values.ravel())

# Получение отобранных признаков
N = rfe.n_features_
print("Number of selected features: ", N)
sign_tokens = [X.columns[i] for i, val in enumerate(rfe.support_) if val]
print("Significant features: ", sign_tokens)


# Преобразование значимых признаков в 0 и 1
X = os_data_X[sign_tokens].replace(False, 0, inplace=False).replace(True, 1, inplace=False)
y = os_data_y['y']

# Построение логистической регрессии
logit_model = sm.Logit(y, X)
result = logit_model.fit()
print(result.summary2())

# Удаление лишних признаков
sign_tokens.remove('day_of_week_mon')
sign_tokens.remove('day_of_week_tue')
sign_tokens.remove('day_of_week_wed')
sign_tokens.remove('day_of_week_thu')
sign_tokens.remove('day_of_week_fri')

# Повторное построение модели
X = os_data_X[sign_tokens].replace(False, 0, inplace=False).replace(True, 1, inplace=False)
logit_model = sm.Logit(y, X)
result = logit_model.fit()
print(result.summary2())
# Обучение модели
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
logreg = LogisticRegression(max_iter=2000)  # Увеличение количества итераций
logreg.fit(X_train, y_train)

# Точность модели
y_pred = logreg.predict(X_test)
print('Accuracy of classifier on test set: {:.2f}'.format(logreg.score(X_test, y_test)))

# Матрица ошибок и отчет о классификации
conf_matrix = confusion_matrix(y_test, y_pred)
print(conf_matrix)
print(classification_report(y_test, y_pred))

# ROC-кривая
logit_roc_auc = roc_auc_score(y_test, logreg.predict(X_test))
fpr, tpr, thresholds = roc_curve(y_test, logreg.predict_proba(X_test)[:,1])
plt.figure()
plt.plot(fpr, tpr, label='Logistic Regression (area = %0.2f)' % logit_roc_auc)
plt.plot([0, 1], [0, 1],'r--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic')
plt.legend(loc="lower right")
plt.savefig('Log_ROC')
plt.show()

# Графики
pd.crosstab(data['job'], data['y']).plot(kind='bar')
plt.title('Frequency of Purchase for Job Title')
plt.xlabel('Job')
plt.ylabel('Frequency of Purchase')

pd.crosstab(data['marital'], data['y']).plot(kind='bar', stacked=True)
plt.title('Frequency of Purchase for Marital Status')
plt.xlabel('Marital Status')
plt.ylabel('Frequency of Purchase')

pd.crosstab(data['education'], data['y']).plot(kind='bar', stacked=True)
plt.title('Frequency of Purchase for Education Level')
plt.xlabel('Education Level')
plt.ylabel('Frequency of Purchase')

pd.crosstab(data['day_of_week'], data['y']).plot(kind='bar')
plt.title('Frequency of Purchase for Day of Week')
plt.xlabel('Day of Week')
plt.ylabel('Frequency of Purchase')

pd.crosstab(data['month'], data['y']).plot(kind='bar')
plt.title('Frequency of Purchase for Month')
plt.xlabel('Month')
plt.ylabel('Frequency of Purchase')

data['age'].hist()
plt.title('Frequency of Purchase for Age')
plt.xlabel('Age')
plt.ylabel('Frequency of Purchase')

pd.crosstab(data['poutcome'], data['y']).plot(kind='bar')
plt.title('Frequency of Purchase for Previous Marketing Campaign Outcome')
plt.xlabel('Previous Marketing Campaign Outcome')
plt.ylabel('Frequency of Purchase')

plt.show()
Вывод:
"C:\Program Files\Python310\python.exe" "C:\Users\polum\Downloads\Telegram Desktop\code.py" 
(41188, 21)
['age', 'job', 'marital', 'education', 'default', 'housing', 'loan', 'contact', 'month', 'day_of_week', 'duration', 'campaign', 'pdays', 'previous', 'poutcome', 'emp_var_rate', 'cons_price_idx', 'cons_conf_idx', 'euribor3m', 'nr_employed', 'y']
['basic.4y' 'unknown' 'university.degree' 'high.school' 'basic.9y'
 'professional.course' 'basic.6y' 'illiterate']
y
0    36548
1     4640
Name: count, dtype: int64
Percentage of no subscription is 88.73458288821988
Percentage of subscription 11.265417111780131
['age' 'duration' 'campaign' 'pdays' 'previous' 'emp_var_rate'
 'cons_price_idx' 'cons_conf_idx' 'euribor3m' 'nr_employed' 'y'
 'job_admin.' 'job_blue-collar' 'job_entrepreneur' 'job_housemaid'
 'job_management' 'job_retired' 'job_self-employed' 'job_services'
 'job_student' 'job_technician' 'job_unemployed' 'job_unknown'
 'marital_divorced' 'marital_married' 'marital_single' 'marital_unknown'
 'education_Basic' 'education_high.school' 'education_illiterate'
 'education_professional.course' 'education_university.degree'
 'education_unknown' 'default_no' 'default_unknown' 'default_yes'
 'housing_no' 'housing_unknown' 'housing_yes' 'loan_no' 'loan_unknown'
 'loan_yes' 'contact_cellular' 'contact_telephone' 'month_apr' 'month_aug'
 'month_dec' 'month_jul' 'month_jun' 'month_mar' 'month_may' 'month_nov'
 'month_oct' 'month_sep' 'day_of_week_fri' 'day_of_week_mon'
 'day_of_week_thu' 'day_of_week_tue' 'day_of_week_wed' 'poutcome_failure'
 'poutcome_nonexistent' 'poutcome_success']
Length of oversampled data is  51134
Number of no subscription in oversampled data 25567
Number of subscription 25567
Proportion of no subscription data in oversampled data is  0.5
Proportion of subscription data in oversampled data is  0.5
C:\Users\polum\AppData\Roaming\Python\Python310\site-packages\sklearn\linear_model\_logistic.py:469: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.

Increase the number of iterations (max_iter) or scale the data as shown in:
    https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
    https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
  n_iter_i = _check_optimize_result(
Number of selected features:  20
Significant features:  ['job_admin.', 'job_technician', 'marital_divorced', 'marital_married', 'marital_single', 'education_Basic', 'education_high.school', 'education_professional.course', 'education_university.degree', 'default_no', 'housing_no', 'housing_yes', 'loan_no', 'contact_cellular', 'month_mar', 'day_of_week_fri', 'day_of_week_mon', 'day_of_week_thu', 'day_of_week_tue', 'day_of_week_wed']
C:\Users\polum\Downloads\Telegram Desktop\code.py:76: FutureWarning: Downcasting behavior in `replace` is deprecated and will be removed in a future version. To retain the old behavior, explicitly call `result.infer_objects(copy=False)`. To opt-in to the future behavior, set `pd.set_option('future.no_silent_downcasting', True)`
  X = os_data_X[sign_tokens].replace(False, 0, inplace=False).replace(True, 1, inplace=False)
Optimization terminated successfully.
         Current function value: 0.537100
         Iterations 7
                                Results: Logit
==============================================================================
Model:                   Logit                Method:               MLE       
Dependent Variable:      y                    Pseudo R-squared:     0.225     
Date:                    2024-04-30 00:01     AIC:                  54968.1072
No. Observations:        51134                BIC:                  55144.9513
Df Model:                19                   Log-Likelihood:       -27464.   
Df Residuals:            51114                LL-Null:              -35443.   
Converged:               1.0000               LLR p-value:          0.0000    
No. Iterations:          7.0000               Scale:                1.0000    
------------------------------------------------------------------------------
                               Coef.  Std.Err.    z     P>|z|   [0.025  0.975]
------------------------------------------------------------------------------
job_admin.                     0.2421   0.0255   9.5106 0.0000  0.1922  0.2920
job_technician                -0.0182   0.0310  -0.5881 0.5565 -0.0789  0.0425
marital_divorced              -0.4519   0.0387 -11.6656 0.0000 -0.5279 -0.3760
marital_married               -0.9927   0.0360 -27.5973 0.0000 -1.0632 -0.9222
marital_single                -0.4431   0.0352 -12.5799 0.0000 -0.5122 -0.3741
education_Basic                0.3735   0.0324  11.5310 0.0000  0.3100  0.4369
education_high.school          0.6961   0.0330  21.0978 0.0000  0.6315  0.7608
education_professional.course  0.7721   0.0394  19.5925 0.0000  0.6949  0.8493
education_university.degree    0.8847   0.0340  26.0103 0.0000  0.8180  0.9513
default_no                    -1.2682   0.0298 -42.4867 0.0000 -1.3267 -1.2097
housing_no                     0.0750   0.0319   2.3521 0.0187  0.0125  0.1376
housing_yes                    0.0230   0.0329   0.7008 0.4834 -0.0414  0.0874
loan_no                       -1.8217   0.0314 -57.9767 0.0000 -1.8833 -1.7602
contact_cellular               0.1834   0.0253   7.2449 0.0000  0.1338  0.2330
month_mar                      2.1180   0.0793  26.7240 0.0000  1.9627  2.2733
day_of_week_fri                2.0240   0.0372  54.4609 0.0000  1.9511  2.0968
day_of_week_mon                1.8903   0.0368  51.4097 0.0000  1.8182  1.9623
day_of_week_thu                2.1917   0.0372  58.8964 0.0000  2.1188  2.2646
day_of_week_tue                2.0747   0.0373  55.6154 0.0000  2.0016  2.1478
day_of_week_wed                2.1740   0.0374  58.1721 0.0000  2.1008  2.2472
==============================================================================

C:\Users\polum\Downloads\Telegram Desktop\code.py:92: FutureWarning: Downcasting behavior in `replace` is deprecated and will be removed in a future version. To retain the old behavior, explicitly call `result.infer_objects(copy=False)`. To opt-in to the future behavior, set `pd.set_option('future.no_silent_downcasting', True)`
  X = os_data_X[sign_tokens].replace(False, 0, inplace=False).replace(True, 1, inplace=False)
Optimization terminated successfully.
         Current function value: 0.586122
         Iterations 7
                                Results: Logit
==============================================================================
Model:                   Logit                Method:               MLE       
Dependent Variable:      y                    Pseudo R-squared:     0.154     
Date:                    2024-04-30 00:01     AIC:                  59971.5583
No. Observations:        51134                BIC:                  60104.1914
Df Model:                14                   Log-Likelihood:       -29971.   
Df Residuals:            51119                LL-Null:              -35443.   
Converged:               1.0000               LLR p-value:          0.0000    
No. Iterations:          7.0000               Scale:                1.0000    
------------------------------------------------------------------------------
                               Coef.  Std.Err.    z     P>|z|   [0.025  0.975]
------------------------------------------------------------------------------
job_admin.                     0.3311   0.0239  13.8597 0.0000  0.2843  0.3780
job_technician                 0.0501   0.0290   1.7309 0.0835 -0.0066  0.1069
marital_divorced               0.1257   0.0346   3.6290 0.0003  0.0578  0.1936
marital_married               -0.2297   0.0309  -7.4418 0.0000 -0.2902 -0.1692
marital_single                 0.2154   0.0307   7.0046 0.0000  0.1551  0.2756
education_Basic                0.9781   0.0289  33.8289 0.0000  0.9214  1.0347
education_high.school          1.1931   0.0299  39.9599 0.0000  1.1346  1.2516
education_professional.course  1.2525   0.0359  34.8461 0.0000  1.1820  1.3229
education_university.degree    1.3865   0.0309  44.8338 0.0000  1.3259  1.4472
default_no                    -1.0204   0.0290 -35.2421 0.0000 -1.0771 -0.9636
housing_no                     0.6219   0.0282  22.0192 0.0000  0.5666  0.6773
housing_yes                    0.5788   0.0292  19.8555 0.0000  0.5217  0.6360
loan_no                       -1.6323   0.0310 -52.6452 0.0000 -1.6931 -1.5715
contact_cellular               0.3747   0.0241  15.5177 0.0000  0.3274  0.4220
month_mar                      2.1100   0.0771  27.3647 0.0000  1.9589  2.2611
==============================================================================

Accuracy of classifier on test set: 0.89
[[7617   49]
 [1570 6105]]
              precision    recall  f1-score   support

           0       0.83      0.99      0.90      7666
           1       0.99      0.80      0.88      7675

    accuracy                           0.89     15341
   macro avg       0.91      0.89      0.89     15341
weighted avg       0.91      0.89      0.89     15341


Process finished with exit code 0