24/9/19 算法笔记 kaggle BankChurn数据分类

题目是要预测银行里什么样的客户会流失,流失的概率是多少

我这边先展示一下我写的二分类的算法

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report

# 读取训练集和测试集数据
train = pd.read_csv("C:\\Users\\91144\\Desktop\\kaggle比赛数据\\Bank Churn 数据集进行二元分类\\playground-series-s4e1\\train.csv")
test = pd.read_csv("C:\\Users\\91144\\Desktop\\kaggle比赛数据\\Bank Churn 数据集进行二元分类\\playground-series-s4e1\\test.csv")

# 删除不需要的列
data = train
data.drop(['id','CustomerId','Surname'],axis=1,inplace=True)

# 对分类变量进行独热编码
object_cols = data.select_dtypes(include=['object']).columns
dumm = pd.get_dummies(data, columns=object_cols, prefix_sep='')

# 数据缩放
data = dumm
data['CreditScore'] = (data['CreditScore'] - data['CreditScore'].min()) / (data['CreditScore'].max() - data['CreditScore'].min())
data['EstimatedSalary'] = (data['EstimatedSalary'] - data['EstimatedSalary'].min()) / (data['EstimatedSalary'].max() - data['EstimatedSalary'].min())

# 划分训练集和测试集
X = data.drop('Exited',axis=1)  # 特征集 X
y = data['Exited']    # 标签集 y
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)

# 使用逻辑回归模型进行训练和预测
LR = LogisticRegression()
LR.fit(X_train, y_train)
print('训练集准确率:\n', LR.score(X_train, y_train))
print('验证集准确率:\n', LR.score(X_test, y_test))

# 对测试集进行预测
data = test
data.drop(['id','CustomerId','Surname'],axis=1,inplace=True)
object_cols = data.select_dtypes(include=['object']).columns
dumm = pd.get_dummies(data, columns=object_cols, prefix_sep='')

# 数据缩放
data = dumm
data['CreditScore'] = (data['CreditScore'] - data['CreditScore'].min()) / (data['CreditScore'].max() - data['CreditScore'].min())
data['EstimatedSalary'] = (data['EstimatedSalary'] - data['EstimatedSalary'].min()) / (data['EstimatedSalary'].max() - data['EstimatedSalary'].min())

# 进行预测
y_pred = LR.predict(data)
print(y_pred)

# 将预测结果保存到CSV文件中
df = pd.read_csv("C:\\Users\\91144\\Desktop\\kaggle比赛数据\\Bank Churn 数据集进行二元分类\\playground-series-s4e1\\test.csv")
id = df['id']
result = pd.DataFrame({'id':id, 'Exited':y_pred})
result.to_csv('2combined_columns.csv', index=False)

但是我预测出来基本Exited全是0

这里我应该是特征处理做的太草率,或者是数据参数问题

跑了这么多分

然后加以了改进,我用到了管道,交叉验证

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report

# 读取训练集和测试集数据
train = pd.read_csv("C:\\Users\\91144\\Desktop\\kaggle比赛数据\\Bank Churn 数据集进行二元分类\\playground-series-s4e1\\train.csv")
test = pd.read_csv("C:\\Users\\91144\\Desktop\\kaggle比赛数据\\Bank Churn 数据集进行二元分类\\playground-series-s4e1\\test.csv")

# 删除不需要的列
train.drop(['id', 'CustomerId', 'Surname'], axis=1, inplace=True)
test.drop(['id', 'CustomerId', 'Surname'], axis=1, inplace=True)

# 定义特征和目标变量
X = train.drop('Exited', axis=1)
y = train['Exited']

# 划分训练集和验证集
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)

# 定义数值和分类特征
num_cols = ['CreditScore', 'Age', 'Balance', 'EstimatedSalary']
cat_cols = ['Geography', 'Gender', 'Tenure', 'NumOfProducts', 'HasCrCard', 'IsActiveMember']

