【机器学习】吴恩达 1.0单变量线性回归

import numpy as np
import pandas as pd
import scipy.io as sio
import matplotlib.pyplot as plt
from sklearn.svm import SVC
data=pd.read_csv('ex1data1.txt',names=['Population','Profit'])
data.head()#默认5行
data=pd.DataFrame(data)

#特征归一化 (原始数据-平均值)/标准差
data=(data-data.mean())/data.std()


#代价函数
def computeCost(X,y,theta):
    inner=np.power(((X*theta.T)-y),2)
    return np.sum(inner)/(2*len(X))

#原始数据集表上增加第0列,总共为三列
data.insert(0,'Ones',1)
cols=data.shape[1] #读列数,此时cols=3
X=data.iloc[:,:-1]#所有行,除了最后一列,此时X中有ones列和population列,72*2
y=data.iloc[:,cols-1:cols]#最后一列,等同于[2:3]
X=np.matrix(X.values)#转换为矩阵 72*2
y=np.matrix(y.values)# 72*1
theta=np.matrix(np.array([0,0])) #1*2
print("初试theta值的代价为:")
print(computeCost(X,y,theta))

#梯度下降
def gradientDecent(X,y,theta,alpha,iters):#iters迭代次数
    tempt=np.matrix(np.zeros(theta.shape))#创建一个大小为theta的全零矩阵
    parameters=int(theta.ravel().shape[1])#parameters获取的是theta的值的个数
    cost=np.zeros(iters)#初始化代价
    for i in range(iters):
        error=(X*theta.T)-y
        for j in range(parameters):#将每个theta[j]的值下降一次
            term=np.multiply(error,X[:,j])#error与X的第J列的对应向量分别相乘,增加的一列用于与1相乘
            tempt[0,j]=theta[0,j]-((alpha/len(X))*(np.sum(term)))
        cost[i]=computeCost(X,y,tempt)#计算第i次迭代时的theta的代价
        theta=tempt#每次循环下降一次
    return theta,cost

alpha=0.01
iters=1500
g,cost=gradientDecent(X,y,theta,alpha,iters)
print("theta:")
print(g)
print(cost)

predict1=(1,7)*g.T
print("预测值1:")
print(predict1)

x=np.linspace(data.Population.min(),data.Population.max(),100)#等差数列,100个点
f=g[0,0]+(g[0,1]*x)#假设函数
fig,ax=plt.subplots(figsize=(8,6))
ax.plot(x,f,'r',label='Prediction')#红线
ax.scatter(data.Population,data.Profit,label='training data')#散点图
ax.legend(loc=2)#第二象限 左上角
ax.set_xlabel('Population')
ax.set_ylabel('Profit')
ax.set_title("Predicted Profit vs. Population Size")
plt.show()
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
data=pd.read_csv('ex1data2.txt',names=['size','bedrooms','price'])
data.head()#默认5行
#data=pd.DataFrame(data)

#特征归一化 (原始数据-平均值)/标准差
data=(data-data.mean())/data.std()


#代价函数
def computeCost(X,y,theta):
    inner=np.power(((X*theta.T)-y),2)
    return np.sum(inner)/(2*len(X))

#原始数据集表上增加第0列,总共为三列
data.insert(0,'ones',1)
cols=data.shape[1] #读列数
X=data.iloc[:,:-1]#所有行,除了最后一列
y=data.iloc[:,cols-1:cols]#最后一列
X=np.matrix(X.values)
y=np.matrix(y.values)
theta=np.matrix(np.array([0,0,0]))#多元与单元


#梯度下降
def gradientDecent(X,y,theta,alpha,iters):#iters迭代次数
    tempt=np.matrix(np.zeros(theta.shape))#创建一个大小为theta的全零矩阵
    parameters=int(theta.ravel().shape[1])#parameters获取的是theta的值的个数
    cost=np.zeros(iters)#初始化代价
    for i in range(iters):
        error=(X*theta.T)-y
        for j in range(parameters):#将每个theta[j]的值下降一次
            term=np.multiply(error,X[:,j])#error与X的第J列的对应向量分别相乘,增加的一列用于与1相乘
            tempt[0,j]=theta[0,j]-((alpha/len(X))*(np.sum(term)))
        cost[i]=computeCost(X,y,tempt)#计算第i次迭代时的theta的代价
        theta=tempt#每次循环下降一次
    return theta,cost

alpha=0.01
iters=1500
g,cost=gradientDecent(X,y,theta,alpha,iters)
print("theta变量与最小代价")
print(g)
print(cost)

fig=plt.figure()
x=np.linspace(data.size.min(),data.size.max(),100)#等差数列,100个点
y=np.linspace(data.bedrooms.min(),data.bedrooms.max(),100)
f=g[0,0]+(g[0,1]*x)+(g[0,2]*y)#假设函数
ax=Axes3D(fig)
ax.scatter3D(x,y,f)
ax.plot3D(x,y,f,'gray')
plt.show()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值