python之机械学习题3求损失函数的关系图
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
x_data=[1,2,3]
y_data=[2,4,6]
#定义初始函数
def fun(x,w):
return x*w
#定义损失函数
def loss(x,y):
y_pred = fun(x,w)
return (y_pred -y)**2
#权重准备空列表
w_list = []
mse_list = []
for w in np.arange(0,4.1,0.1):
sum_tot=0
for x,y in zip(x_data,y_data):
sum_tot +=loss(x,y)
w_list.append(w)
mse_list.append(sum_tot/3)
#画图
plt.plot(w_list,mse_list)
plt.ylabel("loss")
plt.xlabel("w")
plt.title("loss han shu!!")