機(jī)器學(xué)習(xí)與深度學(xué)習(xí)——自定義函數(shù)進(jìn)行線性回歸模型分析(波士頓房價(jià))
目的與要求
1、通過自定義函數(shù)進(jìn)行線性回歸模型對boston數(shù)據(jù)集前兩個(gè)維度的數(shù)據(jù)進(jìn)行模型訓(xùn)練并畫出SSE和Epoch曲線圖,畫出真實(shí)值和預(yù)測值的散點(diǎn)圖,最后進(jìn)行二維和三維度可視化展示數(shù)據(jù)區(qū)域。
2、通過自定義函數(shù)進(jìn)行線性回歸模型對boston數(shù)據(jù)集前四個(gè)維度的數(shù)據(jù)進(jìn)行模型訓(xùn)練并畫出SSE和Epoch曲線圖,畫出真實(shí)值和預(yù)測值的散點(diǎn)圖,最后進(jìn)行可視化展示數(shù)據(jù)區(qū)域。
步驟
1、先載入boston數(shù)據(jù)集 Load Iris data
2、分離訓(xùn)練集和設(shè)置測試集split train and test sets
3、對數(shù)據(jù)進(jìn)行標(biāo)準(zhǔn)化處理Normalize the data
4、自定義損失函數(shù)
5、使用梯度下降算法訓(xùn)練線性回歸模型
6、初始化模型參數(shù)
7、訓(xùn)練模型
8、對訓(xùn)練集和新數(shù)據(jù)進(jìn)行預(yù)測
9、畫出SSE和Epoch折線圖
10、畫出真實(shí)值和預(yù)測值的散點(diǎn)圖
11、進(jìn)行可視化
代碼
1、通過自定義函數(shù)進(jìn)行線性回歸模型對boston數(shù)據(jù)集前兩個(gè)維度的數(shù)據(jù)進(jìn)行模型訓(xùn)練并畫出SSE和Epoch曲線圖,畫出真實(shí)值和預(yù)測值的散點(diǎn)圖,最后進(jìn)行二維和三維度可視化展示數(shù)據(jù)區(qū)域。
#引入所需庫
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# 讀取數(shù)據(jù)
data_url = "http://lib.stat.cmu.edu/datasets/boston"
raw_df = pd.read_csv(data_url, sep="\s+", skiprows=22, header=None)
data = np.hstack([raw_df.values[::2, :], raw_df.values[1::2, :2]])
target = raw_df.values[1::2, 2]
x = data[:,:2] # 只使用前兩個(gè)特征進(jìn)行線性回歸
y = target.reshape(-1,1)
#自定義函數(shù)進(jìn)行線性回歸
def compute_cost(X, y, theta):
"""
計(jì)算損失函數(shù)(平均誤差平方和)
"""
m = len(y)
predictions = X.dot(theta)
cost = (1/(2*m)) * np.sum(np.square(predictions-y))
return cost
def gradient_descent(X, y, theta, learning_rate, num_epochs):
"""
使用梯度下降算法訓(xùn)練線性回歸模型
"""
m = len(y)
cost_history = np.zeros(num_epochs)
theta_history = np.zeros((num_epochs, theta.shape[0]))
for epoch in range(num_epochs):
predictions = X.dot(theta)
errors = predictions - y
theta = theta - (1/m) * learning_rate * (X.T.dot(errors))
cost = compute_cost(X, y, theta)
cost_history[epoch] = cost
theta_history[epoch,:] = theta.T
return theta, cost_history, theta_history
#對輸入特征進(jìn)行標(biāo)準(zhǔn)化
mean_x = np.mean(x, axis=0) #求出每一列特征的平均值
std_x = np.std(x, axis=0) #求出每一列特征的標(biāo)準(zhǔn)差。
x = (x - mean_x) / std_x #將每一列特征進(jìn)行標(biāo)準(zhǔn)化,即先將原始數(shù)據(jù)減去該列的平均值,再除以該列的標(biāo)準(zhǔn)差,這樣就能得到均值為0,標(biāo)準(zhǔn)差為1的特征
X = np.hstack([np.ones((len(x),1)), x]) # 添加一列全為1的特征,表示截距項(xiàng)
# 初始化模型參數(shù)
theta = np.zeros((X.shape[1],1))
# 訓(xùn)練模型
learning_rate = 0.01
num_epochs = 1000
theta, cost_history, theta_history = gradient_descent(X, y, theta, learning_rate, num_epochs)
# 對訓(xùn)練集進(jìn)行預(yù)測
predictions = X.dot(theta)
predictions[:10]
# 對新數(shù)據(jù)進(jìn)行預(yù)處理
new_data = np.array([[0.01, 18]]) # 假設(shè)新數(shù)據(jù)是 CRIM=0.01,ZN=18
new_data = (new_data - mean_x) / std_x
new_X = np.hstack([np.ones((1,1)), new_data]) # 添加截距項(xiàng)
# 使用訓(xùn)練出的模型參數(shù)進(jìn)行預(yù)測
new_predictions = new_X.dot(theta)
new_predictions
print('預(yù)測的房價(jià)為:${:.7f}'.format(float(new_predictions)*1000))
# 畫出Epoch曲線圖
#將每個(gè)特征在訓(xùn)練過程中更新的參數(shù)θ的變化情況繪制出來,可以看到不同特征在訓(xùn)練過程中的變化趨勢
plt.figure()
plt.plot(range(num_epochs), theta_history[:, 0], label='theta0')
plt.plot(range(num_epochs), theta_history[:, 1], label='theta1')
plt.show()
# 畫出SSE和Epoch折線圖
plt.figure(figsize=(10,5))
plt.plot(range(num_epochs), cost_history)
plt.xlabel('Epoch')
plt.ylabel('SSE')
plt.title('SSE vs. Epoch')
plt.show()
# 畫出預(yù)測值與真實(shí)值的比較圖
plt.figure(figsize=(10,5))
plt.scatter(y, predictions)
plt.xlabel('True Values')
plt.ylabel('Predictions')
plt.title('True Values vs. Predictions')
plt.show()
# 畫出數(shù)據(jù)二維可視化圖
plt.figure(figsize=(10,5))
plt.scatter(x[:,0], y)
plt.xlabel('CRIM')
plt.ylabel('MEDV')
plt.title('CRIM vs. MEDV')
plt.show()
# 畫出數(shù)據(jù)三維可視化圖
fig = plt.figure(figsize=(10,5))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x[:,0], x[:,1], y)
ax.set_xlabel('CRIM')
ax.set_ylabel('ZN')
ax.set_zlabel('MEDV')
ax.set_title('CRIM-ZN vs. MEDV')
plt.show()
Jupyter截圖:
1、通過自定義函數(shù)進(jìn)行線性回歸模型對boston數(shù)據(jù)集前四個(gè)維度的數(shù)據(jù)進(jìn)行模型訓(xùn)練并畫出SSE和Epoch曲線圖,畫出真實(shí)值和預(yù)測值的散點(diǎn)圖,最后進(jìn)行可視化展示數(shù)據(jù)區(qū)域。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#載入數(shù)據(jù)
data_url = "http://lib.stat.cmu.edu/datasets/boston"
raw_df = pd.read_csv(data_url, sep="\s+", skiprows=22, header=None)
data = np.hstack([raw_df.values[::2, :], raw_df.values[1::2, :2]])
target = raw_df.values[1::2, 2]
x = data[:,:2]#前2個(gè)維度
y = target
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# 讀取數(shù)據(jù)
data_url = "http://lib.stat.cmu.edu/datasets/boston"
raw_df = pd.read_csv(data_url, sep="\s+", skiprows=22, header=None)
data = np.hstack([raw_df.values[::2, :], raw_df.values[1::2, :2]])
target = raw_df.values[1::2, 2]
x = data[:,:4] #
y = target.reshape(-1,1)
#自定義函數(shù)進(jìn)行線性回歸
def compute_cost(X, y, theta):
"""
計(jì)算損失函數(shù)(平均誤差平方和)
"""
m = len(y)
predictions = X.dot(theta)
cost = (1/(2*m)) * np.sum(np.square(predictions-y))
return cost
def gradient_descent(X, y, theta, learning_rate, num_epochs):
"""
使用梯度下降算法訓(xùn)練線性回歸模型
"""
m = len(y)
cost_history = np.zeros(num_epochs)
theta_history = np.zeros((num_epochs, theta.shape[0]))
for epoch in range(num_epochs):
predictions = X.dot(theta)
errors = predictions - y
theta = theta - (1/m) * learning_rate * (X.T.dot(errors))
cost = compute_cost(X, y, theta)
cost_history[epoch] = cost
theta_history[epoch,:] = theta.T
return theta, cost_history, theta_history
#對輸入特征進(jìn)行標(biāo)準(zhǔn)化
mean_x = np.mean(x, axis=0) #求出每一列特征的平均值
std_x = np.std(x, axis=0) #求出每一列特征的標(biāo)準(zhǔn)差。
x = (x - mean_x) / std_x #將每一列特征進(jìn)行標(biāo)準(zhǔn)化,即先將原始數(shù)據(jù)減去該列的平均值,再除以該列的標(biāo)準(zhǔn)差,這樣就能得到均值為0,標(biāo)準(zhǔn)差為1的特征
X = np.hstack([np.ones((len(x),1)), x]) # 添加一列全為1的特征,表示截距項(xiàng)
# 初始化模型參數(shù)
theta = np.zeros((X.shape[1],1))
# 訓(xùn)練模型
learning_rate = 0.01
num_epochs = 1000
theta, cost_history, theta_history = gradient_descent(X, y, theta, learning_rate, num_epochs)
# 畫出Epoch曲線圖
#將每個(gè)特征在訓(xùn)練過程中更新的參數(shù)θ的變化情況繪制出來,可以看到不同特征在訓(xùn)練過程中的變化趨勢
plt.figure()
plt.plot(range(num_epochs), theta_history[:, 0], label='theta0')
plt.plot(range(num_epochs), theta_history[:, 1], label='theta1')
plt.plot(range(num_epochs), theta_history[:, 2], label='theta2')
plt.plot(range(num_epochs), theta_history[:, 3], label='theta3')
plt.show()
# 對訓(xùn)練集進(jìn)行預(yù)測
predictions = X.dot(theta)
predictions[:10]
# 對新數(shù)據(jù)進(jìn)行預(yù)處理
new_data = np.array([[ 0.01,18,2.310,0]]) # 假設(shè)新數(shù)據(jù)是 CRIM=0.01,ZN=18,INDUS=2.310,CHAS=0
new_data = (new_data - mean_x) / std_x
new_X = np.hstack([np.ones((1,1)), new_data]) # 添加截距項(xiàng)
# 使用訓(xùn)練出的模型參數(shù)進(jìn)行預(yù)測
new_predictions = new_X.dot(theta)
new_predictions
print('預(yù)測的房價(jià)為:${:.7f}'.format(float(new_predictions)*1000))
# 畫出SSE曲線圖
plt.figure()
plt.plot(range(num_epochs), cost_history)
plt.xlabel('Epoch')
plt.ylabel('SSE')
plt.title('SSE vs. Epoch')
plt.show()
# 畫出預(yù)測值與真實(shí)值的比較圖
plt.figure(figsize=(10,5))
plt.scatter(y, predictions)
plt.xlabel('True Values')
plt.ylabel('Predictions')
plt.title('True Values vs. Predictions')
plt.show()
# 可視化前四個(gè)維度的數(shù)據(jù)
#前四個(gè)維度數(shù)據(jù)的可視化圖像。其中橫軸為第一個(gè)特征CRIM,縱軸為第二個(gè)特征ZN,縱軸為第三個(gè)特征INDUS,點(diǎn)的顏色為第四個(gè)特征的值。
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x[:, 0], x[:, 1], x[:, 2], c=x[:, 3], cmap='cool')
ax.set_xlabel('CRIM')
ax.set_ylabel('ZN')
ax.set_zlabel('INDUS')
plt.title('Boston Housing Data')
plt.show()
Jupyter截圖:
部分解析:
1、通過自定義函數(shù)進(jìn)行線性回歸模型對boston數(shù)據(jù)集前兩個(gè)維度的數(shù)據(jù)進(jìn)行模型訓(xùn)練并畫出SSE和Epoch曲線圖,畫出真實(shí)值和預(yù)測值的散點(diǎn)圖,最后進(jìn)行二維和三維度可視化展示數(shù)據(jù)區(qū)域。文章來源:http://www.zghlxwxcb.cn/news/detail-538094.html
畫出SSE(誤差平方和)隨Epoch(迭代次數(shù))的變化曲線圖,用來評估模型訓(xùn)練的效果。在每個(gè)Epoch,模型都會計(jì)算一次預(yù)測值并計(jì)算預(yù)測值與實(shí)際值之間的誤差(即損失),然后通過梯度下降算法更新模型參數(shù),使得下一次預(yù)測的誤差更小。隨著Epoch的增加,SSE的值會逐漸減小,直到收斂到一個(gè)最小值。
2、通過自定義函數(shù)進(jìn)行線性回歸模型對boston數(shù)據(jù)集前四個(gè)維度的數(shù)據(jù)進(jìn)行模型訓(xùn)練并畫出SSE和Epoch曲線圖,畫出真實(shí)值和預(yù)測值的散點(diǎn)圖,最后進(jìn)行可視化展示數(shù)據(jù)區(qū)域。
畫出SSE(誤差平方和)隨Epoch(迭代次數(shù))的變化曲線圖,用來評估模型訓(xùn)練的效果。在每個(gè)Epoch,模型都會計(jì)算一次預(yù)測值并計(jì)算預(yù)測值與實(shí)際值之間的誤差(即損失),然后通過梯度下降算法更新模型參數(shù),使得下一次預(yù)測的誤差更小。隨著Epoch的增加,SSE的值會逐漸減小,直到收斂到一個(gè)最小值。
使用梯度下降算法訓(xùn)練線性回歸模型的基本思路是:先隨機(jī)初始化模型參數(shù)θ,然后通過迭代調(diào)整參數(shù)θ,使得損失函數(shù)的值盡量小。模型訓(xùn)練完成后,我們可以用訓(xùn)練好的模型對新的數(shù)據(jù)進(jìn)行預(yù)測。文章來源地址http://www.zghlxwxcb.cn/news/detail-538094.html
到了這里,關(guān)于機(jī)器學(xué)習(xí)與深度學(xué)習(xí)——自定義函數(shù)進(jìn)行線性回歸模型的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!