一个特征值
- 加载数据,将数据赋给x和y两个向量;
此处使用numpy模块对数组进行处理data = np.loadtxt(‘data1’,delimiter=’、’),此时data为包含两列数据的数组;
计算data的行数,将第一列赋给x,第二列赋给y
m = np.size(data,0)
x=data[:,0]#数据切片,取所有行的第一列,为一行数据
y=data[:,1]#去所有行的第二列,一行数据
- 画出原始数据的散点图
fig,ax = plt.subplots(1,2,figsize(20,10))
a[0].scatter(x,y,c='r',marker='x')
ax[0].plot(x, mx.dot(theta))
ax[0].set_title('Original scatterplot and Predict line')
如图:
-
代价函数
- 数据整理
theta = np.zeros(2)
mx = x.reshape((m,1))
mx = np.stack((np.ones((m,1)),mx))
my = y.reshape((m,1))- 代价函数实现
def costFunc(theta, x, y, reg=False, lamba=0.0):
m, n = x.shape#m为x的行数,n为x的列数
theta = theta.reshape((n, 1))
y = y.reshape((m, 1))#重复做事防止y没被标准化m行1列的形式
err = x.dot(theta) - y
J = 0.5*(np.sum(err*err))/m
if reg:
# the theta0 is not involed
theta = theta[1:]
regSum = np.sum(theta * theta)
J += lamba/(2.0*m)*regSum
return J 使用梯度下降法最小化代价函数
def gradient(theta, x, y, reg=False, lamda=0.0):
m, n = x.shape
theta = theta.reshape((n, 1))
y0 = y.reshape((m, 1))
y1 = x.dot(theta)
grad = ((x.T).dot(y1-y0))/m#注意x的转置,因为θ0是乘以的1,所以x是添加了1位
#列的,转置后刚好得到
if reg:
theta = np.vstack((0, theta[1:]))
grad += (lamda/m)*theta
return grad.flatten()
iters = 15000#迭代次数
alpha = 0.01#学习速率
def gradientSolve(theta, x, y, alpha, iters, reg=False, lamda=0.0):
lamda *= 1.0
alpha *= 1.0
jhistory = []
theta = theta.flatten()
while iters > 0:
deri = gradient(theta, x, y, reg, lamda)
theta = theta - alpha*deri
jhistory.append(costFunc(theta, x, y, reg, lamda))
iters -= 1
return theta, jhistory#theta为梯度下降法迭代后的最后theta值,后面为每一次迭
#代后的代价函数值,为了画图
代价函数随迭代次数的图像如图: