吴恩达课程中,代码是用Octave写的,分为两个部分:
1、定义代价函数;
% 定义代价函数 J
function J = costFunctionJ(X, y, theta)
m = size(X, 1); % 样本量
predictions = X * theta; % 预测值
sqrErrors = (predictions - y) .^2; % 预测值与真实值的方差
J = 1/(2*m) * sum(sqrErrors); % 代价函数J
2、给X,y,theta 赋值并调用函数;
X = [1 1; 1 2; 1 3];
y = [1; 2; 3];
theta = [0; 1];
j = costFunctionJ(X, y, theta)
使用python实现的关键点在于,矩阵、向量的定义、计算都需要调用numpy的相应方法。
只要将Octave的对应语句功能用numpy方法实现即可。
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 21 16:16:12 2020
@author: weisssun
"""
import numpy as np
def costFunctionJ(X, y, theta): # 定义代价函数
m = len(X) # 样本数
predictions = np.dot(X, theta) # X 与 theta 的乘积和(点积),即预测值
print(predictions) #打印查看
sqrErrors = np.power((predictions - y), 2) # 预测值与真实值的方差
print(sqrErrors) #打印查看
J = 1/(2*m) * np.sum(sqrErrors) # 代价函数 J
return J
X = np.array([[1, 1],
[1, 2],
[1, 3]])
# 矩阵 X
y = np.array([[1],[2],[3]]) # 列向量 y,真实值
theta = np.array([[0],[1]]) # 列向量 theta,参数
J = costFunctionJ(X, y, theta)
print(J)