如题,直接上代码和结果
import math
import random
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
x_train = np.array([0, 1, 2, 3, 4, 5])
y_train = np.array([1.1, 2.2, 3.8, 4.1, 4.9, 5.2])
dense = 100
k = np.linspace(0,2,dense)
b = np.linspace(-2,4,dense)
def get_loss_value(k,b):
return np.square(k*x_train+b - y_train).sum()/len(x_train)
def draw_contour_line(dense,isoheight): #dense表示取值的密度,isoheight表示等高线的值
list_k = []
list_b = []
list_loss = []
for i in range(dense):
for j in range(dense):
loss = get_loss_value(k[i],b[j])
if 1.05*isoheight>loss>0.95*isoheight:
list_k.append(k[i])
list_b.append(b[j])
else:
pass
plt.scatter(list_k,list_b,s=1) #s=0.25比较合适
draw_contour_line(dense,0.2)
draw_contour_line(dense,0.5)
draw_contour_line(dense,1)
draw_contour_line(dense,2)
plt.title('Loss Func Contour Line')
plt.xlabel('k')
plt.ylabel('b')
plt.axis([0,2,-2,4])
plt.show()
输出结果如下: