吴恩达--机器学习--单变量线性回归实例

1.模块用法表格:

用法名描述
data.head(n)n代表显示data数据的前n行
np.power(a, b)a的b次方
data.insert(a, b, c)a表示插入到data中第a+1列,b表示插入列的名称,c表示插入元素的值
ravel()返回原始数据的视图或者副本,只有在参数order = ‘F’时返回副本;
data.linspace(x, y, z)x为起始位置,y为终止位置,z为把y-x平均分为z份,即x的长度

2.问题:需要根据城市人口数量,预测开小吃店的利润 数据在ex1data1.txt里,第一列是城市人口数量,第二列是该城市小吃店利润。
示例代码:

# -*- coding: utf-8 -*-
"""
Created on Tue Aug  4 09:55:20 2020

@author: X
"""

#库与模块引入
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#坐标图中显示中文
plt.rcParams['font.sans-serif']=['SimHei'] #显示中文标签
plt.rcParams['font.serif'] = ['KaiTi']
plt.rcParams['axes.unicode_minus'] = False
#1.简单练习:输出5*5单位矩阵
A = np.eye(5)
print(A)
#2.单变量线性回归
#问题描述:根据城市人口数量,预测小吃店得利润。数据第一列是城市人口数量,第二列是该城市小吃店利润

#读入数据并显示数据:
path = r'C:\Users\X\Desktop\机器学习方法\吴恩达学习笔记\单变量线性回归\ex1data1.txt'
data = pd.read_csv(path, header = None, names = ['Population', 'Profit'])
#data.head(n)中n代表显示data数据的前n行

#显示图形:
data.plot(kind = 'scatter', x = 'Population', y = 'Profit', figsize = (12, 8))
#plt.show()

#梯度下降算法
#这个部分你需要在现有数据集上,训练线性回归的参数θ
#使用约定公式
def computerCost(X, y, theta):
    #np.power(a, b)为a的b次方
    inner = np.power(((X * theta.T) - y), 2)
    return np.sum(inner) / (2 * len(X))

#数据前面读取完毕,现在加入一列x,用来更新θ,θ初始化为0,学习率初始化为0.01,迭代次数为1500次
#data.insert(a, b, c)中a表示插入到data中第a+1列,b表示插入列的名称,c表示插入元素的值
data.insert(0, 'Ones', 1)


#针对于computerCost函数中形参的取值,对data中训练集进行初始化
cols = data.shape[1]

#data.iloc[]用来提取data数据中的对应数据
X = data.iloc[:,:-1]#X是data里除最后一列
y = data.iloc[:, cols - 1: cols]


#代价函数是Numpy矩阵,还需要转换X和y,然后使用。首先初始化theta
#np.matrix将数组转换为矩阵
X = np.matrix(X.values)
y = np.matrix(y.values)
theta = np.matrix(np.array([0, 0]))

#计算代价函数--theta初始化为0
print(computerCost(X, y, theta))

#梯度下降算法

def gradientDescent(X, y, alpha, iters):
    theta = np.matrix(np.array([0, 0]))
    temp = np.matrix(np.zeros(theta.shape))
    #ravel() 返回原始数据的视图或者副本,只有在参数order = ‘F’时返回副本;
    parameters = int(theta.ravel().shape[1])
    cost = np.zeros(iters)

    for i in range(iters):
        error = np.dot(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] = computerCost(X, y, theta)
        
    return theta,cost


#初始化附加变量:alpha = 0.01, iters = 1500
alpha = 0.01
iters = 1500
g, cost = gradientDescent(X, y, alpha, iters)
predict1 = np.dot([1, 3.5], g.T)
predict2 = np.dot([1, 7], g.T)
print('3.5万人利润:',float(predict1[0][0]))
print('7万人利润:',float(predict2[0][0]))

#绘制原始散点图和拟合后曲线
#data.linspace(x, y, z),x为起始位置,y为终止位置,z为把y-x平均分为z份,即x的长度
x = np.linspace(data.Population.min(), data.Population.max(), 100)
f = g[0, 0] * 1 + (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 = 'Training Data')
ax.legend(loc = 2)
ax.set_xlabel('Population/万人')
ax.set_ylabel('Profit/万元')
ax.set_title('Predicted Profit vs. Population Size')

结果展示:
3.5万人利润: 0.4519767867701763
7万人利润: 4.534245012944713
在这里插入图片描述
扩展:
在matplotlib.pyplot绘制的坐标图中显示中文:

#引入对应模块
import matplotlib.pyplot as plt
#坐标图中显示中文
plt.rcParams['font.sans-serif']=['SimHei'] #显示中文标签
plt.rcParams['font.serif'] = ['KaiTi']
plt.rcParams['axes.unicode_minus'] = False

矩阵乘法和数组的乘法:

import numpy as np
#产生a,b两个数组
a = np.array([1, 2], [3, 4])
b = np.array([1], [1])
#数组标量乘法
a * b
#数组乘法
np.dot(a, b)

#a,b转换为矩阵
a = np.matrix(a)
b = np.matrix(b)
#矩阵标量乘法
np.multiply(a, b)
#矩阵乘法
np.dot(a,b)
a * b
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值