栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

机器学习

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

机器学习

问题陈述:将一个只有两个数据点的简单数据集——一个1000平方英尺的房子以300,000美元的价格售出,一套2000平方英尺的房子以500,000美元的价格售出。这两点将构成我们的训练集。通过这两个点拟合线性回归模型,来预测其他房屋的价格。

在这个实例中,我们定义尺寸单位是1000平方英尺,价格单位是1000美元。

1.调用相关库。numpy是一个流行的科学计算库,Matplotlib是一个流行的数据绘图库。

import numpy as np
import matplotlib.pyplot as plt
plt.style.use('./deeplearning.mplstyle')

2.创建x_train和y_train变量,数据存储在一维numpy数组中。

# x_train is the input variable (size in 1000 square feet)
# y_train is the target (price in 1000s of dollars)
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}")

3.使用m来表示训练示例的数量,numpy有一个.shape参数,x_train.shpe返回一个python元组,x_train.shape[0]是数组的长度和示例的数量。也可以使用len()函数。

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

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

 4.要访问numpy数组中的值,需要使用所需的偏移量索引数组。

i = 0 # Change this to 1 to see (x^1, y^1)

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

5.绘制数据。使用matplotlib库中的scatter()函数绘制这两个点,使用其他函数来设置要显示的标题和标签。

# Plot the data points
plt.scatter(x_train, y_train, marker='x', c='r')
# Set the title
plt.title("Housing Prices")
# Set the y-axis label
plt.ylabel('Price (in 1000s of dollars)')
# Set the x-axis label
plt.xlabel('Size (1000 sqft)')
plt.show()

 6.线性回归模型表示为

 从w=100,b=100开始尝试,之后不断调整w和b的值。

w = 100
b = 100
print(f"w: {w}")
print(f"b: {b}")

 

7. 在for循环中计算函数的输出

def compute_model_output(x, w, b):
    """
    Computes the prediction of a linear model
    Args:
      x (ndarray (m,)): Data, m examples 
      w,b (scalar)    : model parameters  
    Returns
      y (ndarray (m,)): target values
    """
    m = x.shape[0]
    f_wb = np.zeros(m)
    for i in range(m):
        f_wb[i] = w * x[i] + b
        
    return f_wb

8.调用comput_model_output函数并绘制输出。

tmp_f_wb = compute_model_output(x_train, w, b,)

# Plot our model prediction
plt.plot(x_train, tmp_f_wb, c='b',label='Our Prediction')

# Plot the data points
plt.scatter(x_train, y_train, marker='x', c='r',label='Actual Values')

# Set the title
plt.title("Housing Prices")
# Set the y-axis label
plt.ylabel('Price (in 1000s of dollars)')
# Set the x-axis label
plt.xlabel('Size (1000 sqft)')
plt.legend()
plt.show()

 9.可见,当前的参数不会产生适合数据的线,调整参数,修改参数w=200,b=100

w = 200                         
b = 100 

 10.现在可以通过模型进行预测。例如,预测一栋1200平方英尺的房子。

x_i = 1.2
cost_1200sqft = w * x_i + b    

print(f"${cost_1200sqft:.0f} thousand dollars")

 小结:线性回归建立一个模型,建立特征和目标之间的关系在上面的例子中,特征是房屋大小,目标是房价,对于简单的线性回归,模型有两个参数w和b,它们的值使用训练数据进行拟合,一旦确定了模型的参数,就可以使用该模型对新数据进行预测。

程序源码:

链接:https://pan.baidu.com/s/1lEwRRxi7vUq99d_hF01AJg 
提取码:0000

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/991057.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号