吴恩达机器学习C1W2Lab06-使用Scikit-Learn进行线性回归

前言

有一个开源的、商业上可用的机器学习工具包,叫做scikit-learn。这个工具包包含了你将在本课程中使用的许多算法的实现。

目标

在本实验室你可以:

  • 利用scikit-learn实现基于正态方程的近似解线性回归

工具

您将使用scikit-learn中的函数以及matplotlib和NumPy

import numpy as np
np.set_printoptions(precision=2)
from sklearn.linear_model import LinearRegression, SGDRegressor
from sklearn.preprocessing import StandardScaler
from lab_utils_multi import  load_house_data
import matplotlib.pyplot as plt
dlblue = '#0096ff'; dlorange = '#FF9300'; dldarkred='#C00000'; dlmagenta='#FF40FF'; dlpurple='#7030A0'; 
plt.style.use('./deeplearning.mplstyle')

线性回归,闭式解

Scikit-learn具有线性回归模型,实现了封闭形式的线性回归。
让我们使用早期实验室的数据——一个1000平方英尺的房子卖了30万美元,一个2000平方英尺的房子卖了50万美元。

Size (1000 sqft)Price (1000s of dollars)
1300
2500

加载数据集

X_train = np.array([1.0, 2.0])   #features
y_train = np.array([300, 500])   #target value

创建并拟合模型

下面的代码使用scikit-learn执行回归。第一步创建一个回归对象。
第二步使用与对象相关的方法之一fit。这将执行回归,将参数拟合到输入数据。该工具包需要一个二维X矩阵。

linear_model = LinearRegression()
#X must be a 2-D Matrix
linear_model.fit(X_train.reshape(-1, 1), y_train) 

视图参数

w \mathbf{w} w b \mathbf{b} b参数在scikit-learn中被称为“系数”和“截距”。

b = linear_model.intercept_
w = linear_model.coef_
print(f"w = {w:}, b = {b:0.2f}")
print(f"'manual' prediction: f_wb = wx+b : {1200*w + b}")

做出预测

调用predict函数生成预测。

y_pred = linear_model.predict(X_train.reshape(-1, 1))

print("Prediction on training set:", y_pred)

X_test = np.array([[1200]])
print(f"Prediction for 1200 sqft house: ${linear_model.predict(X_test)[0]:0.2f}")

第二个例子是

第二个例子来自早期的一个具有多个特征的实验。最终的参数值和预测非常接近该实验室非标准化“长期”的结果。这种不正常的运行需要几个小时才能产生结果,而这几乎是瞬间的。封闭形式的解决方案在诸如此类的较小数据集上工作得很好,但在较大的数据集上可能需要计算。

封闭形式的解不需要规范化。

# load the dataset
X_train, y_train = load_house_data()
X_features = ['size(sqft)','bedrooms','floors','age']
linear_model = LinearRegression()
linear_model.fit(X_train, y_train) 
b = linear_model.intercept_
w = linear_model.coef_
print(f"w = {w:}, b = {b:0.2f}")
print(f"Prediction on training set:\n {linear_model.predict(X_train)[:4]}" )
print(f"prediction using w,b:\n {(X_train @ w + b)[:4]}")
print(f"Target values \n {y_train[:4]}")

x_house = np.array([1200, 3,1, 40]).reshape(-1,4)
x_house_predict = linear_model.predict(x_house)[0]
print(f" predicted price of a house with 1200 sqft, 3 bedrooms, 1 floor, 40 years old = ${x_house_predict*1000:0.2f}")

祝贺

在这个实验中,你:

  • 使用开源机器学习工具包scikit-learn
  • 使用该工具包中的接近形式解决方案实现线性回归
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值