线性回归

任务1. 一元线性回归

任务介绍:

  • 自定义一元回归函数MyLinearRegression(),输入参数为x和y的数组xArr和yArr,输出为参数w1和w0,利用最小二乘法求得参数;
  • 使用美国医疗保险费数据insurance.csv中的输入特征age和目标特征charges,输入MyLinearRegression()函数,得到回归参数值w1和w0,并保留到小数点后两位;
  • 调用sklearn的LinearRegression()函数,比较其运行结果与上述自定义函数MyLinearRegression()的输出结果是否一致。
  • 利用age与charges绘制真实样本点,利用w1与w0计算预测值,再绘制age与预测值的点图,观察真实样本点与预测点之间的拟合程度。

补全代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression

insurance = pd.read_csv('insurance.csv')
age = insurance['age'].values
charges = insurance['charges'].values

# 请在下方作答
# 定义一元线性回归函数
def MyLinearRegression(xArr, yArr):

# x均值, y均值计算
mean_x = xArr.mean()
mean_y = yArr.mean()

# w0, w1计算,公式
numerator = np.sum((xArr - mean_x) * (yArr - mean_y))
denominator = np.sum((xArr - mean_x)**2)
w1 = numerator / denominator
w0 = mean_y - w1 * mean_x

return round(w0,2), round(w1,2)

print("模型训练,得到参数值")
w0, w1 = MyLinearRegression(age, charges)
print(w1,'\n', w0)

print("sklearn的训练结果")
lr = LinearRegression()
#线性回归模型训练
lr.fit(age.reshape(-1, 1), charges)
print(round(lr.coef_[0],2))
print(round(lr.intercept_,2))

# 观察真实样本点与预测点之间的拟合程度
plt.scatter(age, charges, marker='.') # 画样本点,随机散点
# 利用w1与w0计算预测值,绘制预测点
plt.scatter(age, w1 * age + w0, marker='+') # 画预测点,形成直线
plt.show()

# 请直接运行处结果,然后提交作业,该运行结果会自动一同提交上去
模型训练,得到参数值
257.72 
 3165.89
sklearn的训练结果
257.72
3165.89

png

最小二乘法求解公式

目标:最小化预测值与真实值的平方误差之和:

闭式解(Normal Equation)

  1. 斜率 ( w_1 )

    其中 (\bar{x}) 和 (\bar{y}) 分别是 (x) 和 (y) 的均值。

  2. 截距 ( w_0 )

round(w0, 2) 和 round(w1, 2) 的作用是对线性回归模型的参数进行四舍五入处理,保留两位小数。

这段代码使用 scikit-learnLinearRegression 类实现线性回归,并输出模型参数。以下是逐行解释:

1. 创建线性回归模型实例

1
lr = LinearRegression()
  • LinearRegression()scikit-learn 中用于线性回归的类。
  • lr 是该类的一个实例,后续通过它调用模型训练、预测等方法。

    2. 模型训练

    1
    lr.fit(age.reshape(-1, 1), charges)
  • 作用:用输入数据 age(特征)和 charges(目标值)训练线性回归模型。
  • 关键细节
    • age 是一维数组(形状如 (n,)),但 scikit-learn 要求输入特征为二维数组(形状如 (n, 1))。
    • age.reshape(-1, 1) 将一维数组转换为二维列向量(n 行 1 列),确保输入格式正确。
    • charges 是目标值的一维数组,无需调整形状。

      3. 输出模型参数

      1
      2
      print(round(lr.coef_[0], 2))
      print(round(lr.intercept_, 2))
  • lr.coef_
    • 存储模型的回归系数(即 w1,特征权重)。
    • 对于一元线性回归,coef_ 是一个包含单个元素的数组(如 [w1]),因此用 coef_[0] 提取数值。
  • lr.intercept_
    • 存储模型的截距项(即 w0)。
    • 直接通过 intercept_ 访问,无需索引。
  • round(..., 2):将参数四舍五入保留两位小数,便于与自定义函数结果对比。

任务2. 多元线性回归

任务介绍:

  • 自定义多元线性回归函数MyLinearRegression2(),输入参数为X和y的数组xArr和yArr,输出为参数ws,利用最小二乘法求得参数;
  • 使用美国医疗保险费数据insurance.csv中的输入特征age、bmi和children,目标特征charges,根据MyLinearRegression2()函数,得到回归参数值ws;注意判断(X^T X)^{-1}是否为满秩,如果满秩,则引入正则项,参数为alpha,目标函数变为岭回归问题。
  • 为了得到模型的截距,需要在矩阵X最后增加一列,并且该列所有行的值均为1。
  • 调用sklearn的LinearRegression()函数,比较其运行结果与上述自定义函数MyLinearRegression2()的输出结果是否一致。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from sklearn.linear_model import LinearRegression
