当前位置: 首页 > news >正文

机器学习-1:线性回归

常用的线性回归模型主要有以下这些

  • 简单线性回归
  • 多元线性回归
  • 多项式回归
  • 岭回归
  • 套索回归
  • 弹性网络回归
  • 逐步回归

 一.简单的一元线性回归

1.导入必备的库

#导入必备的库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split,cross_val_score
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score

 2.设置显示选项

# 设置显示选项
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
pd.set_option('display.max_rows', None)    #显示最大行数
pd.set_option('display.max_columns', None)  #显示最大列数
pd.set_option('display.max_colwidth', None)  #显示的最大列宽
pd.set_option('display.width', None)  #显示的最宽度

3.导入数据

data=pd.read_excel("汽车制造行业收入表.xlsx")
data=pd.DataFrame(data)
x=pd.DataFrame(data["工龄"])
y=pd.DataFrame(data["薪水"])

4.划分训练集和测试集

x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=42)

 变量名:

  • x_train: 训练集的特征数据。用于训练模型。

  • x_test: 测试集的特征数据。用于评估模型的性能。

  • y_train: 训练集的目标变量。与 x_train 对应,用于训练模型。

  • y_test: 测试集的目标变量。与 x_test 对应,用于评估模型的性能。

train_test_split 函数参数:

  • x: 输入特征数据。可以是 NumPy 数组、Pandas DataFrame 或其他可迭代的数据结构。

  • y: 目标变量。与 x 对应,表示要预测的值。

  • test_size=0.2: 指定测试集的比例。0.2 表示 20% 的数据将被分配到测试集,剩余 80% 的数据将被分配到训练集。

  • random_state=42: 随机种子,用于确保数据分割的可重复性。指定一个整数(如 42)可以使每次运行代码时,数据分割的结果相同。这对于调试和结果复现非常有用

5.数据预处理

根据数据情况进行数据的标准化/归一化/二值化

6.模型建立 

6.1创建线性回归模型:y=a*x+b

model = LinearRegression()

 6.2训练模型

model.fit(x_train, y_train)

 6.3输出线性回归系数

print("线性回归系数a:",model.coef_)
print("线性回归截距b:",model.intercept_)
线性回归系数a: [[1114.15442257]]
线性回归截距b: [7680.390625]

 6.4预测数据

y_test_pred= model.predict(x_test)

 6.5评估

mse = mean_squared_error(y_test, y_test_pred)
r2 = r2_score(y_test, y_test_pred)
rmse = np.sqrt(mse)
mae = np.mean(np.abs(y_test - y_test_pred))
# 计算调整后的R平方
n = len(y_test)
p = x_train.shape[1]
adjusted_r2 = 1 - (1 - r2) * (n - 1) / (n - p - 1)
cv_scores = cross_val_score(model, x, y, cv=5, scoring='r2')

 1. mse = mean_squared_error(y_test, y_test_pred)

  • 功能:计算测试集上的均方误差(Mean Squared Error, MSE)。

  • y_test: 测试集的真实目标值。

  • y_test_pred: 模型在测试集上的预测值。

  • MSE 越小,表示模型的预测值与实际值越接近

2. r2 = r2_score(y_test, y_test_pred)

  • 功能:计算测试集上的R平方(R2)得分。

  • y_test: 测试集的真实目标值。

  • y_test_pred: 模型在测试集上的预测值

  • R2 越接近1,表示模型越好

3.rmse = np.sqrt(mse)

  • 功能:计算均方误差的平方根。

  • RMSE 提供了与原始数据相同单位的误差度量,便于解释。与 MSE 类似,RMSE 越小,模型越好。

4.mae = np.mean(np.abs(y_test - y_test_pred))

  • 功能:计算测试集上预测值与实际值之间的平均绝对误差。

  • MAE 是预测值与实际值之间绝对差异的平均值,MAE 越小,表示模型的预测值与实际值越接近,MAE 对异常值不如 MSE 敏感

5.adjusted_r2 = 1 - (1 - r2) * (n - 1) / (n - p - 1)

  • 功能:计算调整后的 R2 值。

  • 调整后的 R2 在自变量数量较多时更为可靠,因为它惩罚了不必要的复杂性

6. cv_scores = cross_val_score(model, x, y, cv=5, scoring='r2')

  • 功能:使用5折交叉验证来评估模型的R平方得分。

  • model: 要评估的模型对象,例如 LinearRegression()。

  • x: 特征数据。

  • y: 目标变量。

  • cv=5: 使用5折交叉验证,将数据分成5个子集。

  • scoring='r2': 使用R平方作为评估指标。

  • 输出:cv_scores 是一个数组,包含每次交叉验证的R平方得分。

其中交叉验证的评估指标主要有以下几种

1. R平方(R2)

  • 范围:[−∞,1]

  • 𝑅2=1:表示模型完美拟合数据。

  • 𝑅2=0:表示模型没有解释任何方差,预测的效果与简单的均值预测相同。

  • 𝑅2<0:表示模型比简单的均值预测效果还差。

2. 均方误差(Mean Squared Error, MSE)

  • 范围:[0,∞)

  • MSE 越小,表示模型的预测值与实际值越接近。

  • MSE 为 0 表示模型预测完全准确。

3. 均方根误差(Root Mean Squared Error, RMSE)

  • 范围:[0,∞)

  • RMSE 是 MSE 的平方根,提供了与原始数据相同单位的误差度量。

  • RMSE 越小,表示模型的预测值与实际值越接近。

4. 平均绝对误差(Mean Absolute Error, MAE)

  • 范围:[0,∞)

  • MAE 越小,表示模型的预测值与实际值越接近。

  • MAE 为 0 表示模型预测完全准确。

5. 分类准确率(Accuracy)

  • 范围:[0,1]

  • 准确率为 1 表示模型预测完全准确。

  • 准确率为 0 表示模型预测完全错误。

6. F1分数(F1 Score)

  • 范围:[0,1]

  • F1 分数为 1 表示完美的精确率和召回率。

  • F1 分数为 0 表示模型没有正确预测任何正类样本。

