吴恩达课程中,代码是用Octave写的,分为两个部分:
1、定义代价函数;
% 定义代价函数 Jfunction 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 npdef 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) # 代价函数 Jreturn JX = 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)