import numpy as np
from numpy import linalg, column_stack, ones, array
import pandas as pd
insurance = pd.read_csv('insurance.csv')

# 请在下方作答 #
# 定义多元线性回归函数
def MyLinearRegression2(xArr, yArr):

# 调用mat将Array转换为矩阵
xMat = np.asmatrix(xArr)
yMat = np.asmatrix(yArr).T # 转换为列向量
xTx = xMat.T*xMat
# 通过调用linalg计算行列式来判定协方差矩阵是否可逆
if linalg.det(xTx) < 1e-8:
print( "singular matrix, can't do inverse")
# 引入正则项,即 岭回归
alpha = 0.1
# 添加岭回归正则项(单位矩阵大小为特征数+1)
xTx += alpha * np.eye(xMat.shape[1])

# 计算参数向量
# 计算参数并转为一维数组
ws = xTx.I * (xMat.T * yMat)

return ws

# 模型训练,得到参数值
X = insurance[['age', 'bmi', 'children']].values
# 调用column_stack函数在矩阵X后增加一列,并且该列所有行的值均为1
# 添加截距列(全1)
X = column_stack((X, ones(X.shape[0])))
y = insurance['charges']
ws = MyLinearRegression2(X, y)
print("自定义的训练结果")
print(ws)
# sklearn的训练结果
lr = LinearRegression(fit_intercept=False) # 关键:禁用自动截距
#线性回归模型训练
lr.fit(X, y)
print("sklearn的训练结果")
print(lr.coef_)
print(lr.intercept_)

# 请直接运行处结果,然后提交作业,该运行结果会自动一同提交上去
自定义的训练结果
[[  239.99447429]
 [  332.0833645 ]
 [  542.86465225]
 [-6916.24334779]]
sklearn的训练结果
[  239.99447429   332.0833645    542.86465225 -6916.24334779]
0.0

任务3. 线性回归应用:预测医疗费用

任务介绍

  • 对insurance.csv中的名义型特征进行One-Hot编码,得到了数据变量insurance
  • 请使用自定义的多元回归函数MyLinearRegression2()得到回归模型参数ws和预测值y_pred,并计算R2分数
  • 比较使用sklearn进行模型训练和模型评价R2分数的结果

复用上一节实验中实现的代码,可以复制粘贴代替下面的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import pandas as pd
import numpy as np
from sklearn import linear_model, metrics
from numpy import array, mean, ones
import matplotlib.pyplot as plt

# 调用get_dummies函数对非数值型特征进行 one-hot 编码处理,以便于运算
insurance = pd.read_csv('insurance.csv')
insurance = pd.get_dummies(insurance, drop_first=True) # One-Hot编码
print(insurance.shape)

# 从insurance中获取X与y
X = insurance.drop(['charges'], axis=1).values.astype(np.float64)
y = insurance['charges'].values.astype(np.float64)

# 对每个特征与y的关系进行可视化,观察与y的相关性
plt.figure(figsize=(20,10))
for i in range(X.shape[1]):
plt.subplot(2,6,i+1)
plt.scatter(array(X)[:,i],y,s=20)
plt.show()

def MyLinearRegression2(xArr, yArr):

# 调用mat将Array转换为矩阵
xMat = np.asmatrix(xArr)
yMat = np.asmatrix(yArr).T # 转换为列向量
xTx = xMat.T*xMat
# 通过调用linalg计算行列式来判定协方差矩阵是否可逆
if np.linalg.det(xTx) < 1e-8:
print( "singular matrix, can't do inverse")
# 引入正则项,即 岭回归
alpha = 0.1
# 添加岭回归正则项(单位矩阵大小为特征数+1)
xTx += alpha * np.eye(xMat.shape[1])

# 计算参数向量
# 计算参数并转为一维数组
ws = xTx.I * (xMat.T * yMat)

return ws

# 根据X、y和自定义函数MyLinearRegression2()训练模型参数ws,并计算X的预测值y_pred
ws = MyLinearRegression2(X, y)
y_pred = X.dot(ws)
y_pred = array(y_pred).reshape(y_pred.shape[0],) # 将矩阵转换为一行多列的array格式

# 调用metrics中的r2_score函数根据y和y_pred计算决定系数score
score = metrics.r2_score(y, y_pred)