对于回归问题,常用的指标包括 R2、MSE、RMSE 和 MAE;对于分类问题,常用的指标包括准确率和 F1 分数

5.7可视化

plt.scatter(x_train, y_train, color='blue', label='训练数据')
plt.scatter(x_test, y_test, color='green', label='测试数据')
plt.plot(x_test, y_test_pred, color='red', linewidth=2, label='预测数据')
plt.xlabel('工龄')
plt.ylabel('薪水')
plt.title('简单的线性回归')
plt.legend()
plt.show()

5.8代码汇总

#1.导入必备的库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split,cross_val_score
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
#2.设置显示选项
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
pd.set_option('display.max_rows', None)    #显示最大行数
pd.set_option('display.max_columns', None)  #显示最大列数
pd.set_option('display.max_colwidth', None)  #显示的最大列宽
pd.set_option('display.width', None)  #显示的最宽度
#3.导入数据
data=pd.read_excel("汽车制造行业收入表.xlsx")
data=pd.DataFrame(data)
x=pd.DataFrame(data["工龄"])
y=pd.DataFrame(data["薪水"])
#4.划分训练集与测试集
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=42)
#5数据预处理
#6.1创建线性回归模型
model = LinearRegression()
#6.2模型训练
model.fit(x_train, y_train)
#6.3输出回归数值
print("线性回归系数a:",model.coef_)
print("线性回归截距b:",model.intercept_)
#6.4预测数据
y_test_pred= model.predict(x_test)
#6.5模型评估
mse = mean_squared_error(y_test, y_test_pred)
r2 = r2_score(y_test, y_test_pred)
rmse = np.sqrt(mse)
mae = np.mean(np.abs(y_test - y_test_pred))
# 计算调整后的R平方
n = len(y_test)
p = x_train.shape[1]
adjusted_r2 = 1 - (1 - r2) * (n - 1) / (n - p - 1)
cv_scores = cross_val_score(model, x, y, cv=5, scoring='r2')
# 输出结果
print("交叉验证评估:", cv_scores)#用于评估模型的泛化能力和稳定性
print("平均交叉验证:", np.mean(cv_scores))
print("均方误差:", mse)#它表示预测值与实际值之间误差的平方的平均值
print("决定系数:", r2)
print("均方根误差 (RMSE):", rmse)
print("平均绝对误差 (MAE):", mae)
print("调整后的R^2:", adjusted_r2)
# 数据可视化
plt.scatter(x_train, y_train, color='blue', label='训练数据')
plt.scatter(x_test, y_test, color='green', label='测试数据')
plt.plot(x_test, y_test_pred, color='red', linewidth=2, label='预测数据')
plt.xlabel('工龄')
plt.ylabel('薪水')
plt.title('简单的线性回归')
plt.legend()
plt.show()

二.多元线性回归:客户价值数据表

#1.导入必备的库
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import statsmodels.api as sm
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error as mse
from sklearn.preprocessing import StandardScaler
from scipy import stats
#2.显示设置
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
pd.set_option('display.max_rows', None)    #显示最大行数
pd.set_option('display.max_columns', None)  #显示最大列数
pd.set_option('display.max_colwidth', None)  #显示的最大列宽
pd.set_option('display.width', None)  #显示的最宽度
#3.数据导入
data=pd.read_excel("客户价值数据表.xlsx")#4.数据预处理
#4.1使用均值填写缺失值
print("缺失值统计:\n",data.isnull().sum())
data = data.apply(lambda col: col.fillna(col.mean()), axis=0)#使用每一列的平均值填充
# print(data.head())
#4.2异常值处理
numeric_data = data.select_dtypes(include=[np.number])
z_scores = np.abs(stats.zscore(data.select_dtypes(include=[np.number])))  # 仅对数值型数据计算 Z-score
threshold = 3  # Z-score 阈值 3个标准差
outliers = (z_scores > threshold).any(axis=1)  # 检测异常值
print("检测到的异常值行索引:\n", data[outliers].index.tolist())  # 输出异常值的行索引
print(data[outliers])
data = data[~outliers]  # 移除异常值#4.3训练集与测试集的划分
x=data.drop(["客户价值"],axis=1)  #去掉"客户价值这一列"
y=data["客户价值"]
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=42)
#4.4创建标准化训练集与测试集
scaler = StandardScaler()
x_train = scaler.fit_transform(x_train)  # 对训练集进行标准化
x_test = scaler.transform(x_test)#5建立模型
#5.1建立线性回归模型(多元)
linear=LinearRegression()
#5.2模型训练
linear.fit(x_train,y_train)  #使用标准化后的数据进行模型训练
#5.3输出各项系数
print("线性回归的系数a是:",linear.coef_)  #
print("线性回归的截距b是:",linear.intercept_)
#5.4数据预测
y_pred=linear.predict(x_test)
#5.5模型评估
print("回归得分:",linear.score(x_test,y_test).__round__(2))  #保留两位小数
print("mse线性回归评估:",mse(y_test, y_pred).__round__(2))
#5.6可视化
plt.bar(range(len(linear.coef_)), linear.coef_)
plt.xlabel("特征")
plt.ylabel("系数")
plt.title("特征重要性")plt.show()
plt.figure(figsize=(10, 6))
plt.boxplot(numeric_data.values, tick_labels=numeric_data.columns)
plt.title("箱线图检测异常值")
plt.xticks(rotation=45)
plt.show()

三.多项式回归

适用于一元和多元的非线性关系

