TingHong18 / Machine-Learing

0 stars 0 forks source link

CostFunction #2

Open TingHong18 opened 3 weeks ago

TingHong18 commented 3 weeks ago
#載入csv檔案
import pandas as pd
data = pd.read_csv("Salary_Data.csv",encoding="utf-8")

x = data["YearsExperience"]
y = data["Salary"]
#運用
w=10
b=0
y_pred = w*x + b
cost = (y-y_pred)**2 #距離平方
print(cost.sum()/len(x)) #距離平方的平均
#寫成函式
def computecost(x,y,w,b):
    y_pred = w*x + b
    cost = (y-y_pred)**2 #距離平方
    cost = cost.sum()/len(x) #距離平方的平均
    return cost

#當b=0 w=-100~100 cost=多少?
costs =[]
for w in range(-100,101):
    cost = computecost(x, y, w, 10)
    costs.append(cost)
#將資料繪製成圖
import matplotlib.pyplot as plt
plt.scatter(range(-100,101),costs)
plt.savefig("xxx.png")

image

#繪製成拋物線
plt.plot(range(-100,101),costs)
plt.title("b=0 w=-100~100")
plt.xlabel("w")
plt.ylabel("cost")
plt.savefig("xxx.png")

image

#當b=-100~100 w=-100~100 cost=多少?
import numpy as np
ws = np.arange(-100,101)
bs = np.arange(-100,101)
costs = np.zeros((201,201)) #存放不同的w跟b對應到的cost
i=0
for w in ws:
    j=0
    for b in bs:
        cost = computecost(x,y,w,b)
        costs[i,j] = cost
        j=j+1
    i=i+1

ax=plt.axes(projection="3d")
b_grid, w_grid=np.meshgrid(bs,ws) #將ws跟bs製成二維網格
ax.plot_surface(w_grid,b_grid,costs) #需傳入ws跟bs的二維網格
ax.set_title("b=-100~100 w=-100~100")
ax.set_xlabel("w")
ax.set_ylabel("b")
ax.set_zlabel("cost")
plt.savefig("xxx.png")

image

ax.plot_surface(w_grid,b_grid,costs,cmap="Spectral_r",alpha=0.7) #需傳入ws跟bs的二維網格,cmap顏色、alpha透明度
ax.plot_wireframe(w_grid,b_grid,costs,color="black",alpha=0.1) #設定邊框
ax.view_init(45,-120) #改變角度

image

plt.figure(figsize=(10,10)) #設定圖的大小
np.min(costs) #最低點(cost)
w_index,b_index = np.where(costs == np.min(costs)) #最低點對應的w跟b索引值
ax.scatter(ws[w_index],bs[b_index],costs[w_index,b_index],color="red",s=40) #劃出最小的點,color顏色、s大小
print(w_index,b_index) #[109] [129]
print(ws[w_index],bs[b_index]) #再從索引值找出對應的w跟b #[9] [29]
print(f"當w={ws[w_index]},b={bs[b_index]} 會有最小cost:{costs[w_index,b_index]}") #當w=[9],b=[29] 會有最小cost:[32.69484848]

image