机器学习笔记(2)相关代码

Model Representation代码展示

import numpy as np
import matplotlib.pyplot as plt

# plt.style.use('./deeplearning.mplstyle')
# 训练集
x_train = np.array([1.0, 2.0])
y_train = np.array([300.0, 500.0])
print(f"x_train = {x_train}")
print(f"y_train = {y_train}")

print(f"x_train.shape:{x_train.shape}")
m = x_train.shape[0]
print(f"Number of training examples is:{m}")

m = len(x_train)
print(f"Number of training examples is:{m}")

x_i = x_train[0]
y_i = y_train[0]
print(f"x^(i)={x_i},y^(i)={y_i}")

# 散点图
plt.scatter(x_train, y_train)
plt.title("Housing Price")
plt.show()


# 计算预测值
def compute_model_output(x, w, b):
    m = x.shape[0]
    f_wb = np.zeros(m)
    print(f_wb)
    for i in range(m):
        f_wb[i] = w * x[i] + b

    return f_wb


# 给出w和b的值
w = 100
b = 100
tmp_f_wb = compute_model_output(x_train, w, b)
print(tmp_f_wb)

# 画出预测值的直线
plt.plot(x_train, tmp_f_wb, c='red', label='Our Prediction')
# 真实值的散点图
plt.scatter(x_train, y_train, label='Actual Values')
plt.title("Housing Price")
plt.xlabel('x_train')
plt.ylabel('y_train')
plt.legend()
plt.show()

# 改变w和b的值
w = 200
b = 100
x_i = 1.2
cost = w * x_i + b
print(f"预测的价格是:{cost}")


# x_train = [1. 2.]
# y_train = [300. 500.]
# x_train.shape:(2,)
# Number of training examples is:2
# Number of training examples is:2
# x^(i)=1.0,y^(i)=300.0
# [0. 0.]
# [200. 300.]
# 预测的价格是:340.0

输出

在这里插入图片描述

Cost Function代码

import numpy as np
import matplotlib.pyplot as plt

x_train = np.array([1.0, 2.0])
y_train = np.array([300.0, 500.0])


# 计算代价函数
def compute_cost(x, y, w, b):
    m = x.shape[0]
    cost_sum = 0
    for i in range(m):
        f_wb = w * x[i] + b
        cost = (f_wb - y[i]) ** 2
        cost_sum = cost_sum + cost
    total_cost = cost_sum/(2*m)
    return total_cost


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值