# 创建预处理步骤
numeric_transformer = Pipeline(steps=[
    ('scaler', StandardScaler())
])

categorical_transformer = Pipeline(steps=[
    ('onehot', OneHotEncoder(handle_unknown='ignore'))
])

preprocessor = ColumnTransformer(
    transformers=[
        ('num', numeric_transformer, num_cols),
        ('cat', categorical_transformer, cat_cols)
    ])

# 创建逻辑回归模型的管道
model = Pipeline(steps=[
    ('preprocessor', preprocessor),
    ('classifier', LogisticRegression(max_iter=1000))
])
# 定义要尝试的参数网格
param_grid = {
    'classifier__C': [0.1, 1, 10],  # 逻辑回归的正则化强度
    'classifier__penalty': ['l1', 'l2']  # 正则化类型
}

# 创建 GridSearchCV 对象
grid_search = GridSearchCV(estimator=model, param_grid=param_grid, cv=5, scoring='accuracy', verbose=1)

# 训练模型
grid_search.fit(X_train, y_train)

# 获取最佳参数和最佳模型
best_params = grid_search.best_params_
best_model = grid_search.best_estimator_



# 训练模型
model.fit(X_train, y_train)

# 验证模型
y_val_pred = best_model.predict(X_val)
print('验证集准确率:', accuracy_score(y_val, y_val_pred))
print(confusion_matrix(y_val, y_val_pred))
print(classification_report(y_val, y_val_pred))

# 对测试集进行预测
test_predictions = best_model.predict(test)
test = pd.read_csv("C:\\Users\\91144\\Desktop\\kaggle比赛数据\\Bank Churn 数据集进行二元分类\\playground-series-s4e1\\test.csv")

# 将预测结果保存到CSV文件中
submission = pd.DataFrame({
    'id': test['id'],  # 如果需要保留 id 列
    'Exited': test_predictions
})
submission.to_csv('3catboost_submission.csv', index=False)
print("Submission file created: catboost_submission.csv")
  1. 数据预处理整合到管道中:通过使用 ColumnTransformerPipeline,将数据预处理步骤(包括数值特征的标准化和分类特征的独热编码)整合到了模型训练的管道中。这样做的好处是,预处理步骤和模型训练步骤可以一起执行,简化了代码,并且确保了训练集和测试集使用相同的预处理步骤。

  2. 使用 GridSearchCV 进行参数调优:这是一个重要的改进,因为模型的性能很大程度上取决于其参数的设置。

  3. 避免数据泄露:通过在管道中整合预处理步骤,您确保了测试集的预测是在与训练集相同的预处理步骤之后进行的,这有助于避免数据泄露。

  4. 模型参数调整:在 LogisticRegression 中设置了 max_iter=1000,这有助于确保收敛,特别是在处理较大的数据集时。

跑了这么多分

然后还有一大佬写的用GBM梯度提升来做的

导入库

# import libraries

# to handle the data
import pandas as pd
import numpy as np

# to visualize the dataset
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.graph_objects as go

# to preprocess the data
from sklearn.preprocessing import MinMaxScaler, LabelEncoder #用于将特征缩放到给定的最小值和最大值之间。#用于将标签编码为从0开始的连续整数

# machine learning
from sklearn.model_selection import StratifiedKFold
from sklearn.feature_extraction.text import TfidfVectorizer #用于将文本数据转换为TF-IDF特征向量。
from sklearn.decomposition import TruncatedSVD  #用于降维的奇异值分解(SVD)方法。
from sklearn.model_selection import cross_val_score

# model
import lightgbm as lgb
from catboost import CatBoostClassifier, Pool
import xgboost as xgb

# evaluation
from sklearn.metrics import roc_auc_score, accuracy_score

# max columns 
pd.set_option('display.max_columns', None)

# hide warnings
import warnings
warnings.filterwarnings('ignore')

数据

