# -*- coding: UTF-8 -*-
import numpy as np
import math
# 定義基礎變量
learning_rate = 0.1
n_iterations = 10000
m = 100
x = 2 * np.random.rand(m, 1) # 生成一組服從0~1均勻分布的隨機樣本,此處表示生成100行一列的二維數組,下同
y = 4 + 3 * x + np.random.randn(m, 1) # 正態分布
x_b = np.c_[np.ones((m, 1)), x] # np.((100, 1)):表示生成100行1列的矩陣,內部填充為1
# 設置閾值
threshold = 0.15
# 1,初始化theta,w0...wn
theta = np.random.randn(2, 1)
count = 0
before_value = 1
# 4,設置閾值,之間設置超參數,迭代次數,迭代次數到了或者滿足閾值,我們就認為收斂了
for iteration in range(n_iterations):
count += 1
# 2,接着求梯度gradient
gradients = 1/m * x_b.T.dot(x_b.dot(theta)-y) # 求平均梯度
# 3,應用公式調整theta值,theta_t + 1 = theta_t - grad * learning_rate
theta = theta - learning_rate * gradients
# 判斷是否滿足閾值
mid = math.sqrt(math.pow((theta[0][0] - 4), 2) + math.pow((theta[1][0] - 3), 2))
if mid <= threshold:
print('總共執行{}次迭代,可知迭代次數設置過大,建議適當減小!'.format(count))
break
# 若與上一次的中間結果比較差值過小也同樣結束循環
err = math.fabs(mid - before_value)
if err < 0.001:
if before_value > threshold:
print('多次迭代都不能滿足閾值,請修改閾值或重新處理數據!')
break
else:
print('總共執行{}次迭代,可知迭代次數設置過大,建議適當減小!'.format(count))
break
# 暫時保存上一次的中間結果
before_value = mid
print('結果:\n x is : {}\n y is : {}\n 誤差 : {}'.format(theta[0][0], theta[1][0], before_value))
結果: