# 多項式迴歸

``````import numpy as np
import matplotlib.pyplot as plt
import cv2

idx = np.where(img < 127)       # 黑點的索引

data_x = idx[1]
data_y = -idx[0] + img.shape[0] # 反轉 y 軸

plt.gca().set_aspect(1)
plt.scatter(data_x, data_y)

plt.show()
``````

``````import numpy as np
import matplotlib.pyplot as plt
import cv2
import numpy.polynomial.polynomial as p

idx = np.where(img < 127)               # 黑點的索引

data_x = idx[1]
data_y = -idx[0] + img.shape[0]         # 反轉 y 軸

t0, t1 = p.polyfit(data_x, data_y, 1)   # 求係數

x = np.array([0, 50])
y = t0  + t1 * x

plt.gca().set_aspect(1)
plt.scatter(data_x, data_y)
plt.plot(x, y)

plt.show()
``````

``````import numpy as np
import matplotlib.pyplot as plt
import cv2
import numpy.polynomial.polynomial as p

idx = np.where(img < 127)       # 黑點的索引

data_x = idx[1]
data_y = -idx[0] + img.shape[0] # 反轉 y 軸

plt.gca().set_aspect(1)
plt.scatter(data_x, data_y)

t0, t1, t2 = p.polyfit(data_x, data_y, 2) # 求二次多項式的係數

x = np.linspace(0, 50, 50)
y = t0  + t1 * x + t2 * (x ** 2)

plt.plot(x, y)

plt.show()
``````

``````import numpy as np
import matplotlib.pyplot as plt
import cv2
from numpy.polynomial import Polynomial as P

idx = np.where(img < 127)       # 黑點的索引

data_x = idx[1]
data_y = -idx[0] + img.shape[0] # 反轉 y 軸

plt.gca().set_aspect(1)
plt.scatter(data_x, data_y)

p = P.fit(data_x, data_y, 2)    # 傳回 `Polynomial` 實例
x, y = p.linspace()             # 傳回 domain 範圍內的 x 與對應的 y

plt.plot(x, y)
plt.show()
``````

`Polynomial` 實例代表一個多項式，以上例來說，傳回的 `Polynomial` 實例，其 `domain` 會是 `[0, 49]`，也就是以給定的 `data_x``domain` 範圍，也就是資料的定義域，`linspace` 方法會傳回 `domain` 範圍內的 x 與對應的 y。

``````import numpy as np
import matplotlib.pyplot as plt
import cv2
from numpy.polynomial import Polynomial as P

idx = np.where(img < 127)       # 黑點的索引

data_x = idx[1]
data_y = -idx[0] + img.shape[0] # 反轉 y 軸

plt.gca().set_aspect(1)
plt.scatter(data_x, data_y)

p = P.fit(data_x, data_y, 2, window = [0, img.shape[1]]) # 指定 window
t0, t1, t2 = p.coef  # 取得係數

x = np.linspace(0, 50, 50)
y = t0  + t1 * x + t2 * (x ** 2)

plt.plot(x, y)
plt.show()
``````