首先需要导入所需要用到的三个库:numpy、pandas、matplotlib
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
读取文件:用read _csv函数进行读取
path = r'C:\Users\噗噗噗噗了个pi\Desktop\machine learning-data\ex1data1.txt'#文件位置
data = pd.read_csv(path, header=None,names=['Population','Profit'])#获取文件
定义代价函数:
#代价函数公式
def computeCost(X, y, theta):
inner = np.power(((X * theta.T) - y), 2)
return np.sum(inner) / (2 * len(X))
print(data.head())#输出前五行的内容
data.insert(0,'Ones',1)
X*theta.T=h(theta),之所以采用theta的转置是因为矩阵运算的规则:1*n的矩阵和n*1的矩阵相乘得到预测的y值。data.insert是为了在第一列插入偏置值1
数据处理:
# 初始化X和y
cols = data.shape[1]
X = data.iloc[:,:-1]#X是data