import numpy as np;
import pandas as pd;
import matplotlib.pyplot as plt;
#导入文件绘制散点图
path = 'D:\python\机器学习第一次作业\ex1data1.txt';
data = pd.read_csv(path, header=None, names=['Population', 'Profit'])
#data1 = pd.read_csv(path,header=None,names=['population','profile']);
data.head();#显示前几行
data.describe()#describe() 函数可以查看数据的基本情况,包括:count 非空值数、mean 平均值、std 标准差、max 最大值、min 最小值、(25%、50%、75%)分位数等。
data.plot(kind='scatter', x='Population', y='Profit', figsize=(12,8))
plt.show()
def computeCost(X, y, theta):
inner = np.power(((X * theta.T) - y), 2)
return np.sum(inner) / (2 * len(X))
data.insert(0, 'Ones', 1)
# set X (training data) and y (target variable)
cols = data.shape[1] #得到数据列数
X = data.iloc[:,0:cols-1]#X是所有行,去掉最后一列
y = data.iloc[:,cols-1:cols]#X是所有行,最后一列
X.head()
X = np.matrix(X.values)
y = np.matrix(y.values)
theta = np.matrix(np.array([0,0]))#theta初始化为0
computeCost(X, y, theta)
def gradientDescent(X,y,theta,alpha,iters): #iters是迭代次数 alpha是步长
temp = np.matrix(np.zeros(theta.shape)) #构建零值矩阵,暂存theta
parameters = int(theta.ravel().shape[1]) #ravel计算需要求解的参数个数 功能将多维数组降至一维
cost = np.zeros(iters) #构建iters个0的数组
for i in range(iters): #进行迭代
error = (X*theta.T)-y #获取差值
for j in range(parameters): #更新theta_j
term = np.multiply(error,X[:,j]) #乘以x_i 因为x_0等于1,所以这个式包含theta_0,theta_1
temp[0,j] = theta[0,j] - (alpha/len(X))*np.sum(term) #更新theta_j
theta = temp #更新全部theta值
cost[i] = computeCost(X,y,theta) #更新代价值
return theta, cost
alpha = 0.01
iters = 1000
g, cost = gradientDescent(X, y, theta, alpha, iters)
computeCost(X, y, g)
#进行绘图
x = np.linspace(data.Population.min(),data.Population.max(),100) #抽取100个样本
f = g[0,0]+(g[0,1]*x) #线性函数,利用x抽取的等距样本绘制线性直线
fig, ax = plt.subplots(figsize=(12,8)) #返回图表以及图表相关的区域,为空代表绘制区域为111--->一行一列图表,选中第一个
ax.plot(x,f,'r',label="Prediction") #绘制直线
ax.scatter(data.Population,data.Profit,label='Training Data') #绘制散点图
ax.legend(loc=4) #显示标签位置 给图加上图例 'lower right' : 4,
ax.set_xlabel("Population")
ax.set_ylabel("Profit")
ax.set_title("Predicted Profit vs Population Size")
plt.show()
#绘制代价函数
fig, ax = plt.subplots() #返回图表以及图表相关的区域,为空代表绘制区域为111--->一行一列图表,选中第一个
ax.plot(np.arange(iters),cost,'r')
ax.set_xlabel('Iterations')
ax.set_ylabel('Cost')
ax.set_title("Error vs. Training Epoch")
plt.show()
机器学习第一次作业
最新推荐文章于 2024-09-12 21:05:39 发布