機器學習第乙個演算法

2021-09-26 22:50:54 字數 1944 閱讀 3709

單變數線性回歸

#導包import numpy as np

import matplotlib.pyplot as plt

plt.rcparams[『font.sans-serif』]=[『simhei』]#正常顯示中文

plt.rcparams[『axes.unicode_minus』]=false#正常顯示符號

#讀取資料

data=np.loadtxt(r』資料集檔案所在路徑』,delimiter=』,』)

print(data.shape)

#資料提取

x=data[:,:-1]# x行向量

y=data[:,-1]# y列向量

#資料初始化

x=np.c_[np.ones(len(x)),x]#按列方向組合

y=np.c_[y]#按列方向組合

#定義模型

def model(x,theta):

h=np.dot(x,theta)#公式 點乘

return h

#定義代價函式

def cost_function(h,y):

m=len(y)#例項的數量

j=1.0/(2*m)np.sum(np.square(h-y))#代價函式公式 計算總誤差

# j=1.0/(2m)*np.dot((h-y).t,(h-y))

return j

#定義梯度下降函式

def gradient_descent(x,y,alpha=0.01,iter_num=2000):

m,n=x.shape#樣本個數

theta=np.zeros((n,1))#初始化thete值

j_history=np.zeros(iter_num)#初始化代價函式值

# 執行梯度下降

for i in range(iter_num):

h=model(x,theta)

j_history[i]=cost_function(h,y)#計算並儲存代價函式值

deltatheta=(1.0/m)*np.dot(x.t,h-y)#公式 計算deltatheta

theta-=alpha*deltatheta#更新delta

return j_history,theta

j_history,theta=gradient_descent(x,y)

print(theta)

plt.title(『代價曲線』)

plt.plot(j_history,c=『c』)#c是顏色(color)

plt.xlabel(『迭代次數』)

plt.ylabel(『迭代值』)

plt.show()

plt.title(『樣本散點圖』)

plt.scatter(x[:,1],y[:,0],c=『pink』,marker=』*』,label=『樣本點』)#marker是點的樣式

min_x,max_x=np.min(x[:,1]),np.max(x[:,1])

min_x_y,max_x_y=theta[0]+theta[1]*min_x,theta[0]+theta[1]*max_x

plt.plot([min_x,max_x],[min_x_y,max_x_y],c=『purple』)

plt.legend()

plt.show()

#資料模型

xx=np.arange(4,24)#設定模型的x值

yy=theta[0]+theta[1]*xx#根據模型和xx,計算**值yy

plt.title(『模型』)

plt.scatter(x[:,1],y,c=『k』,marker=』+』)

plt.xlim(4,25)

plt.plot(xx,yy,c=『b』)

plt.legend()

plt.show()

散點圖:

Python機器學習 第乙個機器學習專案

資料集 1.導入庫 import pandas as pd import numpy as np import matplotlib as plt from sklearn.model selection import train test split from sklearn.model sele...

記學習機器學習的第乙個演算法

就拿最經典的房屋 來說吧,我們假設想用房屋面積去 房屋 我們需要去假設自變數房屋面積和因變數房屋面積是線性相關關係的,而線性回歸正適合解決連續性變數 問題,所以這裡我們可以用單變數線性回歸去 它。如圖,我們的資料集變化趨勢擬合一條直線,而我們的目的就是盡可能去找到一條直線擬合最多的點 對於多元線性回...

第乙個機器學習樣例《python與機器學習實戰》

該資料集比較簡單,但是資料相當的大。保留他原始形式是有必要的。我們通過資料標準化處理對他做簡單的處理以降低問題的複雜度 標準化的數學公式為 資料規範化詳見這個博主的 我使用的jupyter notebook編譯器 資料匯入jupyter notebook有兩種方法,一種是直接在notebook就新建...