def fit(self, x, y):
     x_pow = []                              # 空のリストを定義
     xx = x.reshape(len(x), 1)               # 2次元配列としての縦ベクトルに変換
     for i in range(1, self.degree + 1):
         x_pow.append(xx**i)                 # ベクトルxを0乗(=1)から指定したdegree乗までリストに追加する
     mat = np.concatenate(x_pow, axis = 1)   # degree乗まで格納したリスト(ベクトル)を横に結合して行列を作成
     linreg = p_ml_03_LinearReg.LinearRegression()     # 自作モジュールから線形回帰のクラスを呼び出し
     linreg.fit(mat, y)
     self.w_ = linreg.w_
Example #2
0
def f(x):
    return 1 + 2 * x


x = np.random.random(10) * 10  # 乱数を生成して10倍
y = f(x) + np.random.randn(10)  # xをf(x)に代入した値に乱数でノイズを載せている

# 多項式回帰
model = p_ml_10_PolynomialReg.PolynomialRegression(10)  # 10乗まで考えた多項式回帰
model.fit(x, y)

plt.scatter(x, y, color="b")
plt.ylim([y.min() - 1, y.max() + 1])  # グラフの表示範囲をyの最大最小の+-1までに限定

xx = np.linspace(x.min(), x.max(), 300)  # xの最大最小の間を300分割
yy = np.array([model.predict(u)
               for u in xx])  # xxの値それぞれについて多項式回帰で予測した値をyyに配列として格納
plt.plot(xx, yy, color="r")

# 線形回帰
model = p_ml_03_LinearReg.LinearRegression()
model.fit(x, y)
b, a = model.w_

x1 = x.min() - 1
x2 = x.max() + 1
plt.plot([x1, x2], [f(x1), f(x2)], color="k", linestyle="dashed")

plt.show()
Example #3
0
y_poly_sum = np.zeros(len(xx))  # xxと同じ要素数の零ベクトルを作成
y_poly_sum_sq = np.zeros(len(xx))  # xxと同じ要素数の零ベクトルを作成
y_lin_sum = np.zeros(len(xx))  # xxと同じ要素数の零ベクトルを作成
y_lin_sum_sq = np.zeros(len(xx))  # xxと同じ要素数の零ベクトルを作成
y_true = f(xx)

n = 100000

warnings.filterwarnings("ignore")

for i in range(n):
    x, y = sample(5)
    poly = p_ml_10_PolynomialReg.PolynomialRegression(4)  # 4次の多項式近似
    poly.fit(x, y)

    lin = p_ml_03_LinearReg.LinearRegression()  # 線形近似
    lin.fit(x, y)

    y_poly = poly.predict(xx)
    y_poly_sum += y_poly  # 多項式近似による予測値の合計
    y_poly_sum_sq += (y_poly - y_true)**2  # 予測値と真値の差の2乗の合計

    y_lin = lin.predict(xx.reshape(-1, 1))
    y_lin_sum += y_lin  # 線形近似による予測値の合計
    y_lin_sum_sq += (y_lin - y_true)**2  # 予測値と真値の差の2乗の合計

fig = plt.figure()

ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)