#1.导入必要的库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
from scipy import stats
#2.设置显示选项
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
pd.set_option('display.max_rows', None)    #显示最大行数
pd.set_option('display.max_columns', None)  #显示最大列数
pd.set_option('display.max_colwidth', None)  #显示的最大列宽
pd.set_option('display.width', None)  #显示的最宽度#3.读取数据
data=pd.read_excel("客户价值数据表.xlsx")#4.数据预处理
#4.1使用均值填写缺失值
print("缺失值统计:\n",data.isnull().sum())
data = data.apply(lambda col: col.fillna(col.mean()), axis=0)#使用每一列的平均值填充
# print(data.head())
#4.2异常值处理
numeric_data = data.select_dtypes(include=[np.number])
z_scores = np.abs(stats.zscore(data.select_dtypes(include=[np.number])))  # 仅对数值型数据计算 Z-score
threshold = 3  # Z-score 阈值 3个标准差
outliers = (z_scores > threshold).any(axis=1)  # 检测异常值
print("检测到的异常值行索引:\n", data[outliers].index.tolist())  # 输出异常值的行索引
print(data[outliers])
data = data[~outliers]  # 移除异常值
x=data.drop(["客户价值","性别"],axis=1)  #去掉"客户价值这一列"
y=data["客户价值"]
#4.3多项式特征转换
degree = 2
poly = PolynomialFeatures(degree=degree)
x_poly = poly.fit_transform(x)
#4.4划分训练集和测试集
x_train, x_test, y_train, y_test = train_test_split(x_poly, y, test_size=0.2, random_state=42)
#4.5标准化训练集与测试集
scaler = StandardScaler()
x_train = scaler.fit_transform(x_train)  # 对训练集进行标准化
x_test = scaler.transform(x_test)#5模型建立
#5.1建立多项式回归模型
model = LinearRegression()
#5.2训练模型
model.fit(x_train, y_train)
#5.3输出模型参数
print("模型系数(权重):", model.coef_)
print("模型截距:", model.intercept_)
#5.4预测
y_pred = model.predict(x_test)
#5.5模型评估(计算均方误差(MSE)和 R² 得分)
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print("均方误差 (MSE):", mse)
print("R² 得分:", r2)

四.岭回归

1.使用L2正则化

正则化(Regularization)是一种用于防止机器学习模型过拟合的技术。

过拟合是指模型在训练集上表现很好,但在测试集上表现较差

# 1. 导入必要的库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.metrics import mean_squared_error, r2_score
from scipy import stats
# 2. 设置显示选项
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
pd.set_option('display.max_rows', None)    # 显示最大行数
pd.set_option('display.max_columns', None)  # 显示最大列数
pd.set_option('display.max_colwidth', None)  # 显示的最大列宽
pd.set_option('display.width', None)  # 显示的最宽度# 3. 读取数据
data=pd.read_excel("客户价值数据表.xlsx")# 4. 数据预处理
#4.1使用均值填写缺失值
print("缺失值统计:\n",data.isnull().sum())
data = data.apply(lambda col: col.fillna(col.mean()), axis=0)#使用每一列的平均值填充
# print(data.head())
#4.2异常值处理
numeric_data = data.select_dtypes(include=[np.number])
z_scores = np.abs(stats.zscore(data.select_dtypes(include=[np.number])))  # 仅对数值型数据计算 Z-score
threshold = 3  # Z-score 阈值 3个标准差
outliers = (z_scores > threshold).any(axis=1)  # 检测异常值
print("检测到的异常值行索引:\n", data[outliers].index.tolist())  # 输出异常值的行索引
print(data[outliers])
data = data[~outliers]  # 移除异常值
x=data.drop(["客户价值"],axis=1)  #去掉"客户价值这一列"
y=data["客户价值"]
# 4.3 将数据分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)
# 4.4 标准化
scaler = StandardScaler()
x_train = scaler.fit_transform(X_train)  # 对训练集进行标准化
x_test = scaler.transform(X_test)# 5. 建立模型
# 5.1 定义参数网格
param_grid = {'alpha': np.logspace(-4, 4, 100)}  # 从 0.0001 到 10000 的 100 个值
# 5.2 使用 GridSearchCV 寻找最佳 alpha
ridge = Ridge()
grid_search = GridSearchCV(ridge, param_grid, cv=5, scoring='neg_mean_squared_error')
grid_search.fit(X_train, y_train)
# 5.3 输出最佳参数和对应的模型
best_alpha = grid_search.best_params_['alpha']
print("最佳 alpha:", best_alpha)
# 5.4 使用最佳 alpha 训练最终模型
ridge_best = Ridge(alpha=best_alpha)
ridge_best.fit(X_train, y_train)
# 5.5 预测
y_pred = ridge_best.predict(X_test)
# 5.6 模型评估
mse = mean_squared_error(y_test, y_pred)
print("Mean Squared Error:", mse)
# 6. 残差分析
residuals = y_test - y_pred
# 6.1 绘制残差图
plt.figure(figsize=(10, 6))
plt.scatter(y_pred, residuals)
plt.axhline(0, color='red', linestyle='--')
plt.xlabel("预测值")
plt.ylabel("残差")
plt.title("残差分析")
plt.show()
# 7. 计算 AIC 和 BIC
n = len(y_test)  # 样本数量
k = X_train.shape[1]  # 自变量数量
# 计算 AIC 和 BIC
aic = n * np.log(mse) + 2 * (k + 1)  # +1 是因为有截距项
bic = n * np.log(mse) + np.log(n) * (k + 1)
print("AIC:", aic)
print("BIC:", bic)
# 8. 计算调整后的 R²
r2 = r2_score(y_test, y_pred)
adjusted_r2 = 1 - (1 - r2) * (n - 1) / (n - k - 1)
print("调整后的 R²:", adjusted_r2)

五.套索回归 

使用L1正则化

