gpt4 book ai didi

python - 使用实际数据在图上添加回归线

转载 作者:行者123 更新时间:2023-12-04 04:06:05 26 4
gpt4 key购买 nike

我在 Pandas 数据框中有以下数据:

freq = [10, 2, 1, 10, 6, 4, 1, 1,
6, 3, 4, 10, 6, 3, 9, 5,
5, 5, 4, 2, 2, 9, 11, 7, 5,
1, 3, 10, 7, 5, 5, 5, 8,
7, 25, 17, 9, 6, 7, 8, 4,
10, 3, 1, 7, 11, 6, 5, 10,
11, 8, 11, 15, 4, 6, 11, 6,
10, 10, 10, 4, 5, 7, 15, 15,
10, 12, 17, 25, 26, 22, 14, 15,
15, 7, 9, 8, 6, 1]

date=[737444, 737445, 737446, 737447, 737448,
737449, 737450, 737451, 737452, 737453, 737454, 737455, 737456,
737457, 737458, 737459, 737460, 737461, 737462, 737463, 737464,
737465, 737466, 737467, 737468, 737469, 737470, 737472, 737473,
737474, 737475, 737476, 737477, 737478, 737479, 737480, 737481,
737482, 737483, 737484, 737485, 737486, 737487, 737488, 737489,
737490, 737491, 737492, 737493, 737494, 737495, 737496, 737497,
737498, 737499, 737500, 737501, 737502, 737503, 737504, 737505,
737506, 737507, 737508, 737509, 737510, 737511, 737512, 737513,
737514, 737515, 737516, 737517, 737518, 737519, 737520, 737521,
737522, 737523]

我计算的回归系数和截距如下:

    from sklearn.model_selection import train_test_split

y = np.asarray(df['Frequency'])
X = df[['Date']]
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.3,random_state=42)

model = LinearRegression()
model.fit(X_train, y_train)
model.score(X_train, y_train)

coefs = zip(model.coef_, X.columns)
model.__dict__

得到如下结果:

    Coefficient: 
[0.08711929]
Intercept:
-64241.58584385233
sl = -64241.6 + 0.1 Date

我想在显示实际数据趋势的图上方绘制这条线。我该怎么办?

最佳答案

import matplotlib.pyplot as plt

datemin = min(date)
datemax = max(date)

x_new = np.linspace(datemin, datemax , 100)
y_new = model.predict(x_new[:, np.newaxis])

plt.figure(figsize=(4, 3))
ax = plt.axes()
ax.scatter(date, freq)
ax.plot(x_new, y_new)

ax.set_xlabel('x')
ax.set_ylabel('y')

ax.axis('tight')
plt.show()

查看详细解释here

关于python - 使用实际数据在图上添加回归线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62499547/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com