# sklearn模型训练与预测
lr = linear_model.LinearRegression(fit_intercept=False)
# 模型训练
lr.fit(X, y)
# 计算X的预测值y_pred_sk与R2分数score_sk
y_pred_sk = lr.predict(X) # 使用训练好的sklearn模型进行预测
score_sk = metrics.r2_score(y, y_pred_sk) # 计算决定系数R²
print(score_sk)

# 请直接运行处结果,然后提交作业,该运行结果会自动一同提交上去
(1338, 9)

png

0.7235368166092777
1

广告点击率预测

广告点击率(CTR)预测是广告行业的典型应用,是评估广告效果的一个非常重要的指标。通过历史数据训练预测模型,对于每天的增量数据进行预测,找出广告的CTR符合标准的样本进行投放。

数据集介绍

数据集来自于kaggle,数据包含了10天的Avazu的广告点击数据,训练集10000个,测试集1000个。每一条广告包含:广告id、时间、广告位置等属性。

任务1:导入库和数据集与数据预处理

  • 读入训练数据和测试数据,划分data和label
  • 将string类型的特征转化为int型:1)进行 one-hot 编码处理,会得到高维稀疏的特征,增大内存开销;2)使用python内置的hash函数将那些类型为object的特征变量映射为一定范围内的整数(原来的string被映射成了integer),可以大大降低内存的消耗。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import gzip
import pandas as pd
import random
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn import linear_model

types_train = {
'id': np.dtype(int),
'click': np.dtype(int), #是否点击,1表示被点击,0表示没被点击
'hour': np.dtype(int), #广告被展现的日期+时间
'C1': np.dtype(int), #匿名分类变量
'banner_pos': np.dtype(int), #广告位置
'site_id': np.dtype(str), #站点Id
'site_domain': np.dtype(str), #站点域名
'site_category': np.dtype(str), #站点分类
'app_id': np.dtype(str), # appId
'app_domain': np.dtype(str), # app域名
'app_category': np.dtype(str), # app分类
'device_id': np.dtype(str), #设备Id
'device_ip': np.dtype(str), #设备Ip
'device_model': np.dtype(str), #设备型号
'device_type': np.dtype(int), #设备型号
'device_conn_type': np.dtype(int),
'C14': np.dtype(int), #匿名分类变量
'C15': np.dtype(int), #匿名分类变量
'C16': np.dtype(int), #匿名分类变量
'C17': np.dtype(int), #匿名分类变量
'C18': np.dtype(int), #匿名分类变量
'C19': np.dtype(int), #匿名分类变量
'C20': np.dtype(int), #匿名分类变量
'C21':np.dtype(int) #匿名分类变量
}

# 添加列名
header_row = ['id', 'click', 'hour', 'C1', 'banner_pos', 'site_id', 'site_domain', 'site_category', \
'app_id', 'app_domain', 'app_category', 'device_id', 'device_ip', 'device_model',\
'device_type', 'device_conn_type', 'C14', 'C15', 'C16', 'C17', 'C18', 'C19',\
'C20', 'C21']

# 读入训练数据和测试数据
train = pd.read_csv('train_data.csv', names=header_row, dtype=types_train)
test = pd.read_csv('test_data.csv', names=header_row, dtype=types_train)
# 去除第0行(表示列的编号,不是样本)
train = train.drop(labels=train.index.values[0])
test = test.drop(labels=test.index.values[0])
print(test.shape)

# 划分data和label
train_data = train.drop('click', axis=1) #去除click 这一列
print(train_data.shape)
train_label = train['click'] #提取click 这一列

# 数据预处理
# 使用pd.get_dummies对非数值型特征进行 one-hot 编码处理,得到高维稀疏的特征
train_data1 = pd.get_dummies(train_data)
print(train_data1.shape)

# 编写convert_obj_to_int()函数将string类型的特征转换为int型
def convert_obj_to_int(self):
object_list_columns = self.columns
object_list_dtypes = self.dtypes
new_col_suffix = '_int'
for index in range(0, len(object_list_columns)):
if object_list_dtypes[index] == object:
# 使用hash和map将string特征变量映射为一定范围内的整数
self[object_list_columns[index] + new_col_suffix] = self[object_list_columns[index]].map(lambda x: hash(x) % (1 << 32))
self.drop([object_list_columns[index]], inplace=True, axis=1)
return self

# 调用convert_obj_to_int()函数,将string类型转换为int型
train_data = convert_obj_to_int(train_data)
print(train_data.shape)
(1000, 24)
(10000, 23)
(10000, 10531)
(10000, 23)


C:\Users\29020\AppData\Local\Temp\ipykernel_71456\1472409378.py:66: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
  if object_list_dtypes[index] == object:
