吴恩达机器学习第一周作业

吴恩达机器学习第一周作业

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt


data = np.loadtxt('ex1data1.txt', delimiter=',')
x = data[:, 0]
y = data[:, 1]
m = y.size
y = y.reshape(-1, 1)

plt.figure(0)
fg1 = plt.scatter(x, y, marker='x', c='r')
plt.xlabel('profit in $10,000s')
plt.ylabel('Population of City in 10,000s')


# 正规方程法
# x = np.column_stack((np.ones([m, 1]), x))
# theta = np.linalg.inv(x.T@x)@x.T@y
# print(theta)


# 代价函数
def computerCost(X, Y, Theta):
    inner = X @ Theta.T - Y
    J = np.sum(inner * inner) / (2 * Y.size)
    return J


# 梯度下降法
x = np.column_stack((np.ones([m, 1]), x))
theta = np.zeros([1, 2])
alpha = 0.01
epoch = 1000


# 梯度下降函数
def gradientDescent(X, Y, Theta, Alpha=0.01, Epoch=1000):
    Cost = np.zeros([Epoch, 1])
    for i in range(Epoch):
        inner = X @ Theta.T - Y
        for j in range(Theta.size):
            Xg = X[:, j].reshape(-1, 1)
            inner = inner * Xg
            Theta[0, j] = Theta[0, j] - (Alpha/m) * np.sum(inner)
        Cost[i] = computerCost(X, Y, Theta)
    return Cost, Theta


cost, theta = gradientDescent(x, y, theta, alpha, epoch)
plt.figure(0)
x2 = np.linspace(x[:, 1].min(), x[:, 1].max(), 100)
y2 = theta[0, 0] + theta[0, 1] * x2
fg2 = plt.plot(x2, y2)
plt.show()

在这里插入图片描述

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值