# 1. 导入必要的库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LassoCV, Lasso
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
from scipy import stats
# 2. 设置显示选项
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
pd.set_option('display.max_rows', None)    # 显示最大行数
pd.set_option('display.max_columns', None)  # 显示最大列数
pd.set_option('display.max_colwidth', None)  # 显示的最大列宽
pd.set_option('display.width', None)  # 显示的最宽度# 3. 读取数据
data=pd.read_excel("客户价值数据表.xlsx")# 4. 数据预处理
#4.1使用均值填写缺失值
print("缺失值统计:\n",data.isnull().sum())
data = data.apply(lambda col: col.fillna(col.mean()), axis=0)#使用每一列的平均值填充
# print(data.head())
#4.2异常值处理
numeric_data = data.select_dtypes(include=[np.number])
z_scores = np.abs(stats.zscore(data.select_dtypes(include=[np.number])))  # 仅对数值型数据计算 Z-score
threshold = 3  # Z-score 阈值 3个标准差
outliers = (z_scores > threshold).any(axis=1)  # 检测异常值
print("检测到的异常值行索引:\n", data[outliers].index.tolist())  # 输出异常值的行索引
print(data[outliers])
data = data[~outliers]  # 移除异常值
x=data.drop(["客户价值"],axis=1)  #去掉"客户价值这一列"
y=data["客户价值"]
# 4.3 将数据分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)
#4.4创建标准化训练集与测试集
scaler = StandardScaler()
x_train = scaler.fit_transform(X_train)  # 对训练集进行标准化
x_test = scaler.transform(X_test)# 5. 建立模型
# 5.1 使用 LassoCV 寻找最佳 alpha
lasso_cv = LassoCV(alphas=np.logspace(-4, 4, 100), cv=5)  # 100 个 alpha 值,5 折交叉验证
lasso_cv.fit(X_train, y_train)
# 5.2 输出最佳参数和对应的模型
best_alpha = lasso_cv.alpha_
print("最佳 alpha:", best_alpha)
# 5.3 使用最佳 alpha 训练最终模型
lasso_best = Lasso(alpha=best_alpha)
lasso_best.fit(X_train, y_train)
# 5.4 预测
y_pred = lasso_best.predict(X_test)
# 5.5 模型评估
mse = mean_squared_error(y_test, y_pred)
print("Mean Squared Error:", mse)
# 5.6 输出模型系数
print("Coefficients:", lasso_best.coef_)
print("Intercept:", lasso_best.intercept_)
# 6. 计算 AIC 和 BIC
n = len(y_test)  # 样本数量
k = np.sum(lasso_best.coef_ != 0)  # 非零系数的数量
# 计算 AIC 和 BIC
aic = n * np.log(mse) + 2 * (k + 1)  # +1 是因为有截距项
bic = n * np.log(mse) + np.log(n) * (k + 1)
print("AIC:", aic)
print("BIC:", bic)
# 7. 计算调整后的 R²
r2 = r2_score(y_test, y_pred)
adjusted_r2 = 1 - (1 - r2) * (n - 1) / (n - k - 1)
print("调整后的 R²:", adjusted_r2)
# 8. 残差分析
residuals = y_test - y_pred
# 8.1 绘制残差图
plt.figure(figsize=(10, 6))
plt.scatter(y_pred, residuals)
plt.axhline(0, color='red', linestyle='--')
plt.xlabel("预测值")
plt.ylabel("残差")
plt.title("残差分析")
plt.show()

六.弹性网络回归

使用L1与L2正则化相结合

# 1. 导入必要的库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import ElasticNetCV, ElasticNet
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
from scipy import stats
# 2. 设置显示选项
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
pd.set_option('display.max_rows', None)    # 显示最大行数
pd.set_option('display.max_columns', None)  # 显示最大列数
pd.set_option('display.max_colwidth', None)  # 显示的最大列宽
pd.set_option('display.width', None)  # 显示的最宽度# 3. 读取数据
data=pd.read_excel("客户价值数据表.xlsx")# 4. 数据预处理
#4.1使用均值填写缺失值
print("缺失值统计:\n",data.isnull().sum())
data = data.apply(lambda col: col.fillna(col.mean()), axis=0)#使用每一列的平均值填充
# print(data.head())
#4.2异常值处理
numeric_data = data.select_dtypes(include=[np.number])
z_scores = np.abs(stats.zscore(data.select_dtypes(include=[np.number])))  # 仅对数值型数据计算 Z-score
threshold = 3  # Z-score 阈值 3个标准差
outliers = (z_scores > threshold).any(axis=1)  # 检测异常值
print("检测到的异常值行索引:\n", data[outliers].index.tolist())  # 输出异常值的行索引
print(data[outliers])
data = data[~outliers]  # 移除异常值
x=data.drop(["客户价值"],axis=1)  #去掉"客户价值这一列"
y=data["客户价值"]
# 4.3 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)
#4.4创建标准化训练集与测试集
scaler = StandardScaler()
x_train = scaler.fit_transform(X_train)  # 对训练集进行标准化
x_test = scaler.transform(X_test)# 5. 建立模型
# 5.1 使用 ElasticNetCV 寻找最佳 alpha 和 l1_ratio
alphas = np.logspace(-4, 4, 100)  # 100 个 alpha 值
l1_ratios = np.linspace(0.1, 1, 10)  # 10 个 l1_ratio 值,确保大于 0
model_cv = ElasticNetCV(alphas=alphas, l1_ratio=l1_ratios, cv=5, random_state=42, max_iter=5000, tol=1e-5)
model_cv.fit(X_train, y_train)# 5.2 输出最佳参数和对应的模型
best_alpha = model_cv.alpha_
best_l1_ratio = model_cv.l1_ratio_
print("最佳 alpha:", best_alpha)
print("最佳 l1_ratio:", best_l1_ratio)# 5.3 使用最佳参数训练最终模型
model = ElasticNet(alpha=best_alpha, l1_ratio=best_l1_ratio, random_state=42)
model.fit(X_train, y_train)# 5.4 预测
y_pred = model.predict(X_test)# 5.5 评估
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print("均方误差 (MSE):", mse)
print("R² 得分:", r2)# 6. 可视化
# 绘制系数
plt.figure(figsize=(10, 6))
plt.bar(range(len(model.coef_)), model.coef_)
plt.xlabel("特征")
plt.ylabel("系数")
plt.title("弹性网络回归系数")
plt.show()
# 8. 残差分析
residuals = y_test - y_pred# 8.1 绘制残差图
plt.figure(figsize=(10, 6))
plt.scatter(y_pred, residuals)
plt.axhline(0, color='red', linestyle='--')
plt.xlabel("预测值")
plt.ylabel("残差")
plt.title("残差分析")
plt.show()
# 8.2 绘制残差的直方图
plt.figure(figsize=(10, 6))
plt.hist(residuals, bins=30, edgecolor='k')
plt.xlabel("残差")
plt.ylabel("频率")
plt.title("残差的直方图")
plt.show()
# 8.3 绘制 Q-Q 图
import scipy.stats as stats
plt.figure(figsize=(10, 6))
stats.probplot(residuals, dist="norm", plot=plt)
plt.title("Q-Q 图")
plt.show()

