机器学习学习记录 1.线性回归
单变量线性回归
#调用所需要的库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#读取文件
path = 'ex1data1.txt'
data = pd.read_csv(path, header=None, names=['Population', 'Profit'])#read_csv用来读取文件
data.head() #只观察前5行数据(只能读取前五行数据)
data.describe() #统计一个datafram的信息,观察一系列数据的范围、大小、波动趋势。
其中**describe()**函数功能返回值如下:
Population | Profit | |
---|---|---|
count | 总数量 | |
mean | 均值 | |
std | 标准差 | |
min | 最小值 | |
25% | 四分之一分位数 | |
50% | 二分之一分位数 | |
75% | 四分之三分位数 | |
max | 最大值 |
将数据可视化(画图)
data.plot(kind='scatter', x='Population', y='Profit', figsize=(12,8))#画散点图,x和y分别是其横纵坐标标签,figsize是其图像大小
plt.show()#展示画出的图像
代价函数
创建一个以参数 θ \theta θ为特征函数的代价函数
J ( θ ) = 1 2 m ∑ i = 1 m ( h θ ( x ( i ) ) − y ( i ) ) 2 J(\theta)=\frac{1}{2m}\sum_{i=1}^{m}(h_\theta(x^{(i)})-y^{(i)})^2 J(θ)=2m1i=1∑m(hθ(x(i))−y(i))2
其中:
h θ ( x ) = θ T X = θ 0 x 0 + θ 1 x 1 + θ 2 x 2 + . . . + θ n x n h_\theta(x)=\theta^TX=\theta_0x_0+\theta_1x_1+\theta_2x_2+...+\theta_nx_n hθ(x)=θ