机器学习(第二周多元线性回归模型代码)

多元线性回归说到底和一元线性回归并没有什么区别。所以在代码上也并没有太大的区别

# 1、导入包
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt


# 2、导入数据
path = 'D:\一些桌面玩意\python项目\吴恩达机器学习\杂七杂八\数据\多变量线性回归数据.txt'
data = pd.read_csv(path ,header = None ,name = ['areas','bedrooms','price'])
data.head()  # 检验一下


# 3、特征归一化
def normalize_feature(data):
    return (data - data.mean())/data.std()          
data = normalize_feature(data)
data.head() 
# data.mean():是data每一列的平均值。    data.std():是data每一列的标准差

data.plot.scatter('areas','price',label = 'areas')
plt.show()

data.plot.scatter('bedrooms','price',label = 'bedrooms')
plt.show()


# 4、添加全为1的列
data.insert(0,'one',1)
data.head()


# 5、构造数据集
X = data.iloc[:,0:-1]
Y = data.iloc[:,-1]


# 6、将dataframe数据结构转成数组
X = X.values
y = y.values
y = y.reshape(47,1)


# 7、构造损失函数
def daijiahanshu(X,y,theta):
    inner = np.power(X @ theta - y,2)
    return np.sum(inner)/(2*len(X))
theta = np.zeros((3,1))
cost_init = daijiahanshu(X,y,theta)
cpst_init


# 8、梯度下降函数
def tiduxiajianghanshu(X,y,theta,alpha,iters):
    costs = []

    for i in range(iters):
        theta = theta - (X.T @ (X @ theta - y)*alpha) / len(X)
        cost = daijiahanshu(X,y,theta)
        costs.append(cost)

    return theta,costs

candinate_alpha = [0.0003,0.003,0.03,0.0001,0.001,0.01]
iters = 2000


# 9、梯度函数可视化
fig,ax = plt.subplots()

for alpha in candinate_alpha:
    _,costs = tiduxiajiang(X,y,theta,alpha,iters)
    ax.plot(np.arange(iters),costs,label = alpha)
    ax.legend()

ax.set( xlabel = 'iters',
        ylabel = 'cost',
        title = 'cost vs iters')
plt.show()



你可能感兴趣的:(python,人工智能,线性回归)