特征工程1

#1.导入必备的库
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from statsmodels.stats.outliers_influence import variance_inflation_factor
from sklearn.feature_selection import mutual_info_regression
#2.显示选项
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False"""
1.皮尔逊相关系数:用于衡量两个连续变量之间的线性关系,值范围在 -1 到 1 之间。
值接近 1 表示强正相关,接近 -1 表示强负相关,接近 0 表示无相关性。   
2.斯皮尔曼等级相关系数:用于衡量两个变量之间的单调关系,适用于非正态分布的数据。
3.肯德尔相关系数:另一种用于衡量两个变量之间的相关性的方法,适用于小样本数据。
"""
df=pd.read_excel("客户价值数据表.xlsx")
pearson = df.corr(method='pearson')  # 计算皮尔逊相关系数
spearman =df.corr(method='spearman') # 计算斯皮尔曼等级相关系数
kendall = df.corr(method='kendall')  # 计算肯德尔相关系数
correlation_matrices = [pearson, spearman, kendall]
names = ["pearson", "spearman", "kendall"]
# 遍历列表并绘制热力图
for matrix, name in zip(correlation_matrices, names):plt.figure(figsize=(10, 8))sns.heatmap(matrix, annot=True, fmt=".2f", cmap='coolwarm')plt.title(f"{name}相关性矩阵")plt.show()#2.VIF 用于检测多重共线性,计算每个特征与其他特征的相关性。VIF 值越高,表示该特征与其他特征的相关性越强,通常 VIF > 10 被认为存在严重的多重共线性
# 计算 VIF
X = df.drop('客户价值', axis=1)  # 特征
vif = pd.DataFrame()
vif['特征'] = X.columns
vif['VIF'] = [variance_inflation_factor(X.values, i) for i in range(X.shape[1])]
print(vif)# 互信息用于衡量两个变量之间的信息共享程度,适用于分类和连续变量。值越高,表示两个变量之间的相关性越强。
y=df["客户价值"]
mi = mutual_info_regression(X, y)
mi_scores = pd.Series(mi, index=X.columns)
print(mi_scores.sort_values(ascending=False))

特征选择方法:

一.逐步回归

#1.导入必要的库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.api as sm
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.preprocessing import StandardScaler#2.设置显示选项
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
pd.set_option('display.max_rows', None)    #显示最大行数
pd.set_option('display.max_columns', None)  #显示最大列数
pd.set_option('display.max_colwidth', None)  #显示的最大列宽
pd.set_option('display.width', None)  #显示的最宽度#3.导入数据
data=pd.read_excel("客户价值数据表.xlsx")
x=data.drop(["客户价值"],axis=1)  #去掉"客户价值这一列"
y=data["客户价值"]#4.数据预处理
#4.1标准化
scaler = StandardScaler()
x=scaler.fit_transform(x)
x=pd.DataFrame(x,columns=["历史贷款金额","贷款次数","学历","月收入","性别"])
#4.2划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)#5.建立模型
def stepwise_selection(X, y, initial_list=[], threshold_in=0.01, threshold_out=0.05, verbose=True):"""逐步回归特征选择:param X: 特征数据(DataFrame):param y: 目标变量(Series):param initial_list: 初始特征列表:param threshold_in: 添加特征的显著性阈值:param threshold_out: 删除特征的显著性阈值:param verbose: 是否打印过程:return: 最终选择的特征列表"""included = list(initial_list)while True:changed = False# 前向选择excluded = list(set(X.columns) - set(included))new_pval = pd.Series(index=excluded, dtype=float)for new_column in excluded:model = sm.OLS(y, sm.add_constant(pd.DataFrame(X[included + [new_column]]))).fit()new_pval[new_column] = model.pvalues[new_column]best_pval = new_pval.min()if best_pval < threshold_in:best_feature = new_pval.idxmin()included.append(best_feature)changed = Trueif verbose:print(f"Add {best_feature} with p-value {best_pval:.6f}")# 后向消除model = sm.OLS(y, sm.add_constant(pd.DataFrame(X[included]))).fit()pvalues = model.pvalues.iloc[1:]  # 忽略截距worst_pval = pvalues.max()if worst_pval > threshold_out:changed = Trueworst_feature = pvalues.idxmax()included.remove(worst_feature)if verbose:print(f"Remove {worst_feature} with p-value {worst_pval:.6f}")if not changed:breakreturn included# 运行逐步回归
selected_features = stepwise_selection(X_train, y_train)
# 输出最终选择的特征
print("最终选择的特征:", selected_features)

二.主成分分析

相关文章:

机器学习-1:线性回归

常用的线性回归模型主要有以下这些 简单线性回归多元线性回归多项式回归岭回归套索回归弹性网络回归逐步回归 一.简单的一元线性回归 1.导入必备的库 #导入必备的库 import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection …...

android 的抓包工具

charles 抓包工具 官网地址 nullCharles Web Debugging Proxy - Official Sitehttps://www.charlesproxy.com/使用手册一定记得看官网 SSL Certificates • Charles Web Debugging Proxy http请求&#xff1a; 1.启动代理&#xff1a; 2.设置设备端口 3.手机连接当前代理 …...

AJAX 与 ASP 的深入探讨

AJAX 与 ASP 的深入探讨 引言 随着互联网技术的飞速发展,Web应用程序的交互性和性能要求越来越高。AJAX(Asynchronous JavaScript and XML)和ASP(Active Server Pages)作为两种重要的Web开发技术,在提高Web应用程序性能和用户体验方面发挥着重要作用。本文将深入探讨AJ…...

Qt开发①Qt的概念+发展+优点+应用+使用