C:\Users\29020\AppData\Local\Temp\ipykernel_71456\1472409378.py:66: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
  if object_list_dtypes[index] == object:
C:\Users\29020\AppData\Local\Temp\ipykernel_71456\1472409378.py:66: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
  if object_list_dtypes[index] == object:
C:\Users\29020\AppData\Local\Temp\ipykernel_71456\1472409378.py:66: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
  if object_list_dtypes[index] == object:
C:\Users\29020\AppData\Local\Temp\ipykernel_71456\1472409378.py:66: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
  if object_list_dtypes[index] == object:
C:\Users\29020\AppData\Local\Temp\ipykernel_71456\1472409378.py:66: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
  if object_list_dtypes[index] == object:
C:\Users\29020\AppData\Local\Temp\ipykernel_71456\1472409378.py:66: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
  if object_list_dtypes[index] == object:
C:\Users\29020\AppData\Local\Temp\ipykernel_71456\1472409378.py:66: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
  if object_list_dtypes[index] == object:
C:\Users\29020\AppData\Local\Temp\ipykernel_71456\1472409378.py:66: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
  if object_list_dtypes[index] == object:
C:\Users\29020\AppData\Local\Temp\ipykernel_71456\1472409378.py:66: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
  if object_list_dtypes[index] == object:

任务2:特征分析

以广告在网页中的位置(banner_pos)为例,查看banner_pos和最终类标(click)之间的关系。

  • 查看banner_pos在数据集中的取值分布;
  • 查看不同banner_pos对点击率click的贡献。
1
2
3
4
5
6
7
8
9
10
11
12
# 查看banner_pos在数据集中的取值分布
print(train.banner_pos.value_counts()/len(train))

# 查看不同banner_pos对点击率click的贡献
banner_pos_val = train.banner_pos.unique()
banner_pos_val.sort()
ctr_avg_list = []
for i in banner_pos_val:
selected_data = train.loc[train.banner_pos == i]
ctr_avg = selected_data.click.mean()
ctr_avg_list.append(ctr_avg)
print(" banner 位置: {}, 点击率: {}".format(i, ctr_avg))
banner_pos
0    0.8041
1    0.1951
2    0.0007
4    0.0001
Name: count, dtype: float64
 banner 位置: 0,  点击率: 0.16975500559631887
 banner 位置: 1,  点击率: 0.19067145053818554
 banner 位置: 2,  点击率: 0.14285714285714285
 banner 位置: 4,  点击率: 0.0

任务3:模型训练与评估

  • 调用sklearn的逻辑回归函数LogisticRegression(),进行模型训练
  • 对测试集test_data进行预测,计算预测结果的各项指标acc, pre, recall, auc
  • 绘制ROC曲线(使用预测的概率值而不是预测的类标)
  • 选做:自定义逻辑回归函数MyLogisticRegression(),进行模型训练与预测,与上述结果比较。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
test_data = test.drop('click', axis=1)
test_data = convert_obj_to_int(test_data)
test_label = test['click']
# 调用sklearn的逻辑回归函数LogisticRegression()
clf = linear_model.LogisticRegression(max_iter=1000) # 增加最大迭代次数防止不收敛

# 模型训练
clf.fit(train_data, train_label)
print("Finish Training!")

# 模型预测
pred = clf.predict(test_data)
pred_proba = clf.predict_proba(test_data)[:, 1]

# 计算模型的acc, pre, recall, auc,并输出
# 请在下方作答
acc = accuracy_score(test_label, pred)
pre = precision_score(test_label, pred)
recall = recall_score(test_label, pred)
auc = roc_auc_score(test_label, pred_proba)
print(f"Accuracy: {acc:.4f}, Precision: {pre:.4f}, Recall: {recall:.4f}, AUC: {auc:.4f}")
# 绘制roc曲线
# 请在下方作答
fpr, tpr, _ = roc_curve(test_label, pred_proba)
plt.figure(figsize=(8,6))
plt.plot(fpr, tpr, label=f'AUC = {auc:.4f}')
plt.plot([0,1], [0,1], 'k--')
plt.title('ROC Curve (sklearn)')
plt.legend()
plt.show()
# 自定义实现逻辑回归函数MyLogisticRegression()
# 请在下方作答

Finish Training!
Accuracy: 0.8120, Precision: 0.0000, Recall: 0.0000, AUC: 0.4983


C:\Users\29020\AppData\Local\Temp\ipykernel_71456\1472409378.py:66: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
  if object_list_dtypes[index] == object:
