2021-04-23


前言

这是我今年考上深圳大学研究生以来第一次写博客,今后研究的方向主要也是机器学习,所以很想用博客写下日常所学的知识。首先申明数据和代码(python)用的别人的不是原创,就是学习笔记

一、数据介绍

数据集包含两列:第一列是城市人口数量,第二列是该城市小吃店利润
数据地址链接:https://pan.baidu.com/s/1gIprExuddNljRrYF_m34Mg
提取码:qn9o

二、实验步骤

1.读入数据(我用的是anacode下面的Jypyter Notebook)

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'])

2.数据加工处理

data.insert(0, 'Ones', 1)#插入一列

在这里插入图片描述

# 初始化X和y
cols = data.shape[1]
X = data.iloc[:,:-1]#X是data里的除最后列
y = data.iloc[:,cols-1:cols]#y是data最后一列

X = np.matrix(X.values)
y = np.matrix(y.values)
theta = np.matrix(np.array([0,0]))

3.构造代价函数和梯度下降函数

在这里插入图片描述

#代价函数
def computeCost(X, y, theta):
    inner = np.power(((X * theta.T) - y), 2)
    return np.sum(inner) / (2 * len(X))
#梯度下降函数
def gradientDescent(X, y, theta, alpha, iters):
    temp = np.matrix(np.zeros(theta.shape))
    parameters = int(theta.ravel().shape[1])
    cost = np.zeros(iters)
    
    for i in range(iters):
        error = (X * theta.T) - y
        
        for j in range(parameters):
            term = np.multiply(error, X[:,j])
            temp[0,j] = theta[0,j] - ((alpha / len(X)) * np.sum(term))
            
        theta = temp
        cost[i] = computeCost(X, y, theta)
        
    return theta, cost
#这个部分实现了Ѳ的更新
#定义迭代次数和学习率
alpha = 0.01
iters = 1500

4.进行实验的最后一步

g, cost = gradientDescent(X, y, theta, alpha, iters)
#g就是最后求得的参数矩阵
x = np.linspace(data.Population.min(), data.Population.max(), 100)
f = g[0, 0] + (g[0, 1] * x)

fig, ax = plt.subplots(figsize=(12,8))
ax.plot(x, f, 'r', label='Prediction')
ax.scatter(data.Population, data.Profit, label='Traning Data')
ax.legend(loc=2)
ax.set_xlabel('Population')
ax.set_ylabel('Profit')
ax.set_title('Predicted Profit vs. Population Size')
plt.show()
#原始数据以及拟合的直线

在这里插入图片描述

拟合了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值