目录 1. Qt的概念和发展 1.1 Qt的概念 1.2 Qt 的发展史&#xff1a; 1.3 Qt 的版本 2. Qt 的优点和应用 2.1 Qt 的优点&#xff1a; 2.2 Qt 的应用场景 2.3 Qt 的应用案例 3. 搭建 Qt 开发环境 3.1 Qt 的开发工具 3.2 Qt SDK 的下载和安装 3.3 Qt 环境变量配置和使…...

函数调用过程的详细解析

目录 一、C语言示例代码 二、汇编代码分步解析&#xff08;x86架构&#xff09; 1. 调用前&#xff1a;参数压栈&#xff08;从右向左&#xff09; 2. 进入被调函数&#xff1a;保存栈帧 3. 执行函数逻辑 4. 恢复栈帧并返回 三、内存布局图示&#xff08;调用过程中栈的变…...

教师管理系统在职校中的应用与优势

随着信息技术的不断发展&#xff0c;教师管理系统在职校中的应用越来越广泛。这一系统通过集成教师信息、教学资源和日程安排等功能&#xff0c;为职校管理带来了诸多便利和优势。 教师管理系统能够显著提高管理效率。传统的人工管理方式往往繁琐且易出错&#xff0c;而教师管理…...

【系统架构设计师】虚拟机体系结构风格

目录 1. 说明2. 解释器体系结构风格3. 规则系统体系结构风格4. 例题4.1 例题1 1. 说明 1.p263。2.虚拟机体系结构风格的基本思想是人为构建一个运行环境&#xff0c;在这个环境之上&#xff0c;可以解析与运行自定义的一些语言&#xff0c;这样来增加架构的灵活性。3.虚拟机体…...

UE C++ UObject 功能的初步总结

一. Uboject的 1.垃圾回收:上篇文章介绍过 2.引用更新 1. 反射:之前的文章描述过的CDO&#xff0c;还有就是C与蓝图相互调用UFUCTION,UPROPERTY 2.序列化&#xff1a;编辑器的资产序列化到磁盘上&#xff0c;变为.uasset等格式的资产文件。所有的东西存在编辑器里&#xff…...

Django 美化使用ModelForm的输入框

在初次使用ModelForm时&#xff0c;我的html文件代码如下&#xff0c;主要内容是显示一个卡片式表单&#xff0c;通过循环遍历 form 对象动态生成表单字段 {% extends layout.html %}{% block content %} <div class"container"><div class"c1"&g…...

SQL在云计算中的新角色:重新定义数据分析

文章目录 1. 云计算与数据分析的融合2. SQL在云计算中的新角色3. 分布式SQL查询引擎4. SQL-on-Hadoop解决方案5. SQL与其他数据分析工具的集成6. 实时数据分析与SQL7. SQL在云数据仓库中的角色8. 安全性与隐私保护9. SQL的未来展望《SQL数据分析实战&#xff08;第2版&#xff…...

使用Redis实现分布式锁,基于原本单体系统进行业务改造

一、单体系统下&#xff0c;使用锁机制实现秒杀功能&#xff0c;并限制一人一单功能 1.流程图&#xff1a; 2.代码实现&#xff1a; Service public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderSe…...

用Python实现线性回归:从数学原理到代码实战

一、前言&#xff1a;为什么线性回归是AI必修课&#xff1f; 作为机器学习领域的"Hello World"&#xff0c;线性回归算法具有三大核心价值&#xff1a; 1️⃣ 理解监督学习的底层逻辑&#xff08;特征工程→模型训练→预测输出&#xff09; 2️⃣ 掌握梯度下降等优化…...

JS 链表

文章目录 链表题的一些总结两种链表定义set存储链表节点&#xff0c;存的是整个空间同时处理长短不一的两个链表处理方法 while(l1 || l2)处理方法 while(l1 & l2) dummyhead的使用 链表题的一些总结 两种链表定义 class class ListNode {val;next null;constructor(va…...

AI时代:架构师的困境与救赎

在GitHub Copilot生成完整函数、ChatGPT编写业务逻辑的今天&#xff0c;编程正经历着前所未有的范式变革。某在线教育平台的技术负责人曾向我展示&#xff1a;团队使用AI工具3个月后&#xff0c;年轻工程师在架构评审会上对Kafka消息队列的消费机制支支吾吾&#xff0c;却在IDE…...

1-10 github注册仓库

如何在github中注册一个仓库&#xff1f; 1.0 注册仓库 1-1 GitHub的账号注册教程_github注册-CSDN博客 2.0 删除仓库 1-2 从github中删除创建的仓库_github删除仓库-CSDN博客 3.0 创建仓库 1-3 【教程】GitHub新建仓库新手教程_github仓库-CSDN博客 4.0 github操作 1-4 1-9 克…...

JavaScript作用域与闭包

一 作用域 在JavaScript中&#xff0c;作用域&#xff08;Scope&#xff09;指的是变量和函数的可访问性范围。在JavaScript中&#xff0c;作用域有全局作用域和局部作用域之分。 全局作用域&#xff08;Global Scope&#xff09;&#xff1a;全局作用域指的是在代码中任何位置…...

docker容器部署jar应用导入文件时候报缺少字体错误解决

如题&#xff0c;在导入文件时候报错如下&#xff1a; Handler dispatch failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class sun.awt.X11FontManager 经查是缺少对应字体&#xff0c;解决办法有两张&#xff1a; 第一种&#xff1a;…...

lean4安装

目录 lean4安装windows 证明等比数列和函数函数 lean4安装windows lean4 windows一键安装(全网最简单的安装流程)_lean4安装-CSDN博客 证明等比数列和函数函数 import Mathlib.Data.Real.Basic -- 导入实数基础库 import Mathlib.Tactic.Simps.Basic -- 导入简化策略 im…...

HTML的入门

一、HTML HTML&#xff08;HyperText Markup Language&#xff0c;超文本标记语言&#xff09;是一种用来告知浏览器如何组织页面的标记语言。 超文本&#xff1a;就是超越了文本&#xff1b;HTML不仅仅可以用来显示文本(字符串、数字之类)&#xff0c;还可以显示视频、音频等…...

