happywu 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,23 @@
1
+ Metadata-Version: 2.4
2
+ Name: happywu
3
+ Version: 0.1.0
4
+ Summary: happywu — 原始 .py 文件原样分发(单文件顶层模块)
5
+ Author-email: happywu <happywu@example.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://pypi.org/project/happywu/
8
+ Requires-Python: >=3.8
9
+ Description-Content-Type: text/markdown
10
+ Requires-Dist: numpy
11
+ Requires-Dist: pandas
12
+ Requires-Dist: scikit-learn
13
+ Requires-Dist: scipy
14
+ Requires-Dist: matplotlib
15
+ Requires-Dist: seaborn
16
+
17
+ # happywu
18
+
19
+ 原 `.py` 文件一字不改,作为顶层单文件模块 `happywu` 分发。
20
+
21
+ 安装:`pip install happywu`
22
+
23
+ 使用:`import happywu`,安装后 `site-packages/happywu.py` 的内容与作者上传的原文件完全一致。
@@ -0,0 +1,5 @@
1
+ happywu.py,sha256=xDPdb5FV5uAO93m_ClxtVYu_8Eg9ZCX6_HfCEdU2sO0,9440
2
+ happywu-0.1.0.dist-info/METADATA,sha256=ZO0ZwaiFTyrv-j-3ggSOCElq72-It2hVxoktFKgPDJA,688
3
+ happywu-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
4
+ happywu-0.1.0.dist-info/top_level.txt,sha256=WpXArOYRVc6Y8u-WDSQjg6gcdu1vOXMtuQnEBw4d7rc,8
5
+ happywu-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ happywu
happywu.py ADDED
@@ -0,0 +1,236 @@
1
+ # 2026湖北工匠杯 人工智能算法测试员 样题参考答案
2
+ # 任务:电信客户流失预测 全流程实现
3
+ # 代码风格:简约清晰,带详细注释,覆盖所有得分点
4
+
5
+ # -------------------------- 模块A:数据加载与预处理 --------------------------
6
+ # 1. 导入所需库
7
+ import pandas as pd
8
+ import numpy as np
9
+ import matplotlib.pyplot as plt
10
+ from sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV
11
+ from sklearn.preprocessing import StandardScaler, LabelEncoder
12
+ from sklearn.linear_model import LogisticRegression
13
+
14
+ from sklearn.metrics import (accuracy_score, precision_score, recall_score, f1_score,
15
+ confusion_matrix, classification_report)
16
+ import seaborn as sns
17
+
18
+ # 2. 生成示例数据集(正式比赛时直接pd.read_csv('churn_data.csv')即可)
19
+ # 注:示例数据已构造特征与流失的真实关联,方便观察模型效果;正式比赛数据无需此步
20
+ def generate_sample_data():
21
+ np.random.seed(42)
22
+ n = 2000
23
+ # 构造特征:月付合同、电子支票支付、在网时长越短、月费越高,流失概率越大
24
+ tenure = np.random.randint(1, 72, n)
25
+ monthly_charges = np.round(np.random.uniform(20, 120, n), 2)
26
+ contract = np.random.choice(['月付', '一年', '两年'], n, p=[0.6, 0.25, 0.15])
27
+ payment = np.random.choice(['电子支票', '邮寄支票', '银行转账', '信用卡'], n)
28
+
29
+ # 计算流失概率
30
+ churn_prob = 0.1
31
+ churn_prob += (contract == '月付') * 0.3 # 月付用户流失率高30%
32
+ churn_prob += (payment == '电子支票') * 0.2 # 电子支票支付流失率高20%
33
+ churn_prob += (tenure < 12) * 0.2 # 新用户流失率高20%
34
+ churn_prob += (monthly_charges > 80) * 0.1 # 高月费用户流失率高10%
35
+ churn_prob = np.clip(churn_prob, 0.05, 0.8)
36
+ churn = np.random.binomial(1, churn_prob, n)
37
+ churn = np.where(churn == 1, '是', '否')
38
+
39
+ data = {
40
+ 'customerID': [f'CUST_{i:04d}' for i in range(n)],
41
+ 'tenure': tenure,
42
+ 'MonthlyCharges': monthly_charges,
43
+ 'Contract': contract,
44
+ 'PaymentMethod': payment,
45
+ 'Churn': churn
46
+ }
47
+ # 计算TotalCharges并加少量缺失值
48
+ data['TotalCharges'] = data['tenure'] * data['MonthlyCharges'] * np.random.uniform(0.9, 1.1, n)
49
+ miss_idx = np.random.choice(n, 45, replace=False)
50
+ for i in miss_idx:
51
+ data['TotalCharges'][i] = np.nan
52
+ df = pd.DataFrame(data)
53
+ df.to_csv('churn_data.csv', index=False, encoding='utf-8-sig')
54
+ return df
55
+
56
+ # 加载/生成数据
57
+ df = generate_sample_data() # 正式比赛替换为 df = pd.read_csv('churn_data.csv')
58
+
59
+ # 3. 数据基本信息输出
60
+ print("=== 数据集基本信息 ===")
61
+ print(f"数据规模:{df.shape[0]}行,{df.shape[1]}列")
62
+ print("\n字段类型:")
63
+ print(df.dtypes)
64
+ print("\n统计摘要:")
65
+ print(df.describe())
66
+
67
+ # 4. 数据探索与清洗
68
+ print("\n=== 缺失值检查 ===")
69
+ print(df.isnull().sum())
70
+ # TotalCharges缺失值用中位数填充(数值型字段)
71
+ df['TotalCharges'] = df['TotalCharges'].fillna(df['TotalCharges'].median())
72
+ # 删除重复值
73
+ df = df.drop_duplicates()
74
+ print(f"去重后数据量:{len(df)}")
75
+
76
+ # 标签分布
77
+ print("\n=== 标签(Churn)分布 ===")
78
+ print(df['Churn'].value_counts(normalize=True).round(2))
79
+
80
+ # 5. 特征预处理
81
+ # 删除无用ID列
82
+ df = df.drop('customerID', axis=1)
83
+ # 分类特征编码
84
+ le_contract = LabelEncoder()
85
+ le_payment = LabelEncoder()
86
+ le_churn = LabelEncoder()
87
+ df['Contract'] = le_contract.fit_transform(df['Contract'])
88
+ df['PaymentMethod'] = le_payment.fit_transform(df['PaymentMethod'])
89
+ df['Churn'] = le_churn.fit_transform(df['Churn']) # 是=1,否=0
90
+
91
+ # 划分特征X和标签y
92
+ X = df.drop('Churn', axis=1)
93
+ y = df['Churn']
94
+
95
+ # 按8:2划分训练集测试集,固定随机种子,分层抽样保持类别比例
96
+ X_train, X_test, y_train, y_test = train_test_split(
97
+ X, y, test_size=0.2, random_state=42, stratify=y
98
+ )
99
+
100
+ # 数值特征标准化(仅用训练集拟合,避免数据泄漏)
101
+ num_cols = ['tenure', 'MonthlyCharges', 'TotalCharges']
102
+ scaler = StandardScaler()
103
+ X_train[num_cols] = scaler.fit_transform(X_train[num_cols])
104
+ X_test[num_cols] = scaler.transform(X_test[num_cols])
105
+
106
+ # -------------------------- 模块A2:算法实现 --------------------------
107
+ # 选择逻辑回归算法(二分类任务常用,稳定易解释)
108
+ model = LogisticRegression(max_iter=1000, random_state=42)
109
+ model.fit(X_train, y_train) # 训练模型
110
+ y_pred = model.predict(X_test) # 测试集预测
111
+ print("\n=== 默认模型初测准确率:", round(accuracy_score(y_test, y_pred), 3))
112
+
113
+ # -------------------------- 模块B:算法运行与验证 --------------------------
114
+ # B2 交叉验证与指标计算
115
+ print("\n=== 5折交叉验证结果 ===")
116
+ cv_scores = cross_val_score(model, X_train, y_train, cv=5, scoring='accuracy')
117
+ print(f"交叉验证平均准确率:{cv_scores.mean():.3f} ± {cv_scores.std():.3f}")
118
+
119
+ # 计算各项验证指标
120
+ y_pred = model.predict(X_test)
121
+ print("\n=== 模型验证指标 ===")
122
+ print(f"准确率:{accuracy_score(y_test, y_pred):.3f}")
123
+ print(f"精确率:{precision_score(y_test, y_pred):.3f}")
124
+ print(f"召回率:{recall_score(y_test, y_pred):.3f}")
125
+ print(f"F1值:{f1_score(y_test, y_pred):.3f}")
126
+ print("\n分类报告:")
127
+ print(classification_report(y_test, y_pred, target_names=['未流失','流失']))
128
+
129
+ # 混淆矩阵
130
+ cm = confusion_matrix(y_test, y_pred)
131
+ print("混淆矩阵:\n", cm)
132
+
133
+ # B3 超参数调优(GridSearchCV)
134
+ param_grid = {
135
+ 'C': [0.01, 0.1, 1, 10, 100], # 正则化强度参数
136
+ }
137
+ grid = GridSearchCV(LogisticRegression(max_iter=1000, random_state=42),
138
+ param_grid, cv=5, scoring='f1')
139
+ grid.fit(X_train, y_train)
140
+ print(f"\n最优参数:{grid.best_params_}")
141
+ print(f"最优交叉验证F1得分:{grid.best_score_:.3f}")
142
+
143
+ # 用最优参数重新训练
144
+ best_model = grid.best_estimator_
145
+ y_pred_best = best_model.predict(X_test)
146
+
147
+ # 对比默认参数vs调优后指标
148
+ compare_df = pd.DataFrame({
149
+ '指标': ['准确率','精确率','召回率','F1值'],
150
+ '默认参数': [
151
+ accuracy_score(y_test, model.predict(X_test)),
152
+ precision_score(y_test, model.predict(X_test)),
153
+ recall_score(y_test, model.predict(X_test)),
154
+ f1_score(y_test, model.predict(X_test))
155
+ ],
156
+ '调优后参数': [
157
+ accuracy_score(y_test, y_pred_best),
158
+ precision_score(y_test, y_pred_best),
159
+ recall_score(y_test, y_pred_best),
160
+ f1_score(y_test, y_pred_best)
161
+ ]
162
+ })
163
+ compare_df = compare_df.round(3)
164
+ print("\n=== 参数调优对比表 ===")
165
+ print(compare_df)
166
+
167
+ # B4 合理性验证:过拟合检查
168
+ train_acc = accuracy_score(y_train, best_model.predict(X_train))
169
+ test_acc = accuracy_score(y_test, y_pred_best)
170
+ print(f"\n=== 过拟合检查 ===")
171
+ print(f"训练集准确率:{train_acc:.3f},测试集准确率:{test_acc:.3f}")
172
+ print(f"准确率差:{abs(train_acc - test_acc):.3f},小于0.1说明无明显过拟合")
173
+
174
+ # -------------------------- 模块C:结果可视化与分析 --------------------------
175
+ plt.rcParams['font.sans-serif'] = ['SimHei', 'WenQuanYi Micro Hei'] # 解决中文显示
176
+ plt.rcParams['axes.unicode_minus'] = False
177
+
178
+ # C1 混淆矩阵热力图
179
+ plt.figure(figsize=(6,5))
180
+ sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',
181
+ xticklabels=['未流失','流失'], yticklabels=['未流失','流失'])
182
+ plt.title('混淆矩阵热力图')
183
+ plt.xlabel('预测标签')
184
+ plt.ylabel('真实标签')
185
+ plt.savefig('混淆矩阵.png', dpi=100, bbox_inches='tight')
186
+ plt.close()
187
+
188
+ # 参数对比柱状图
189
+ plt.figure(figsize=(8,5))
190
+ x = np.arange(len(compare_df['指标']))
191
+ width = 0.35
192
+ plt.bar(x - width/2, compare_df['默认参数'], width, label='默认参数')
193
+ plt.bar(x + width/2, compare_df['调优后参数'], width, label='调优后参数')
194
+ plt.xticks(x, compare_df['指标'])
195
+ plt.ylabel('得分')
196
+ plt.title('默认参数vs调优后指标对比')
197
+ plt.legend()
198
+ # 标注数值
199
+ for i, v in enumerate(compare_df['默认参数']):
200
+ plt.text(i - width/2, v+0.01, str(v), ha='center')
201
+ for i, v in enumerate(compare_df['调优后参数']):
202
+ plt.text(i + width/2, v+0.01, str(v), ha='center')
203
+ plt.ylim(0, 1.1)
204
+ plt.savefig('参数对比图.png', dpi=100, bbox_inches='tight')
205
+ plt.close()
206
+
207
+ # 参数影响曲线
208
+ C_values = [0.01,0.1,1,10,100]
209
+ acc_list = []
210
+ f1_list = []
211
+ for c in C_values:
212
+ m = LogisticRegression(C=c, max_iter=1000, random_state=42)
213
+ m.fit(X_train, y_train)
214
+ yp = m.predict(X_test)
215
+ acc_list.append(accuracy_score(y_test, yp))
216
+ f1_list.append(f1_score(y_test, yp))
217
+
218
+ plt.figure(figsize=(8,5))
219
+ plt.plot(C_values, acc_list, 'o-', label='准确率')
220
+ plt.plot(C_values, f1_list, 's-', label='F1值')
221
+ plt.xscale('log')
222
+ plt.xlabel('正则化参数C')
223
+ plt.ylabel('得分')
224
+ plt.title('参数C对模型性能影响')
225
+ plt.legend()
226
+ plt.grid(alpha=0.3)
227
+ plt.savefig('参数影响曲线.png', dpi=100, bbox_inches='tight')
228
+ plt.close()
229
+
230
+ print("\n=== 所有任务执行完成!已生成混淆矩阵.png、参数对比图.png、参数影响曲线.png ===")
231
+
232
+ # -------------------------- 验证结论参考 --------------------------
233
+ # 1. 最优参数:根据GridSearch结果确定,通常C=1或10表现最优
234
+ # 2. 模型稳定性:5折交叉验证标准差小于0.05说明模型稳定
235
+ # 3. 无明显数据泄漏:标准化仅用训练集拟合,测试集未参与训练过程
236
+ # 4. 无明显过拟合:训练集与测试集准确率差小于0.1