C:\Users\29020\AppData\Local\Temp\ipykernel_71456\1472409378.py:66: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
  if object_list_dtypes[index] == object:
C:\Users\29020\AppData\Local\Temp\ipykernel_71456\1472409378.py:66: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
  if object_list_dtypes[index] == object:
C:\Users\29020\AppData\Local\Temp\ipykernel_71456\1472409378.py:66: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
  if object_list_dtypes[index] == object:
C:\Users\29020\AppData\Local\Temp\ipykernel_71456\1472409378.py:66: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
  if object_list_dtypes[index] == object:
C:\Users\29020\AppData\Local\Temp\ipykernel_71456\1472409378.py:66: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
  if object_list_dtypes[index] == object:
C:\Users\29020\AppData\Local\Temp\ipykernel_71456\1472409378.py:66: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
  if object_list_dtypes[index] == object:
C:\Users\29020\AppData\Local\Temp\ipykernel_71456\1472409378.py:66: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
  if object_list_dtypes[index] == object:
C:\Users\29020\AppData\Local\Temp\ipykernel_71456\1472409378.py:66: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
  if object_list_dtypes[index] == object:
C:\Users\29020\AppData\Local\Temp\ipykernel_71456\1472409378.py:66: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
  if object_list_dtypes[index] == object:
f:\Anconda\Anconda\envs\general\Lib\site-packages\sklearn\metrics\_classification.py:1565: UndefinedMetricWarning: Precision is ill-defined and being set to 0.0 due to no predicted samples. Use `zero_division` parameter to control this behavior.
  _warn_prf(average, modifier, f"{metric.capitalize()} is", len(result))

png


Custom Model - Accuracy: 0.8240, Precision: 0.6875, Recall: 0.1170, AUC: 0.6580

png

正文

作业

什么是信息增益?根据下图分别计算按照属性A和B划分时的信息增益。ID3决策树学习算法将会选择哪个属性?

hw_h_82p6lenbyhkws867e413c0614d3

IMG_20250329_153252

IMG_20250329_153259

什么是交叉验证法?有什么用途?

IMG_20250329_153307

什么是过拟合(overfitting)?什么情况下可能发生过拟合?采取什么措施有助于消除过拟合?

IMG_20250329_153310

正文

极大似然估计

image-20250320200047048

image-20250320200109835

image-20250320200139754

作业

1、何为正则化?其功能是什么?如何理解L1和L2正则化?

IMG_20250320_170100

2、什么是偏差与方差?简要说明偏差、方差与过拟合、欠拟合的关系。

现象 偏差 方差 典型原因 解决方法
欠拟合 模型过于简单(如线性模型拟合非线性数据) 增加特征、使用更复杂模型、减少正则化
过拟合 模型过于复杂(如深度树模型拟合噪声) 增加数据、正则化、简化模型、早停法

IMG_20250320_181442

3、公式推导:最小二乘法、多元线性回归与岭回归、逻辑回归(极大似然法)

IMG_20250321_163937

IMG_20250321_163941

IMG_20250321_163944

IMG_20250321_163948

参考文献

“L1和L2正则化”直观理解(之一),从拉格朗日乘数法角度进行理解_哔哩哔哩_bilibili

超级棒的公式证明,对我帮助很大

https://www.bilibili.com/video/BV1Mh411e7VU?vd_source=bacf29bd4bb51f2ecf08a1ac7c7d8f11&p=3&spm_id_from=333.788.videopod.episodes

前言

好久不编算法了,为了不让300r打水漂,废话不多说,决战蓝桥杯!!!

我是算法彩笔,而且python也不是很会用,所有刷题刷的很慢,后续会把文件整理上传GitHub

思考了一下,因为时间紧迫,没有时间复盘每一道题了,这一篇文章简单记录一下进度

进度记录

3.13

贪心:1.力扣406. 根据身高重建队列2.P10387 [蓝桥杯 2024 省 A] 训练士兵3.蓝桥杯真题 谈判

3.14

贪心:1.蓝桥杯真题 翻硬币

bfs:1.蓝桥杯真题 扫雷2.蓝桥杯真题 长草3.力扣695.岛屿的最大面积

3.16

哈希:1.力扣 两数之和

前缀和:1.洛谷 求区间和

二分问题:1.洛谷 查找

dfs:1.蓝桥杯真题 小朋友崇拜圈2.蓝桥杯真题 最大数字

3.17

二分问题:1.力扣 统计公平数对的数目2.力扣 2226.每个小孩最多能分到多少糖果

3.18

二分答案:1.蓝桥杯真题 冶炼金属

