机器学习笔记(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

输出

机器学习笔记(2)相关代码_第1张图片

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


你可能感兴趣的:(机器学习,python,人工智能)