线性回归预测
唉,研0了,得学机器学习了。当然还是听的吴恩达老师的课,虽然全是英文,但是,怎么评价呢,讲得既专业又通俗易懂,初学者(像我这样的菜鸡)都值得一看!!
根据人口预测利润 输入变量只有一个特征 人口,输出变量为利润
很基础的东西,跟着老师来,lab里面都已经给你写好了。
python
import pandas as pd
from matplotlib import pyplot as plt
# 损失函数
def compute_loss(x, y, w, b):
m = x.shape[0]
sum = 0.
for i in range(m):
sum += (w * x[i] + b - y[i]) ** 2
return sum / m
# 梯度下降
def gradient_descent(x, y, w, b, eta, iterations):
m = x.shape[0]
loss_history = []
for _ in range(iterations):
sum_w = 0.
sum_b = 0.
for i in range(m):
sum_w += (w * x[i] + b - y[i]) * x[i]
sum_b += (w * x[i] + b - y[i])
new_w = w - eta * sum_w / m
new_b = b - eta * sum_b / m
w = new_w
b = new_b
loss_history.append(compute_loss(x, y, w, b))
return w, b, loss_history
if __name__ == '__main__':
data = pd.read_csv(r'D:\BaiduNetdiskDownload\data_sets\ex1data1.txt', names=["x", "y"])
x = data['x']
y = data['y']
w, b, loss_history = gradient_descent(x, y, 0, 0, 0.01, 1000)
epochs = range(len(loss_history))
print(w, b)
# 打印图标
plt.plot(epochs, loss_history, color='red', label='loss')
# plt.plot(x, w * x + b, color='red')
# plt.scatter(x, y, color='blue')
plt.show()
几个图表
损失:
回归预测:
我的预期:
w : 1.1272942024281842, b : -3.241402144274422