Jenkins 部署 之 Mac 一

Jenkins 部署 之 Mac 一 一.Jenkins 部署依赖 JDK 环境 查看 Mac JDK 环境&#xff0c;如果没有安装&#xff0c;先安装 打开终端输入命令:java -version Mac安装配置 JDK 二. 检查 HomeBrew 安装 检查 HomeBrew 是否安装&#xff0c;终端输入命令:brew -v Mac安装HomeB…...

matlab平面波展开法计算的二维声子晶体带隙

平面波展开法计算的二维声子晶体带隙&#xff0c;分别是正方与圆形散射体形成正方格子声子晶体&#xff0c;最后输出了能带图的数据&#xff0c;需要自己用画图软件画出来。 列表 平面波展开法计算二维声子晶体带隙/a2.m , 15823 平面波展开法计算二维声子晶体带隙/a4.m , 942…...

爬虫实战:利用代理ip爬取推特网站数据

引言 亮数据-网络IP代理及全网数据一站式服务商屡获殊荣的代理网络、强大的数据挖掘工具和现成可用的数据集。亮数据&#xff1a;网络数据平台领航者https://www.bright.cn/?promoRESIYEAR50/?utm_sourcebrand&utm_campaignbrnd-mkt_cn_csdn_yingjie202502 在跨境电商、社…...

【kafka系列】生产者

目录 发送流程 1. 流程逻辑分析 阶段一&#xff1a;主线程处理 阶段二&#xff1a;Sender 线程异步发送 核心设计思想 2. 流程 关键点总结 重要参数 一、核心必填参数 二、可靠性相关参数 三、性能优化参数 四、高级配置 五、安全性配置&#xff08;可选&#xff0…...

Kafka日志数据深度解析:从基础查看到高级操作全攻略

#作者&#xff1a;孙德新 文章目录 查看log日志文件(kafka-dump-log.sh)1、查看Log文件基本数据信息2、index文件健康性检查(--index-sanity-check)3、转储文件(--max-message-size)4、偏移量解码(--offsets-decoder)5、日志数据解析(--transaction-log-decoder)6、查询Log文件…...

单例模式、构造函数、左值右值

