Andrew Ng的machine learning课程week2编程题python实现

本文通过一个房价预测案例,介绍了如何使用Python实现线性回归,并利用梯度下降法来最小化代价函数。文中详细解释了数据预处理、成本计算及参数更新等关键步骤。
# -*- coding:utf-8 -*-
import numpy as np
import matplotlib.pylab as plt
from multiprocessing import Process

def plotData(X, y):
    plt.scatter(X, y, color='r', s=10, marker='x')
    plt.xlabel('Population of City in 10,000s')
    plt.ylabel('Profit in $10,000s')
    plt.show()

def computerCost(X, y, theta):
    m = len(y)
    h = np.dot(X, theta)  #X和theta是array类型,用点乘
    square = np.square(h - y) 
    J = 1/(2*m)*sum(square)
    return J

def gradientDescent(X, y, theta, alpha, num_iters):
    m = len(y)
    J_history = np.zeros((num_iters,1))
    for i in range(num_iters):
        theta = theta - alpha/m*(np.dot(X.T,(np.dot(X,theta))-y))
        J_history = computerCost(X, y, theta)
    return theta, J_history

if __name__ == '__main__':
    #X为txt里第一列
    X = np.loadtxt(fname='E:\python\ex1_multi\data\ex1data1.txt',dtype=float,delimiter=",",usecols=(0,))
    #y为txt里第二列
    y = np.loadtxt(fname='E:\python\ex1_multi\data\ex1data1.txt',dtype=float,delimiter=",",usecols=(1,))
    m = len(X)
    #读取的数据为1*m,转换为m*1
    X = X.reshape(m, 1)
    y = y.reshape(m, 1)
    #绘图
    plotData(X, y)
    X = np.column_stack((np.ones((m,1),dtype=int), X)) #Add a column of ones to x
    theta = np.zeros((2,1))
    iterations = 1500
    alpha = 0.01
    J = computerCost(X, y, theta) #Expected cost value (approx) 32.07
    print(J)
    J = computerCost(X, y, [[-1],[2]]) #Expected cost value (approx) 54.24
    print(J)
    theta = gradientDescent(X, y, theta, alpha, iterations)[0]
    print(theta)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值