在Matplotlib中展示中文,防止乱码
核心代码:
1plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
2plt.rcParams['axes.unicode_minus'] = False #用来正常显示负号
完整代码:
1import numpy as np
2import matplotlib.pyplot as plt
3from sklearn.linear_model import Lasso
4
5plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
6plt.rcParams['axes.unicode_minus'] = False #用来正常显示负号
7
8# 生成模拟数据
9np.random.seed(42)
10disciple_count = np.random.randint(50, 200, size=20)
11establishment_years = np.random.randint(1, 100, size=20)
12weapon_types = np.random.randint(1, 10, size=20)
13master_skill = 2 * disciple_count + 1.5 * establishment_years + 3 * weapon_types + np.random.randn(20) * 20 + 100
14
15# 数据转换为二维数组
16X = np.column_stack((disciple_count, establishment_years, weapon_types))
17y = master_skill
18
19# 创建Lasso回归模型并训练
20lasso_reg = Lasso(alpha=0.1)
21lasso_reg.fit(X, y)
22
23# 打印模型参数
24print("截距:", lasso_reg.intercept_)
25print("系数:", lasso_reg.coef_)
26
27# 可视化回归平面(这里只能展示两个特征的二维平面图)
28plt.scatter(disciple_count, master_skill, color='blue', label='实际数据')
29plt.plot(disciple_count, lasso_reg.intercept_ + lasso_reg.coef_[0] * disciple_count + lasso_reg.coef_[1] * np.mean(establishment_years), color='red', linewidth=2, label='回归直线')
30plt.title("武侠小说中的Lasso回归示例")
31plt.xlabel("弟子数量")
32plt.ylabel("掌门武功修为")
33plt.legend()
34plt.show()