【问题标题】:Polynomial fit doesn't plot high degrees多项式拟合不会绘制高度数
【发布时间】:2017-07-13 01:22:44
【问题描述】:

我现在正在使用回归并尝试将多项式模型拟合到具有 3 个不同度数的数据中,并且它仅绘制最低度数。我不知道我哪里出错了。这是我的代码和数据点:

# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime as dt
import time

def main():
    inputfile = "statistics.txt"
    X= np.loadtxt(inputfile, delimiter=",",dtype=np.str, usecols=[0])
    X= [dt.datetime.strptime(date, '%d.%m.%Y') for date in X]
    X = mdates.date2num(X)
    Y= np.loadtxt(inputfile, delimiter=",", usecols=[1])
    num_training = int(0.9*len(X))
    num_test = len(X) - num_training
    X_train, Y_train = X[:num_training], Y[:num_training]
    X_test, Y_test = X[num_training:], Y[num_training:]
    plt.scatter(X_train, Y_train, color="blue",s=10, marker='o')
    plt.title("Euro Swedish Krona Exchange rate")
    plt.xlabel("Time in months from April to June in 2017")
    plt.ylabel("Exhange rate")
    colors = ['teal', 'yellowgreen', 'gold']
    for count, degree in enumerate([2, 3, 4]):
        coeffs = np.polyfit(X_train, Y_train, degree)
        f = np.poly1d(coeffs)
        x_line = np.linspace(X[0], X[-1], 50)
        x_line_plot = mdates.num2date(x_line)
        y_line = f(x_line)
        plt.plot(x_line_plot, y_line, color=colors[count], linewidth=2, label="degree {}".format(degree))
        print(coeffs)
    plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%b'))
    plt.gca().xaxis.set_major_locator(mdates.MonthLocator())    
    plt.grid()
    plt.legend(loc='upper left')
    plt.show()

if __name__ == '__main__':
    main()

-----statistics.txt-----

11.04.2017,9.6059
12.04.2017,9.5741
13.04.2017,9.5976
14.04.2017,9.5892
17.04.2017,9.5763
18.04.2017,9.6101
19.04.2017,9.6107
20.04.2017,9.6309
21.04.2017,9.6611
24.04.2017,9.6266
25.04.2017,9.5858
26.04.2017,9.5551
27.04.2017,9.6070
28.04.2017,9.6474
01.05.2017,9.6438
02.05.2017,9.6220
03.05.2017,9.6326
04.05.2017,9.7007
05.05.2017,9.6669
08.05.2017,9.6616
09.05.2017,9.6649
10.05.2017,9.6974
11.05.2017,9.6489
12.05.2017,9.6480
15.05.2017,9.6903
16.05.2017,9.7402
17.05.2017,9.7432
18.05.2017,9.7797
19.05.2017,9.7800
22.05.2017,9.7683
23.05.2017,9.7363
24.05.2017,9.7255
25.05.2017,9.7378
26.05.2017,9.7233
29.05.2017,9.7138
30.05.2017,9.7580
31.05.2017,9.7684
01.06.2017,9.7402
02.06.2017,9.7256
05.06.2017,9.7388
06.06.2017,9.7707
07.06.2017,9.7833
08.06.2017,9.7685
09.06.2017,9.7579
12.06.2017,9.7980
13.06.2017,9.7460
14.06.2017,9.7634
15.06.2017,9.7540
16.06.2017,9.7510
19.06.2017,9.7475
20.06.2017,9.7789
21.06.2017,9.7676
22.06.2017,9.7581
23.06.2017,9.7629
26.06.2017,9.7537
27.06.2017,9.7647
28.06.2017,9.7213
29.06.2017,9.6806
30.06.2017,9.6309
03.07.2017,9.6479
04.07.2017,9.6740
05.07.2017,9.6332
06.07.2017,9.6457
07.07.2017,9.6084
10.07.2017,9.6101
11.07.2017,9.6299

我认为它与日期有关,因为我的情节没有日期。我的代码中也可能有太多东西。也很奇怪,通过改变度数我有时会得到 3 条曲线,有时只有 1 条。

【问题讨论】:

  • 您可以向我们展示您的 .txt 文件,并解释您遇到的错误。
  • 如果你放大你的图,你会看到它确实绘制了所有三个,但是它们非常接近。

标签: python numpy matplotlib


【解决方案1】:

正如@DavidG 在评论中指出的那样,这三条曲线非常接近,所以除非你放大它们,否则它们看起来是一样的。

这只是问题的一个症状。您可能注意到运行代码时打印的警告。这些表明polyfit 中出现了数值问题。您的 X 值相对较大且非常接近。显然它们大到足以在polyfit 中引起问题。避免这种情况的一种方法是从X 值中减去平均值,因此它们以 0 为中心。(您也可以考虑将移位数据除以其标准差。这种组合的移位和缩放称为白化。在这种情况下,简单地移动数据就足够了。)

这里是对X 值进行这种转换的拟合和绘图代码的修改版本(我也稍微调整了颜色和样式):

colors = ['teal', 'darkgreen', 'black']
markers = ['-', ':', '--']
alphas = [1, 1, 0.25]
mu = X_train.mean()
for count, degree in enumerate([2, 3, 4]):
    coeffs = np.polyfit(X_train - mu, Y_train, degree)
    f = np.poly1d(coeffs)
    x_line = np.linspace(X[0], X[-1], 50) 
    x_line_plot = mdates.num2date(x_line)
    y_line = f(x_line - mu)
    plt.plot(x_line_plot, y_line, markers[count], color=colors[count],
             linewidth=1+2*(count==2), alpha=alphas[count],
             label="degree {}".format(degree))
    print(coeffs)

事实证明,3 次和 4 次曲线仍然接近,但它们与 2 次曲线有很大不同:

【讨论】:

  • 感谢您的精彩回答!我从这个问题中学到的是我应该使用带有颜色的标记,并且有有用的预处理技术来避免错误!这是后续问题:现在我已经了解了回归,有线性和多项式以及正弦曲线等类型的函数来拟合数据曲线。虽然有时我必须使用预处理方法来修改我的数据(从这里学习)。如果我理解正确 numpy 的 polyfit 使用最小二乘法作为估计器。
  • 我可以使用其他一些我可以在 numpy 中找到的估计器(我知道在 sklearn 中我可以使用 Ridge Bayasian 等),因为 numpy 只是使用的软件。关于回归和曲线拟合还有什么我应该知道的吗?
  • 这个问题有点过于宽泛,无法在对 SO 的评论中回答,我觉得没有资格回答任何人“应该知道”的问题。 :) 这样的问题可能适合stats.stackexchange.com
  • 好的,我会尝试自己学习主题回归。我有最后一个问题:我如何通过一些因素来估计哪个程度最适合数据?如果有几个因素我很想知道如何用因素实现曲线性能。 (我知道有所谓的过拟合问题,Tikhonov/Ridge 正在尝试解决它。​​)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-30
  • 2013-09-14
  • 2017-05-31
  • 2018-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多