df_train = pd.read_csv("C:\\Users\\91144\\Desktop\\kaggle比赛数据\\Bank Churn 数据集进行二元分类\\playground-series-s4e1\\train.csv")
df_test = pd.read_csv("C:\\Users\\91144\\Desktop\\kaggle比赛数据\\Bank Churn 数据集进行二元分类\\playground-series-s4e1\\test.csv")

处理缺失值

#缺失值
train_null = df_train.isnull().sum().sum()
test_null = df_test.isnull().sum().sum()
print(f"Null count in Training Data: {train_null}")
print(f"Null count in Test Data: {test_null}")

处理重复值

#重复值
train_duplicate = df_train.drop("id",axis = 1).duplicated().sum()
test_duplicate = df_test.drop("id",axis = 1).duplicated().sum()
print(f"Duplicate count in Training Data: {train_duplicate}")
print(f"Duplicate count in Test Data: {test_duplicate}")
df_train.info()

df_train.describe().T

查看各个特征对流失率的影响

#目标变量是不平衡的,所以我们对这个不平衡的数据集使用分层交叉验证
fig, ax = plt.subplots(figsize=(9, 4))

# Create the count plot
sns.countplot(y="Exited", data=df_train, ax=ax, palette="deep")

# Customize the plot
ax.set_title("Distribution of Exited", fontsize=18, fontweight='semibold', pad=20)
ax.set_xlabel("Count", fontsize=14, labelpad=10)
ax.set_ylabel("Exited", fontsize=14, labelpad=10)

# Add value labels to the bars
for container in ax.containers:
    ax.bar_label(container, label_type='center', fontsize=12, padding=5, color='white', fontweight='bold')

plt.show()

# Create the figure and axes
fig, ax = plt.subplots(figsize=(9, 4))

# Create the count plot
sns.countplot(y="Gender", data=df_train, ax=ax, palette="deep")

# Customize the plot
ax.set_title("Distribution of Gender", fontsize=18, fontweight='semibold', pad=20)
ax.set_xlabel("Count", fontsize=14, labelpad=10)
ax.set_ylabel("Gender", fontsize=14, labelpad=10)

# Add value labels to the bars
for container in ax.containers:
    ax.bar_label(container, label_type='center', fontsize=12, padding=5, color='white', fontweight='bold')

plt.show()

# Create the figure and axes
fig, ax = plt.subplots(figsize=(9, 4))

# Create the count plot
sns.countplot(y="Tenure", data=df_train, ax=ax, palette="deep")

# Customize the plot
ax.set_title("Distribution of Tenure", fontsize=18, fontweight='semibold', pad=20)
ax.set_xlabel("Count", fontsize=14, labelpad=10)
ax.set_ylabel("Tenure", fontsize=14, labelpad=10)

# Add value labels to the bars
for container in ax.containers:
    ax.bar_label(container, label_type='edge', fontsize=10, padding=2, color='black', fontweight='normal')

# Adjust layout to prevent label cutoff
plt.tight_layout()

plt.show()

# Create the figure and axes
fig, ax = plt.subplots(figsize=(9, 4))

# Create the count plot
sns.countplot(y="NumOfProducts", data=df_train, ax=ax, palette="deep")

# Customize the plot
ax.set_title("Distribution of NumOfProducts", fontsize=18, fontweight='semibold', pad=20)
ax.set_xlabel("Count", fontsize=14, labelpad=10)
ax.set_ylabel("NumOfProducts", fontsize=14, labelpad=10)

# Add value labels to the bars
for container in ax.containers:
    ax.bar_label(container, label_type='edge', fontsize=10, padding=2, color='black', fontweight='normal')

# Adjust layout to prevent label cutoff
plt.tight_layout()

plt.show()

# Create the figure and axes
fig, ax = plt.subplots(figsize=(9, 4))

# Create the count plot
sns.countplot(y="HasCrCard", data=df_train, ax=ax, palette="deep")