并查集:1.洛谷P1551 亲戚2.洛谷P1536 村村通

3.19

哈希:1.力扣 3080.执行操作标记数组中的元素

堆:1.力扣 2530.执行k次操作后的最大分数

动态规划:1.力扣 70.爬楼梯2.力扣 198.打家劫舍3.P1048 [NOIP 2005 普及组] 采药4.力扣 494. 目标和5.力扣 322.零钱兑换

3.21

动态规划:1.力扣 2915.和为目标值的最长子序列的长度2.蓝桥杯真题 蓝桥课程抢购3.力扣518. 零钱兑换 II

图论:1.力扣1971.寻找图中是否存在路径

3.25

图论:1.力扣743.网络延迟时间

数论:1.蓝桥杯真题 数字诗意

3.26

贪心:1.蓝桥杯真题 回文数组

图论:1.力扣 1584.连接所有点的最小费用2.蓝桥杯真题 城市规划大师

3.27

动态规划:1.力扣1143.最长公共子序列2.蓝桥杯真题 查找最长公共子序列3.力扣583.两个字符串的删除操作

3.28

动态规划:1.蓝桥杯真题 砍柴

3.30

贪心:1.蓝桥杯真题 三国游戏2.蓝桥杯真题 平均

暴力:1.蓝桥杯真题 翻转

单调队列,单调栈:1.力扣239.滑动窗口最大值2.力扣739.每日温度3.力扣42.接雨水

双指针:1.力扣209.长度最小的子数组2.力扣3.无重复字符的最长字串3.力扣713.乘积小于k的子数组

3.31

二维单调队列:1.蓝桥杯真题 子矩阵(拼劲全力无法战胜,放弃)

4.1

数论:1.蓝桥杯真题 阶乘的和2.蓝桥杯真题 质因数个数

树:1.蓝桥杯真题 子树的大小

4.4

模拟:1.蓝桥杯真题 消除游戏

4.5

差分:1.蓝桥杯真题 重新排序2.力扣1094.拼车

动态规划:1.蓝桥杯真题 全排列的价值2.力扣300.最长递增子序列

贪心:1.蓝桥杯真题 优清零方案

4.9-11

刷填空题

4.12后记:也是考完蓝桥杯了,后面应该很长时间不碰算法了嘿嘿

正文

算法基础

快读模板

1
2
3
4
5
6
# 导入系统模块
import sys
# 重定义input函数,用于快速读取输入
# sys.stdin.readline() 比 python 自带的 input() 快
# strip() 用于去除行末的换行符
input = lambda:sys.stdin.readline().strip()

image-20250312124949702

输入

image-20250312130008507

列表推导器

image-20250312131643035

参考文献

竟然在b站刷到学长做的视频,太惊喜了,真是雪中送炭

【蓝桥杯】Python速成 刷题指南_哔哩哔哩_bilibili

代码模板 (Python) - Open Wiki Community

TsingPig/LanQiao_Python: 视频合集 https://space.bilibili.com/398421867/lists?sid=4898042&spm_id_from=333.788.0.0

补充资料 备注
https://wiki.dwj601.cn/ds-and-algo/templates-py/ 【★★★★★】Python代码模板
https://www.lanqiao.cn/problems/?first_category_id=1 蓝桥题库
https://ac.nowcoder.com/acm/problem/collection/6999 牛客蓝桥寒假题单
https://www.luogu.com.cn/training/list 洛谷题单
https://leetcode.cn/u/endlesscheng/ 力扣分类题单(进入点击“讨论发布”)
https://www.lanqiao.cn/paper/ 【★★★★★】蓝桥杯真题卷模拟系统
https://leetcode.cn/problemset/ 力扣题库

讲的很好的视频

分享|如何科学刷题?- 讨论 - 力扣(LeetCode)

安装git

Git是目前世界上最先进的分布式版本控制系统,没有之一!说到Git,另一个需要知道的便是GitHub,GitHub是目前使用最多的社交代码托管平台。

输入git —version 查看Git版本信息

配置本地信息
为了在后面上传项目到github时方便知道是谁上传的,需要给本机git配置用户名和邮箱:

git config —global user.name “zxj”
git config —global user.email “zxj2902065320@163.com”
查看配置命令:git config —list

配置SSH

ssh key生成命令ssh-keygen -t rsa -C “注册邮箱”

获取ssh key公钥内容(id_rsa.pub)cd ~/.ssh cat id_rsa.pub

Github账号上添加公钥

验证是否配置成功 ssh -T git@github.com

问题

