matplotlib绘制线性回归y=kx+b参数的损失函数等高线图

如题,直接上代码和结果

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()

输出结果如下:
在这里插入图片描述

发布了207 篇原创文章 · 获赞 16 · 访问量 9904

猜你喜欢

转载自blog.csdn.net/weixin_41855010/article/details/104616036
今日推荐