# Customize the plot
ax.set_title("Distribution of HasCrCard", fontsize=18, fontweight='semibold', pad=20)
ax.set_xlabel("Count", fontsize=14, labelpad=10)
ax.set_ylabel("HasCrCard", fontsize=14, labelpad=10)

# Add value labels to the bars
for container in ax.containers:
    ax.bar_label(container, label_type='center', fontsize=12, padding=5, color='white', fontweight='bold')

plt.show()

# Create the figure and axes
fig, ax = plt.subplots(figsize=(9, 4))

# Create the count plot
sns.countplot(y="IsActiveMember", data=df_train, ax=ax, palette="deep")

# Customize the plot
ax.set_title("Distribution of IsActiveMember", fontsize=18, fontweight='semibold', pad=20)
ax.set_xlabel("Count", fontsize=14, labelpad=10)
ax.set_ylabel("IsActiveMember", fontsize=14, labelpad=10)

# Add value labels to the bars
for container in ax.containers:
    ax.bar_label(container, label_type='center', fontsize=12, padding=5, color='white', fontweight='bold')

plt.show()

cat_cols = ['Geography', 'Gender', 'Tenure', 'NumOfProducts', 'HasCrCard',
       'IsActiveMember']

target = 'Exited'

fig = plt.figure(figsize=(9, len(cat_cols)*1.8))

