吴恩达机器学习2,如何预测值,还有出图
import matplotlib.pyplot as plt
#多个特征相差过大,容易震荡,故需要归一化操作
path = "C:/Users/10379/Desktop/线性回归/数据文件/ex1data2.txt"
data = pd.read_csv(path,header=None,names=["Size",'Bedrooms','Price'])
data = (data-data.mean())/data.std() #均值化归一操作,mean()函数对所有的值求平均值,std()函数为标准差
print(data.head())
#接下来初始化数据集变量,首先将变量从数据集中分离出来,然后转化为matrix矩阵才能相乘,theta初始化为全0的矩阵
data.insert(0, 'ones', 1) #在第0列加一列值为1,与theta0进行相乘
cols = data.shape[1] #数据的列数
x = data.iloc[:, 0 : cols-1] #分割出y矩阵
y = data.iloc[:, cols-1:cols] #分割出y矩阵
x= np.matrix(x.values)
y = np.matrix(y.values)
theta = np.matrix(np.array([0,0,0])) #多变量梯度需要三个theta,初始化为0
#定义代价函数
def computeCost(x, y, theta):
inner = np.power(((x*theta.T) - y), 2) #X*theta.T为X矩阵和theta转置矩阵相乘
return np.sum(inner) / (2*len(x))
#定义梯度下降函数
def gredientDecent(x, y, theta, alpha, iters): #alpha为学习率 iters为迭代次数
tempt = np.matrix(np.zeros(theta.shape)) #求一个与theta矩阵大小相等的全0矩阵
parameters = int(theta.ravel().shape[1]) #ravel转化为一维,返回1行的个数
cost = np.zeros(iters) #cost为iters个值的一维矩阵,仅有一行,iters列
for i in range(iters):
error = (x * theta.T) - y # 公式,外层循环中每一次theta改变
for j in range(parameters): #内层循环使用梯度下降算法改变theta的值至代价函数最小
term = np.multiply(error, x[ :, j]) #本次迭代theta值,减法项每项对应×输入矩阵中第j列
tempt[0 , j] = theta[0,j]-((alpha/len(x))*(np.sum(term))) #tempt与theta都是一行多列的二维矩阵
theta = tempt # j循环后,theta中的每个属性值都进行了改变,并保存在tempt临时变量中
cost = computeCost(x, y, theta)
return theta, cost # 梯度下降算法多次下降最终得到theta矩阵
alpha = 0.01
iters = 1500
g,cost = gredientDecent(x, y, theta, alpha, iters)
print("theta变量与最小代价")
print(g)
print(cost)
这是根据网上的已经写出来的程序,后面的预测数据和作图该怎么做呢?