拷贝构造函数 简单的说就是——用一个对象构造另外一个对象 class Myclass {public:int d0;Myclass(int d_){d d_}; //常用的构造函数Myclass(Myclass c) //拷贝构造函数{d c.d;} }; //对比 class Myclass {public:int d0;Myclass(int d_){d d_}; //常用的构造函数Myclass…...

DeepSeek+即梦 做AI视频

DeepSeek做AI视频 制作流程第一步&#xff1a;DeepSeek 生成视频脚本和分镜 第二步&#xff1a;生成分镜图片绘画提示词第三步&#xff1a;生成分镜图片第四步&#xff1a;使用可灵 AI 工具&#xff0c;将生成的图片转成视频。第五步&#xff1a;剪映成短视频 DeepSeek 真的强&…...

「软件设计模式」建造者模式(Builder)

深入解析建造者模式&#xff1a;用C打造灵活对象构建流水线 引言&#xff1a;当对象构建遇上排列组合 在开发复杂业务系统时&#xff0c;你是否经常面对这样的类&#xff1a;它有20个成员变量&#xff0c;其中5个是必填项&#xff0c;15个是可选项。当用户需要创建豪华套餐A&…...

Android设备 网络安全检测

八、网络与安全机制 6.1 网络框架对比 volley&#xff1a; 功能 基于HttpUrlConnection;封装了UIL图片加载框架&#xff0c;支持图片加载;网络请求的排序、优先级处理缓存;多级别取消请求;Activity和生命周期的联动&#xff08;Activity结束生命周期同时取消所有网络请求 …...

安心联车辆管理系统的硬件架构详解

安心联车辆管理系统的硬件架构可分为车载设备和后端平台设备两大部分&#xff0c;以下是详细的硬件组成及功能说明&#xff1a; 一、车载设备 定位与通信模块 北斗/GPS双模定位模块&#xff1a;支持厘米级定位精度&#xff0c;兼容JT/T808、JT/T809等交通部标准协议&#xff0c…...

适用于iOS的应用商店优化(ASO)清单

面对App Store的激烈竞争&#xff0c;您想优化您的应用使其在竞争中脱颖而出&#xff0c;但又不知道应该从哪里开始。我们已经为您准备好了&#xff01;我们整理了一份适用于iOS的应用商店优化&#xff08;ASO&#xff09;检查清单&#xff0c;用以帮助您入门并提高您在App Sto…...

linux概念详解

用户守护进程 用户空间守护进程是一些在后台运行的长期服务程序&#xff0c;提供系统级服务。 下面举一些例子。 网络服务&#xff1a; 如sshd&#xff08;SSH服务&#xff09;、httpd&#xff08;HTTP服务&#xff09;。 sshd&#xff1a;sshd 守护进程会在后台运行&#x…...

嵌入式开发应该具备哪些编程思维?

目录 1、资源限制思维 2、实时性思维 3、硬件抽象思维 4、中断驱动思维 5、功耗优化思维 6、可靠性和容错思维 7、并发和同步思维 8、故障排除与调试思维 9、状态机思维 嵌入式开发与一般的软件开发不同&#xff0c;嵌入式系统通常受到资源&#xff08;内存、处理器、…...

MongoDB索引介绍

索引简述 索引是什么 索引在数据库技术体系中占据了非常重要的位置&#xff0c;其主要表现为一种目录式的数据结构&#xff0c;用来实现快速的数据查询。通常在实现上&#xff0c;索引是对数据库表(集合)中的某些字段进行抽取、排列之后&#xff0c;形成的一种非常易于遍历读取…...

编程速递-庆祝Delphi诞生30周年!

庆祝Delphi 30周年纪念是一个特别的时刻。 回到1995年&#xff0c;也就是30年前&#xff0c;在微软Windows和互联网时代的曙光初现之时&#xff0c;Borland Delphi的创建者们无法想象&#xff0c;当时使用Borland Delphi构建的应用程序至今仍在运行——为全世界数十亿人服务。…...

YOLOv11-ultralytics-8.3.67部分代码阅读笔记-tuner.py

tuner.py ultralytics\utils\tuner.py 目录 tuner.py 1.所需的库和模块 2.def run_ray_tune(model, space: dict None, grace_period: int 10, gpu_per_trial: int None, max_samples: int 10, **train_args,): 1.所需的库和模块 # Ultralytics &#x1f680; AGPL-…...

一文说清楚什么是Token以及项目中使用Token延伸的问题

首先可以参考我的往期文章&#xff0c;我这里说清楚了Cookie&#xff0c;Seesion&#xff0c;Token以及JWT是什么 其实Token你就可以理解成这是一个认证令牌就好了 详细分清Session&#xff0c;Cookie和Token之间的区别&#xff0c;以及JWT是什么东西_还分不清 cookie、sessi…...

VueRouter 实例

分析下列代码 const router new VueRouter({mode:history,routes }) 1.const router new VueRouter({ ... })用来创建一个 Vue Router 实例&#xff0c;用于管理 Vue.js 应用的路由。2.mode: history&#xff1a; 作用&#xff1a;启用 HTML5 History 模式&#xff0c;去除…...

【算法工程】解决linux下Aspose.slides提示No usable version of libssl found以及强化推理模型的短板

1. 背景 构建ubuntu镜像&#xff0c;然后使用Aspose.slides解析PPTX文档&#xff0c;发现一直提示“No usable version of libssl found”。 2. 尝试 使用deepseek R1、kimi1.5、chatgpt o3&#xff0c;并且都带上联网能力&#xff0c;居然还是没有一个能够真正解决&#xf…...

解析浏览器中JavaScript与Native交互原理:以WebGPU为例

引言 随着Web应用复杂度的提升&#xff0c;开发者对浏览器访问本地硬件能力的需求日益增长。然而&#xff0c;浏览器必须在开放性与安全性之间找到平衡——既不能放任JavaScript&#xff08;JS&#xff09;随意操作系统资源&#xff0c;又要为高性能计算、图形渲染等场景提供支…...

小火车理论

格助词...

深度学习框架探秘|Keras 应用案例解析以及 Keras vs TensorFlow vs PyTorch

引言 上一篇文章《深度学习框架探秘&#xff5c;Keras&#xff1a;深度学习的魔法钥匙》 我们初步学习了 Keras&#xff0c;包括它是什么、具备哪些优势&#xff08;简洁易用的 API、强大的兼容性、广泛的应用领域&#xff09;&#xff0c;以及基本使用方法。本文&#xff0c;…...

【01 背包】

01 背包解题思路&#xff1a; 有n件物品和一个最多能背重量为w 的背包。第i件物品的重量是weight[i]&#xff0c;得到的价值是value[i] 。每件物品只能用一次&#xff0c;求解将哪些物品装入背包里物品价值总和最大。 这是标准的背包问题&#xff0c;每一件物品其实只有两个状…...

算法10-二分查找算法

一、二分查找算法概念 二分查找&#xff08;Binary Search&#xff09;是一种高效的查找算法&#xff0c;适用于在有序数组中快速查找目标值。它的核心思想是通过不断缩小查找范围&#xff0c;将时间复杂度从线性查找的 O(n) 优化到 O(log n)。 二、二分查找的流程图 以下是二…...

变相提高大模型上下文长度-RAG文档压缩-3.优化map-reduce(reranker过滤+社区聚类)

我遇到的业务问题实际上是RAG需要处理很多同一对象的日常报告&#xff0c;不像常识类问题&#xff0c;它的相关Document更多而且更分散&#xff0c;日常报告代表数据库里有很多它的内容&#xff0c;而且对象可能只在段落中的几句话提及到。top-k数量受限于大模型长度&#xff0…...

算法11-分治算法

一、分治算法概念 分治算法&#xff08;Divide and Conquer&#xff09;是一种重要的算法设计思想&#xff0c;通过将问题分解为多个子问题&#xff0c;分别解决后再合并结果&#xff0c;从而解决原问题。分治算法的核心思想是“分而治之”&#xff0c;通常包含三个步骤&#…...

Golang internals

To be continued... time.Time golang的时区和神奇的time.Parse context.Context Go Context的踩坑经历 sync.Pool sync.Pool workflow in Go 1.12 new shared pools in Go 1.13 什么是cpu cache理解 Go 1.13 中 sync.Pool 的设计与实现Go: Understand the Design of Sync.Pool…...

Flask中获取请求参数的一些方式总结

在 Flask 中&#xff0c;可以从 request 对象中获取各种类型的参数。以下是全面整理的获取参数的方式及示例代码。 1. 获取 URL 查询参数&#xff08;Query String Parameters&#xff09; URL 中的查询参数通过 ?keyvalue&key2value2 的形式传递&#xff0c;使用 reques…...

vscode/cursor 写注释时候出现框框解决办法

一、问题描述 用vscode/cursor写注释出现如图的框框&#xff0c;看着十分难受&#xff0c;用pycharm就没有 二、解决办法 以下两种&#xff0c;哪个好用改那个 &#xff08;1&#xff09;Unicode Highlight:Ambiguous Characters Unicode Highlight:Ambiguous Characters &a…...

11-跳跃游戏

给你一个非负整数数组 nums &#xff0c;你最初位于数组的 第一个下标 。数组中的每个元素代表你在该位置可以跳跃的最大长度。 判断你是否能够到达最后一个下标&#xff0c;如果可以&#xff0c;返回 true &#xff1b;否则&#xff0c;返回 false 。 贪心算法思路分析 在遍…...

TestHubo基础教程-创建项目

TestHubo是一款国产开源一站式测试工具&#xff0c;涵盖功能测试、接口测试、性能测试&#xff0c;以及 Web 和 App 测试&#xff0c;可以满足不同类型项目的测试需求。本文将介绍如何快速创建第一个项目&#xff0c;以快速入门上手。 1、创建项目 在 TestHubo 中&#xff0c;…...