# background_color = 'grey'
for i, col in enumerate(cat_cols):
    
    plt.subplot(len(cat_cols)//2 + len(cat_cols) % 2, 2, i+1)
    sns.countplot(x=col, hue=target, data=df_train, palette='deep', color='#26090b', edgecolor='#26090b')
    plt.title(f"{col} countplot by target", fontweight = 'bold')
    plt.ylim(0, df_train[col].value_counts().max() + 10)
    
plt.tight_layout()
plt.show()

num_cols = ['CreditScore', 'Age', 'Balance', 'EstimatedSalary']
colors = ['#4e79a7', '#f28e2b', '#e15759', '#76b7b2']

fig, axes = plt.subplots(2, 2, figsize=(12, 10))
fig.suptitle("Distribution of Numerical Features", fontsize=20, fontweight='bold', y=1.02)

for i, column in enumerate(num_cols):
    ax = axes[i//2, i%2]
    sns.histplot(data=df_train, x=column, kde=True, bins=30, ax=ax, color=colors[i], edgecolor='white', linewidth=0.8)
    
    mean, median = df_train[column].mean(), df_train[column].median()
    ax.axvline(mean, color='red', linestyle='dashed', linewidth=2, label=f'Mean: {mean:.2f}')
    ax.axvline(median, color='blue', linestyle='dashed', linewidth=2, label=f'Median: {median:.2f}')

    ax.set_title(column, fontsize=16, pad=15)
    ax.set_xlabel(column, fontsize=14, labelpad=10)
    ax.set_ylabel('Frequency', fontsize=14, labelpad=10)
    ax.tick_params(axis='both', which='major', labelsize=12)
    ax.grid(True, linestyle='--', alpha=0.7)
    ax.set_axisbelow(True)
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.legend(fontsize=12)

plt.tight_layout()
fig.subplots_adjust(top=0.93, hspace=0.3, wspace=0.25)
plt.show()

palette_cmap = ["#6c9a76","#cc4b57","#764a23","#f25a29","#f7941d"]
df_corr = df_train.copy()

catcol = [col for col in df_corr.columns if df_corr[col].dtype == "object"]
le = LabelEncoder()
for col in catcol:
        df_corr[col] = le.fit_transform(df_corr[col])


plt.subplots(figsize =(10, 10))

sns.heatmap(df_corr.corr(), cmap = palette_cmap, square=True, cbar_kws=dict(shrink =.82), 
            annot=True, vmin=-1, vmax=1, linewidths=3,linecolor='#e0b583',annot_kws=dict(fontsize =8))
plt.title("Pearson Correlation Of Features\n", fontsize=25)
plt.xticks(rotation=90)
plt.yticks(rotation=0)
plt.show()

我们可以看到,年龄和人口流动之间有很强的正相关性,这意味着,当年龄越大,人口流动的可能性越大,这可以告诉我们,随着年龄的增长,人口流动的可能性越大。

此外,我们可以看到这次(产品数量和活跃成员)与退出概率之间的强烈负相关,这告诉我们,当一个人更活跃的时候,他们退出的概率是低的,也是当一个客户有更多的产品在银行,他们不太可能搅局。

由此我们可以看出,这两个变量在决定客户流失的可能性是非常重要的。

numeirc_cols = ['Age','CreditScore', 'Balance','EstimatedSalary']
#Use Loop Function
for col in numeirc_cols:
    sc = MinMaxScaler()
    df_train[col+"_scaled"] = sc.fit_transform(df_train[[col]])
    df_test[col+"_scaled"] = sc.fit_transform(df_test[[col]])

拼接 

df_train['Sur_Geo_Gend_Sal'] = df_train['CustomerId'].astype(str) + \
                               df_train['Surname'] + \
                               df_train['Geography'] + \
                               df_train['Gender'] + \
                               np.round(df_train['EstimatedSalary']).astype(str)

df_test['Sur_Geo_Gend_Sal'] = df_test['CustomerId'].astype(str) + \
                              df_test['Surname'] + \
                              df_test['Geography'] + \
                              df_test['Gender'] + \
                              np.round(df_test['EstimatedSalary']).astype(str)

 将文本数据转换为TF-IDF特征向量

def get_vectors(df_train,df_test,col_name):

    vectorizer = TfidfVectorizer(max_features=1000)
    vectors_train = vectorizer.fit_transform(df_train[col_name])
    vectors_test = vectorizer.transform(df_test[col_name])
    
    #用svd降维
    svd = TruncatedSVD(3)
    x_sv_train = svd.fit_transform(vectors_train)
    x_sv_test = svd.transform(vectors_test)

    #将数据转换为 pandas 的 DataFrame 结构
    tfidf_df_train = pd.DataFrame(x_sv_train)
    tfidf_df_test = pd.DataFrame(x_sv_test)

    #命名
    cols = [(col_name + "_tfidf_" + str(f)) for f in tfidf_df_train.columns.to_list()]
    tfidf_df_train.columns = cols
    tfidf_df_test.columns = cols

    #合并
    df_train = df_train.reset_index(drop=True)
    df_test = df_test.reset_index(drop=True)
    df_train = pd.concat([df_train, tfidf_df_train], axis="columns")
    df_test = pd.concat([df_test, tfidf_df_test], axis="columns")
    return df_train,df_test

 SVD降维通常用于文本挖掘(如TF-IDF矩阵降维)、图像处理、推荐系统等领域。然而,SVD也有一些局限性,比如计算复杂度较高,对于非常大的数据集可能不够高效。此外,SVD是一种线性降维方法,可能无法捕捉到数据中的所有非线性结构。在这些情况下,可以考虑使用其他降维技术,如主成分分析(PCA)或t-SNE。

df_train,df_test = get_vectors(df_train,df_test,'Surname')
df_train,df_test = get_vectors(df_train,df_test,'Sur_Geo_Gend_Sal')
df_train.head()

 将数据集中的某些列转换为新的特征,并对这些特征进行处理

def feature_data(df):
    
    df['Senior'] = df['Age'].apply(lambda x: 1 if x >= 60 else 0)
    df['Active_by_CreditCard'] = df['HasCrCard'] * df['IsActiveMember']
    df['Products_Per_Tenure'] =  df['Tenure'] / df['NumOfProducts']
    df['AgeCat'] = np.round(df.Age/20).astype('int').astype('category')
    
    cat_cols = ['Geography', 'Gender', 'NumOfProducts','AgeCat']    #onehotEncoding
    df=pd.get_dummies(df,columns=cat_cols)
    return df
#Genrating New Features
df_train = feature_data(df_train)
df_test = feature_data(df_test)

##Selecting Columns FOr use 
feat_cols=df_train.columns.drop(['id', 'CustomerId', 'Surname','Exited','Sur_Geo_Gend_Sal'])
feat_cols=feat_cols.drop(numeirc_cols)

#Printing
print(feat_cols)
df_train.head()

X=df_train[feat_cols]
y=df_train['Exited']
# LightGBM Parameters
lgbParams = {'n_estimators': 1000,
             'max_depth': 25, 
             'learning_rate': 0.025,
             'min_child_weight': 3.43,
             'min_child_samples': 216, 
             'subsample': 0.782,
             'subsample_freq': 4, 
             'colsample_bytree': 0.29, 
             'num_leaves': 21,
             'verbose':-1}

lgb_model = lgb.LGBMClassifier(**lgbParams)
lgb_cv_scores = cross_val_score(lgb_model, X, y, cv=10, scoring='roc_auc')

print("Cross-validation scores:", lgb_cv_scores)
print("Mean AUC:", lgb_cv_scores.mean())

 这段代码是使用Python的LightGBM库进行机器学习模型训练和交叉验证的例子。LightGBM是一个梯度提升框架,用于训练预测模型,它在处理大型数据集时非常高效。

lgb_model.fit(X,y)

test_predictions = lgb_model.predict_proba(df_test[feat_cols])[:, 1]

# Create a submission DataFrame
submission = pd.DataFrame({
    'id': df_test['id'],
    'Exited': test_predictions
})

# # Save the submission file
submission.to_csv('3submission.csv', index=False)
# Initialize CatBoostClassifier
cat_model = CatBoostClassifier(
    eval_metric='AUC',
    learning_rate=0.022,
    iterations=1000,
    verbose=False
)

# Perform cross-validation with StratifiedKFold
catboost_cv_scores = cross_val_score(cat_model, X, y, cv=5, scoring='roc_auc')

print("Cross-validation scores:", catboost_cv_scores)
print("Mean AUC:", catboost_cv_scores.mean())

#Cat_features
cat_features = np.where(X.dtypes != np.float64)[0]

# Train the model on the entire dataset
train_pool = Pool(X, y, cat_features=cat_features)
cat_model.fit(train_pool)

# Make predictions on the test set
test_pool = Pool(df_test[feat_cols], cat_features=cat_features)
test_predictions = cat_model.predict_proba(test_pool)[:, 1]

# Create submission DataFrame
submission = pd.DataFrame({
    'id': df_test['id'],
    'Exited': test_predictions
})

# Save the submission file
submission.to_csv('catboost_submission.csv', index=False)
print("Submission file created: catboost_submission.csv")
xgb_params = {
    'max_depth': 6,
    'learning_rate': 0.01,
    'n_estimators': 1000,
    'min_child_weight': 1,
    'subsample': 0.8,
    'colsample_bytree': 0.8,
    'gamma': 0,
    'objective': 'binary:logistic',
    'eval_metric': 'auc',
    'use_label_encoder': False,
    'nthread': -1,
    'random_state': 42
}

# Initialize XGBoost Classifier
xgb_model = xgb.XGBClassifier(**xgb_params)

# Perform cross-validation with StratifiedKFold
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
xgb_cv_scores = cross_val_score(xgb_model, X, y, cv=cv, scoring='roc_auc')

print("Cross-validation scores:", xgb_cv_scores)
print("Mean AUC:", xgb_cv_scores.mean())

classifiers = ['LightGBM', 'CatBoost', 'XGBoost']
auc_scores = [lgb_cv_scores.mean(), catboost_cv_scores.mean(), xgb_cv_scores.mean()]
# Create data for the plot
colors = ['#4e79a7', '#f28e2b', '#e15759']

# Create the figure with optimized settings
fig = go.Figure(data=[go.Bar(
    x=classifiers,
    y=auc_scores,
    name='AUC Score',
    marker_color=colors
)])

# Update layout with optimized settings
fig.update_layout(
    title='AUC Comparison',
    xaxis_title='Classifier',
    yaxis_title='AUC Score',
    template='plotly_white',
    font=dict(family="Arial", size=12),
    width=600,
    margin=dict(l=50, r=50, t=50, b=50)
)

# Add gridlines
fig.update_yaxes(showgrid=True, gridwidth=1, gridcolor='#E0E0E0')

# Show the plot
fig.show()

创建一个柱状图,用于比较不同分类器的 AUC 分数。 

# Selcting Best and Highest AUC_Score  from Above trained Models 

# Find the index of the maximum AUc_Score
best_accuracy_index = auc_scores.index(max(auc_scores))

# Print the best model for accuracy
print(f'Best Accuracy: {auc_scores[best_accuracy_index]:.4f} with Model: {classifiers[best_accuracy_index]}')
Best Accuracy: 0.8946 with Model: LightGBM

​​​​​​​

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/882088.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

60.【C语言】内存函数(memset,memcmp函数)

3.memset函数(常用) *简单使用 memset:memory set cplusplus的介绍 点我跳转 翻译: 函数 memset void * memset ( void * ptr, int value, size_t num ); 填充内存块 将ptr指向的内存块的前num个字节设置为指定值(解释为无符号char)。 (指针ptr类型为…

qt-C++笔记之作用等同的宏和关键字

qt-C笔记之作用等同的宏和关键字 code review! Q_SLOT 和 slots: Q_SLOT是slots的替代宏,用于声明槽函数。 Q_SIGNAL 和 signals: Q_SIGNAL类似于signals,用于声明信号。 Q_EMIT 和 emit: Q_EMIT 是 Qt 中用于发射…

【Linux】Linux的基本指令(1)

A clown is always a clown.💓💓💓 目录 ✨说在前面 🍋知识点一:Linux的背景 •🌰1.Unix发展的历史 •🌰2.Linux发展历史 •🌰3.企业应用现状 •🌰4.发行版本 &…

jmeter得到的文档数据处理

通过前面jmeter得到的输出文档,这里是txt文档,里面包含了很多条数据,每条数据的结构如下: 【request】 uuid:xxxxxxx timestamp:xxxxxxxx No.x question:xxxxxxx 【response】 code&#…

windows cuda12.1 pytorch gpu环境配置

安装cuda12.1 nvcc -V conda创建pythong3.10环境 conda create -n llama3_env python3.10 conda activate llama3_env 安装pytorch conda install pytorch torchvision torchaudio pytorch-cuda11.8 -c pytorch -c nvidia gpu - Pytorch version for cuda 12.2 - Stack Ov…

传输层 IV(TCP协议——流量控制、拥塞控制)【★★★★】

(★★)代表非常重要的知识点,(★)代表重要的知识点。 一、TCP 流量控制(★★) 1. 利用滑动窗口实现流量控制 一般说来,我们总是希望数据传输得更快一些。但如果发送方把数据发送得…

powerbi -L10-文件夹内的文件名

powerbi -L10-文件夹内的文件名 Folder.Contents letSource Folder.Contents("\\your_folder\ your_folder "),#"Removed Other Columns" Table.SelectColumns(Source,{"Name", "Date modified", "Folder Path"}), in#&q…

STM32篇:通用输入输出端口GPIO

一.什么是GPIO? 1.定义 GPIO是通用输入输出端口的简称,简单来说就是STM32可控制的引脚STM32芯片的GPIO引脚与 外部设备连接起来,从而实现与外部通讯、控制以及数据采集的功能。 简单来说我们可以控制GPIO引脚的电平变化,达到我们的各种目的…

MQ(RabbitMQ)笔记

初识MQ 同步调用优缺点 异步调用优缺点 总结: 时效性要求高,需要立刻得到结果进行处理--->同步调用 对调用结果不关心,对性能要求高,响应时间短--->异步调用

花园管理系统

基于springbootvue实现的花园管理系统 (源码L文ppt)4-074 4功能结构 为了更好的去理清本系统整体思路,对该系统以结构图的形式表达出来,设计实现该“花开富贵”花园管理系统的功能结构图如下所示: 图4-1 系统总体结…

植物大战僵尸【源代码分享+核心思路讲解】

植物大战僵尸已经正式完结,今天和大家分享一下,话不多说,直接上链接!!!(如果大家在运行这个游戏遇到了问题或者bug,那么请私我谢谢) 大家写的时候可以参考一下我的代码思…

Nginx反向代理出现502 Bad Gateway问题的解决方案

🎉 前言 前一阵子写了一篇“关于解决调用百度翻译API问题”的博客,近日在调用其他API时又遇到一些棘手的问题,于是写下这篇博客作为记录。 🎉 问题描述 在代理的遇到过很多错误码,其中出现频率最高的就是502&#x…

75、Python之函数式编程:生成器的核心方法及更多使用场景

引言 Python中的函数式编程,依托生成器,可以实现惰性求值的特性。但是,生成器其实还可以有更多的使用场景。本文就聚焦生成器,再次聊聊生成器中的主要方法以及更多的使用场景。 本文的主要内容有: 1、生成器的核心方…

解决DockerDesktop启动redis后采用PowerShell终端操作

如图: 在启动redis容器后,会计入以下界面 : 在进入执行界面后如图: 是否会觉得界面过于单调,于是想到使用PowerShell来操作。 步骤如下: 这样就能使用PowerShell愉快地敲命令了(颜值是第一生…

SVM原理

SVM 这里由于过了很长时间 博主当时因为兴趣了解了下 博主现在把以前的知识放到博客上 作为以前的学习的一个结束 这些东西来自其他资料上 小伙伴看不懂英文的自行去翻译下吧 博主就偷个懒了 多维空间和低维空间 不一样的分法,将数据映射到高维 &…

vue源码分析(九)—— 合并配置

文章目录 前言1.vue cli 创建一个基本的vue2 项目2.将mian.js文件改成如下3. 运行结果及其疑问? 一、使用 new Vue 创建过程的 2 种场景二、margeOption的详细说明1.margeOption的方法地址2.合并策略的具体使用3.defaultStrat 默认策略方法 三:以生命周期…

基于单片机的水位检测系统仿真

目录 一、主要功能 二、硬件资源 三、程序编程 四、实现现象 一、主要功能 基于STC89C52单片机,DHT11温湿度采集温湿度,滑动变阻器连接ADC0832数模转换器模拟水位传感器检测水位,通过LCD1602显示信息,然后在程序里设置好是否…

docker启动mysql未读取my.cnf配置文件问题

描述 在做mysql主从复制配置两台mysql时,从节点的my.cnf配置为: [mysqld] datadir /usr/local/mysql/slave1/data character-set-server utf8 lower-case-table-names 1 # 主从复制-从机配置# 从服务器唯一 ID server-id 2 # 启用中继日志 relay-l…

【编程底层原理】Java对象头的详细结构、锁机制及其优化技术,以及逃逸分析和JIT技术在性能优化中的作用

一、引言 在Java的多线程世界中,对象头和锁机制是确保数据一致性和程序性能的关键。本文将带你深入探索Java对象头的结构、锁机制的工作原理,以及逃逸分析和即时编译(JIT)技术如何助力性能优化。 二、Java对象头 1. 对象头的组…

6.数据库-数据库设计

6.数据库-数据库设计 文章目录 6.数据库-数据库设计一、设计数据库的步骤二、绘制E-R图三、关系模式第一范式 (1st NF)第二范式 (2nd NF)第三范式 (3nd NF)规范化和性能的关系 一、设计数据库的步骤 收集信息 与该系统有关人员进行交流、座谈,充分了解用户需求&am…