Cost函数公式
![](https://i-blog.csdnimg.cn/blog_migrate/f70fcf5ef3e9e1467910c8be665d3c6e.png)
(一)引用库
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
%matplotlib widget
from ipywidgets import interact
from matplotlib.gridspec import GridSpec
(二)引用中文标题
"""设置图中的文本样式"""
# fname 为下载的字体库路径,注意 SourceHanSansSC-Bold.otf 字体的路径
zhfont1 = matplotlib.font_manager.FontProperties(fname="SourceHanSansSC-Bold.otf", size = 14)
zhfont2 = matplotlib.font_manager.FontProperties(fname="SourceHanSansSC-Bold.otf", size = 12)
# fontdict 可以使用 css 来设置字体样式
font1 = {'color':'#5F9EA0'}
font2 = {'color':'#8FBC8F'}
font3 = {'color':'#DDA0DD'}
font4 = {'color':'#778899'}
(三)对数组x和数组y赋值
x = np.array([2.5, 3.0, 3.2, 4.1, 5.2, 6.1, 7.3, 7.8]) #数组x
y = np.array([520.0, 630.0, 730.0, 790.0, 830.0, 950.0, 1120.0, 1230.0]) #数组y
(四)定义Cost函数公式
#Cost函数公式
def function_cost(x, y, w, b):
m = x.shape[0] #数组x的长度
cost = 0.0 #初始化值为0
for i in range(m):
f_wb_i = np.dot(x[i], w) + b #得到每一个f_wb的值
cost = cost + (f_wb_i - y[i])**2 #求和
cost = cost/(2*m) #计算cost函数的值
return cost #返回cost函数值
(五)用到的注释
#图1的虚线
def mk_cost_lines(x, y, w, b, ax):
cstr = "cost = (1/m)*("
ctot = 0
label = 'cost for point'
addedbreak = False
for p in zip(x,y):
#数组x:p[0],数组y:p[1]
f_wb_p = w*p[0] + b #计算每一个f_wb(x(i))
c_p = ((f_wb_p - p[1])**2)/2 #计算每一个 (f_wb(x(i)) - y(i))**2
c_p_txt = c_p #将每一个(f_wb(x(i)) - y(i))**2的结果赋值给c_p_txt
#虚线颜色
ax.vlines(p[0], p[1], f_wb_p, lw = 2, color = '#87CEFA', ls = 'dotted', label = label)
label = '' #设置只有一个标签
cxy = [p[0], p[1] + (f_wb_p-p[1])/2]
#数字颜色,data = cost * m
ax.annotate(f'{c_p_txt:0.0f}', xy = cxy, xycoords = 'data', color = '#2F4F4F',
xytext=(5, 0), textcoords = 'offset points')
cstr += f"{c_p_txt:0.0f} +"
if len(cstr) > 38 and addedbreak is False:
cstr += "\n"