正规方程有点简单,用TensorFlow有点杀鸡用牛刀。核心就是记住下面的公式
Python代码如下
import numpy as np
import pandas as pd
def readData(path, name=[]):
# 读取数据
data = pd.read_csv(path, names=name)
# 数据归一化
data = (data - data.mean()) / data.std()
# x_0 = 1
data.insert(0, 'First', 1)
return data
def costFunction(theta, X, Y):
return (1 / 2) * (X.dot(theta) - Y.T).T * (X.dot(theta) - Y.T)
def normalFunction(data):
X = np.matrix(data.iloc[:, 0:-1].values)
Y = np.matrix(data.iloc[:, -1].values)
# 利用正规方程求解参数
theta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(Y.T)
return theta, costFunction(theta, X, Y)
if __name__ == "__main__":
data = readData('D:\Machine Learning\wu\ex1\ex1data2.txt', ['Size', 'Bedrooms', 'Price'])
theta, costValue = normalFunction(data)
print(theta)