在检验ssh配置时,始终报错,问ai说是配置的原因,尝试删除后,报错Could not resolve hostname github.com: Name or service not known,琢磨无法解决,拼尽全力无法战胜,于是保留下来交给未来的自己

image-20250311172436506

git常用指令

克隆仓库git clone https://github.com/logan-zou/Chat_with_Datawhale_langchain.git

1
2
3
4
5
6
7
8
9
10
11
git init:初始化一个git仓库
git clone:clone一个git仓库
git add 命令可将文件添加到缓存
git status 命令来查看相关文件的状态
git commit 将缓存区内容添加到仓库中,可以在后面加-m选项,以在命令行中提供提交注释

git remote add:添加远程仓库
git remote:查看当前的远程仓库
git fetch、git pull:提取远程仓仓库
git push:推送到远程仓库
git remote rm:删除远程仓库

先做记录,我没用过,我目前选择vscode+GitHub的可视化界面

vscode+GitHub

image-20250311173501909

输入仓库名称 点击commit提交

image-20250311174519221

每次更改代码都可以命名后再次提交

代理配置

1
2
git config --global http.proxy "http://127.0.0.1:8080" 
git config --global https.proxy "http://127.0.0.1:8080"

image-20250311175047287

分别代码本地和远程仓库的位置

天呐这图形化太方便了

参考文献

git安装配置教程(小白保姆教程2024最新版)_git安装及配置教程-CSDN博客

给傻子的Git教程_哔哩哔哩_bilibili

Git教程 Git Bash详细教程-CSDN博客

GIT Proxy 一键设置代理 让你的 git clone Github 再也不像百度云一样内行-CSDN博客

简介 - Git教程 - 廖雪峰的官方网站

pip与conda区别

pipconda 都是用来安装和管理 Python 包的工具,但它们的工作方式和适用场景有所不同。以下是它们的主要区别:

1. 包管理的范围

  • pip:是 Python 官方的包管理工具,只用于安装 Python 包。它从 Python 包索引 (PyPI) 中获取包并安装。这意味着它只能安装 Python 包,不能直接处理其他类型的依赖(如系统库、C 库等)。
  • conda:是一个跨平台的包和环境管理工具,它不仅可以安装 Python 包,还可以安装其他语言(如 R、Java、C++ 等)以及非 Python 依赖(如系统库)。conda 能够管理整个环境(包括 Python 版本和库),并解决与系统库之间的依赖关系。

2. 依赖管理

  • pip:在安装包时,pip 仅会安装 Python 包及其 Python 依赖,而不处理系统级依赖。如果一个包依赖于特定的 C 库或其他非 Python 包,pip 不会自动解决这些问题,这可能导致一些复杂的兼容性问题。
  • conda:会同时处理 Python 包和非 Python 包的依赖。它会在安装时自动解决所有依赖,包括操作系统库、C 库等。因此,conda 在依赖关系处理上比 pip 更强大。

3. 包来源

  • pip:通过 PyPI(Python Package Index)来下载和安装包,PyPI 是一个包含大多数 Python 包的中央库。
  • conda:使用 Anaconda 仓库或其他 conda 仓库。Anaconda 仓库提供了大量的科学计算、数据分析相关的包,而不仅限于 Python 包。conda 还支持安装一些没有在 PyPI 上的包。

4. 环境管理

  • pip:本身不提供环境管理功能,但可以与 virtualenvvenv 等工具结合使用来创建虚拟环境。这些虚拟环境允许你为不同项目隔离依赖。
  • conda:内置环境管理功能,可以通过 conda create 命令直接创建隔离的环境,支持不同版本的 Python 以及其他软件的管理。conda 环境的管理比 pip + virtualenv 更加方便和高效。

5. 安装速度

  • pip:通常只安装 Python 包。对于某些包,特别是需要从源代码编译的包,安装可能会比较慢,尤其是在没有预编译二进制文件的情况下。
  • conda:由于它使用的是预编译的二进制包,安装速度通常更快,尤其是对于依赖项繁多的包(如 numpyscipy 等)。它无需从源代码编译,直接安装预编译的版本。

6. 跨平台支持

  • pip:支持所有操作系统,但在一些操作系统(尤其是 Windows)上,安装某些包时可能会遇到编译问题,尤其是 C 扩展包。
  • conda:同样支持多平台,并且在 Windows 系统上安装一些复杂的包(如 numpypandas 等)时,比 pip 更加稳定和方便,因为它会自动提供适合平台的预编译二进制文件。

7. 包版本冲突

  • pip:虽然可以安装特定版本的包,但如果项目中的多个包有不同的依赖版本,pip 并不能很好地解决这些版本冲突,需要手动处理依赖版本。
  • conda:在安装时,conda 会自动解析所有的依赖关系,确保包和其依赖的版本兼容,从而减少版本冲突。

8. 包更新

  • pip:更新包的方式通常是直接运行 pip install --upgrade <package>,但是它会仅更新 Python 包本身,不会考虑系统级的依赖。
  • conda:更新包时,conda 会同时考虑包的 Python 依赖和系统库依赖,可以更全面地管理包更新。

总结对比表:

特性 pip conda
包管理范围 只管理 Python 包 管理 Python 包和其他非 Python 包
依赖关系管理 只处理 Python 依赖 处理 Python 和非 Python 依赖
包来源 PyPI Anaconda 仓库等
环境管理 需配合 virtualenv 使用 内建环境管理
安装速度 慢(尤其是需要编译的包) 快(使用预编译二进制包)
跨平台支持 跨平台支持良好 更好的 Windows 支持
版本冲突处理 手动解决版本冲突 自动解决版本冲突

什么时候使用 pip,什么时候使用 conda

  • 如果你已经在使用 Anaconda 或 Miniconda,并且需要安装 Python 包及其相关依赖,conda 是更好的选择,因为它可以自动解决依赖并更好地管理环境。
  • 如果你没有使用 Anaconda 或只需要安装纯粹的 Python 包,pip 更为轻量和直接。

在实际使用中,有时你会发现两者可以结合使用:可以用 conda 安装 Python 环境和一些复杂的依赖,再用 pip 安装一些不在 Anaconda 仓库中的包。

jupyter转markdown

一、准备工作

安装nbconverter: nbconvert: Convert Notebooks to other formats

1
pip install nbconvert

注意依赖项:

  • 基本依赖:pandoc
1
pip install pandoc

二、使用方法

命令行:

1
$ jupyter nbconvert --to FORMAT notebook.ipynb

这里FORMAT 用具体的格式替换,如 markdown, html等。

例如:

1
$ jupyter nbconvert --to markdown notebook.ipynb

参考文献

Jupyter Notebook文件转markdown - 知乎

Python常用库

1. Numpy

numpy(Numerical Python的简称)是高性能科学计算和数据分析的基础包。其部分功能如下:

ndarray,一个具有矢量算术运算和复杂广播能力的快速且节省空间的多维数组。 用于对整组数据进行快速运算的标准数学函数(无需编写循环)。 用于读写磁盘数据的工具以及用于操作内存映射文件的工具。 线性代数、随机数生成以及傅里叶变换功能。 用于集成由C、C++、Fortran等语言编写的代码的工具。

2. Pandas

pandas是python第三方库,提供高性能易用数据类型和分析工具 pandas基于numpy实现,常与numpy和matplotlib一同使用 pandas中有两大核心数据结构:Series(一维数据) 和 DataFrame(多特征数据,既有行索引,又有列索引)

3. PIL

PIL库是一个具有强大图像处理能力的第三方库 在命令行下的安装方法:pip install pillow 在使用过程中的引入方法:from PIL import Image Image 是 PIL 库中代表一个图像的类(对象) 图像是一个由像素组成的二维矩阵,每个元素是一个RGB值

4. Matplotlib

Matplotlib库由各种可视化类构成,内部结构复杂。 受Matlab启发,matplotlib.pylot是绘制各类可视化图形的命令字库,相当于快捷方式。

5. scikit-learn

scikit-learn(简称 sklearn)是一个开源的 Python 库,广泛应用于机器学习任务,提供了丰富的工具和算法,能够帮助数据科学家和机器学习工程师高效地进行数据预处理、模型训练、评估和优化。它基于 NumPySciPymatplotlib,具有以下主要特点和功能:

主要功能

  • 分类 (Classification) :用于预测数据点所属的类别(如垃圾邮件分类、疾病预测等)。
  • 回归 (Regression) :用于预测连续的数值(如房价预测、股票价格预测等)。
  • 聚类 (Clustering) :将数据点分为不同的簇或组(如客户细分、图像分割等)。
  • 降维 (Dimensionality Reduction) :减少数据的维度,常用于数据压缩和可视化。
  • 模型评估 (Model Evaluation) :提供评估工具,如交叉验证、准确率、F1 分数等。
  • 数据预处理 (Data Preprocessing) :包括标准化、归一化、缺失值处理、编码等。
  • 超参数调优 (Hyperparameter Tuning) :通过网格搜索(GridSearchCV)和随机搜索(RandomizedSearchCV)来优化模型超参数。
0%