机器学习:模型评估与选择

介绍

在本实验中,你将熟悉机器学习常用库numpy, pandas和matplotlib,以及实现欠拟合与过拟合。

评分标准如下:

1 熟悉numpy用法

在该部分实验中,将学习和练习numpy的用法。numpy是矩阵计算工具箱。常用工具包含:创建数组(Array)和基本数学运算(Math)。

# 引入所需要的库文件
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os

%matplotlib inline

1.1 numpy创建数组

#一维数组
a = np.array([1,2,3,4])
a_random = np.random.rand(4) 

print("a=", a)
print("a_random=", a_random)

#二维数组
b = np.array([[1,2], [3,4]])
b_random = np.random.rand(2,2) 
print("b=", b)
print("b_random=", b_random)

#arange与reshape

print(np.arange(5))
print(a.reshape(2,2))

**要点 1.1:**请使用numpy中的arrange和reshape操作创建如下数组。

[[2 4 6 8 10][12 14 16 18 20][22 24 26 28 30]]

# ====================== 在这里填入代码 ======================= 

arr = np.arange(2, 31, 2)
arr = np.reshape(arr, (3, 5))

print(arr)
# ===========================================================

1.2 numpy数学运算

**要点 1.2:**给定矩阵A�和B�,编写函数实现矩阵乘法,点乘,计算矩阵A�的逆,最大特征值和对应的特征向量,并将得到的结果打印出来。

# ====================== 在这里填入代码 ======================= 
def numpy_math(A, B):
    dot_product = A * B
    matrix_product = np.dot(A, B)
    inv_A = np.linalg.inv(A)
    eigenvalues, eigenvectors = np.linalg.eig(A)
    return dot_product,matrix_product,inv_A,eigenvalues,eigenvectors
 
# ============================================================= 


A=np.random.random((3,3))
B=np.random.random((3,3))
dot_product,matrix_product,inv_A,eigenvalues,eigenvectors=numpy_math(A,B)

print("dot_product:\n",dot_product)
print()
print("matrix_product:\n",matrix_product)
print()
print("inv_A:\n",inv_A)
print()
print("eigenvalues:\n",eigenvalues)
print()
print("eigenvectors:\n",eigenvectors)

2 熟悉pandas用法

在该部分实验中,将学习和练习pandas的用法。pandas是数据分析工具箱。常用工具包含:创建和读取,数据分析。

2.1 pandas创建和读取

import pandas as pd

#创建一维series
data=[0, 0, 1,1]

index = ["1-2","3-4","5-6","7-8"]

MLtoday = pd.Series( data, index)
 
MLtoday


#创建二维dataframe

data = {'周一': [0, 0, 1,1], '周二': [0, 1, 0,0], '周三': [1, 0, 0,0], '周四': [0, 0, 0,0], '周五': [0, 1, 0,0]}

index = ["1-2","3-4","5-6","7-8"]

MLcourse = pd.DataFrame(data, index) #机器学习课表

MLcourse  

**要点 2.1**:在该部分实验中,你的任务是**编写代码读取本地的ex1data1数据集,并完成如下操作**。 提示:考虑采用pandas中的read_csv函数

  • 查看数据的尺寸。

  • 查看数据的前5条。

  • 查看数据的后5条。

  • 查看数据的随机5条。

import pandas as pd

from IPython.core.interactiveshell import InteractiveShell

InteractiveShell.ast_node_interactivity = "all"

##====================== 在这里填入代码 =======================
# 数据存储路径
data_path = 'ex1data1.txt'

# 读入相应的数据文件
data = pd.read_csv(data_path)

# 查看数据的尺寸
print('Data shape:', data.shape)

# 查看数据的前五条
print('First 5 rows:')
print(data.head())

# 查看数据的后五条
print('Last 5 rows:')
print(data.tail())

# 查看数据的随机五条
print('Random 5 rows:')
print(data.sample(5))
 
##============================================================= 

2.2 pandas数据分析

**要点 2.2**:在该部分实验中,你的任务是**编写代码针对上述MLcourse数据完成如下操作**。

  • 提取“周三”对应的列并打印。

  • 提取“1-2”对应的行并打印。

  • 增加一列为“周六”,对应的数值为[0,0,1](最后一个数值缺失)。

  • 填充表格中的缺失值为0。

import numpy as np

from IPython.core.interactiveshell import InteractiveShell

InteractiveShell.ast_node_interactivity = "all"


data = {'周一': [0, 0, 1,1], '周二': [0, 1, 0,0], '周三': [1, 0, 0,0], '周四': [0, 0, 0,0], '周五': [0, 1, 0,0]}

index = ["1-2","3-4","5-6","7-8"]

MLcourse = pd.DataFrame(data, index) #机器学习课表

MLcourse 

##====================== 在这里填入代码 =======================


# 提取“周三”对应的列并打印
print(MLcourse['周三']) 


# 提取“1-2”对应的行并打印
print(MLcourse.iloc[0])

#增加一列为“周六”,对应的数值为[0,0,1](最后一个数值缺失)。
new_row =[0,0,1,np.nan]

MLcourse['周六'] = new_row
#填充表格中的缺失值为0。
MLcourse.fillna(0, inplace=True)
MLcourse['周六'] = MLcourse['周六'].astype(int)
print(MLcourse)
##=============================================================  

3 熟悉matplotlib用法

在该部分实验中,将学习和练习matplotlib的用法。matplotlib是绘图工具箱。常用工具包含:散点图,曲线图和直方图。

3.1 matplotlib散点图

import matplotlib.pyplot as plt
import numpy as np

x = np.random.normal(size=50)
y = np.random.normal(size=50)
_ = plt.scatter(x, y,c='red')
_ = plt.xlabel("x")   
_ = plt.ylabel("y")
_ = plt.title("Random dots")   
_ = plt.xlim(-3, 2)  
_ = plt.ylim(-3, 2)
_ = plt.show()

**要点 3.1**:在该部分实验中,你的任务是**编写代码读取本地的ex1data1数据集,并画出散点图,要求横坐标为population,纵坐标为profit**。

##====================== 在这里填入代码 =======================
import pandas as pd
# 数据存储路径
data_path = 'ex1data1.txt'
# 读入相应的数据文件并画出散点图
plt.scatter(data['population'], data['profit'])
plt.xlabel('population')
plt.ylabel('profit')
plt.show()
##============================================================= 

3.2 matplotlib曲线图

x = np.linspace(-5, 5, 100)
y = np.sin(x)
_ = plt.plot(x, y,c='red')
_ = plt.xlabel("x")   
_ = plt.ylabel("y")
_ = plt.title("Curves")   
_ = plt.xlim(-5, 5)  
_ = plt.ylim(-1, 1)
_ = plt.show()

**要点 3.2:**在该部分实验中,你的任务是**编写代码读取本地的ex1data1数据集,并随机选择两个点画一条直线,要求线为红色,两点为蓝色,横坐标为population,纵坐标为profit****。

##====================== 在这里填入代码 =======================
import pandas as pd
# 数据存储路径

data_path = 'ex1data1.txt'
# 读入相应的数据文件并画出直线图
x = data[:, 0]
y = data[:, 1]
plt.scatter(x, y)
idx = np.random.choice(len(x), 2, replace=False)
x1, x2 = x[idx]
y1, y2 = y[idx]
plt.plot([x1, x2], [y1, y2], 'r')
plt.scatter([x1, x2], [y1, y2], color='b')
plt.xlabel('Population')
plt.ylabel('Profit')
plt.show()
##============================================================= 

4 欠拟合与过拟合 (Underfitting and Overfitting)

针对不同的机器学习问题,需要选择合适的模型和参数。如果模型过于简单或者参数过少,可能会导致“欠拟合”。如果模型过于复杂或者参数过多,可能会导致“过拟合”。

**要点 4:** 你的任务是**编写代码实现欠拟合,过拟合和适当拟合**,并最终分析这三种拟合的特点。

import numpy as np
import matplotlib.pyplot as plt
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score
def true_fun(X):
    return 3*np.power(X,2)

np.random.seed(0)

n_samples = 30

X_train = np.sort(np.random.uniform(-1,1,n_samples))
y_train = true_fun(X_train) + np.random.randn(n_samples) * 0.1

X_test = np.linspace(-1, 1, 100)
y_test = true_fun(X_test) + np.random.randn(len(X_test)) * 0.1

plt.figure(figsize=(8, 5))
plt.plot(X_test, true_fun(X_test), label="True function")
plt.scatter(X_train, y_train, edgecolor="b", s=20, label="Training samples")
plt.scatter(X_test, y_test, edgecolor="r", s=20, label="Testing samples")
plt.xlabel("x")
plt.ylabel("y")
plt.xlim((-1, 1))
plt.ylim((0, 2))
plt.legend(loc="best")
plt.title("True function")
plt.show()                

**要点 4.1:** 你的任务是**用直线拟合上述数据,并作图,输出经验误差和测试误差**。

##====================== 在这里填入代码 ======================= 
model = LinearRegression()
model.fit(X_train.reshape(-1, 1), y_train)
y_train_pred = model.predict(X_train.reshape(-1, 1))
y_test_pred = model.predict(X_test.reshape(-1, 1))
Train_error = np.mean((y_train_pred - y_train) ** 2)
Test_error = np.mean((y_test_pred - y_test) ** 2)
plt.figure(figsize=(8, 5))
plt.plot(X_test, true_fun(X_test), label="True function")
plt.scatter(X_train, y_train, edgecolor="b", s=20, label="Training samples")
plt.scatter(X_test, y_test, edgecolor="r", s=20, label="Testing samples")
plt.plot(X_test, y_test_pred, label="Linear regression")
plt.xlabel("x")
plt.ylabel("y")
plt.xlim((-1, 1))
plt.ylim((0, 2))
plt.legend(loc="best")
plt.title("Linear Regression")
plt.show()

print("Traing error:",Train_error)
print("Test error:",Test_error)

**要点 4.2:** 你的任务是**用15次多项式曲线拟合上述数据,并作图,输出经验误差和测试误差**。

##====================== 在这里填入代码 ======================= 

model = Pipeline([
    ("poly_features", PolynomialFeatures(degree=15)),
    ("lin_reg", LinearRegression())
])
model.fit(X_train.reshape(-1, 1), y_train)
y_train_pred = model.predict(X_train.reshape(-1, 1))
y_test_pred = model.predict(X_test.reshape(-1, 1))
Train_error = np.mean((y_train_pred - y_train) ** 2)
Test_error = np.mean((y_test_pred - y_test) ** 2)
plt.figure(figsize=(8, 5))
plt.plot(X_test, true_fun(X_test), label="True function")
plt.scatter(X_train, y_train, edgecolor="b", s=20, label="Training samples")
plt.scatter(X_test, y_test, edgecolor="r", s=20, label="Testing samples")
plt.plot(X_test, y_test_pred, label="Polynomial regression")
plt.xlabel("x")
plt.ylabel("y")
plt.xlim((-1, 1))
plt.ylim((0, 2))
plt.legend(loc="best")
plt.title("Polynomial Regression")
plt.show()
##============================================================

print("Traing error:",Train_error)
print("Test error:",Test_error)

**要点 4.3:** 你的任务是**用二次曲线拟合上述数据并作图,并作图,输出经验误差和测试误差**。

##====================== 在这里填入代码 ======================= 

model = Pipeline([
    ("poly_features", PolynomialFeatures(degree=2)),
    ("lin_reg", LinearRegression())
])
model.fit(X_train.reshape(-1, 1), y_train)
y_train_pred = model.predict(X_train.reshape(-1, 1))
y_test_pred = model.predict(X_test.reshape(-1, 1))
Train_error = np.mean((y_train_pred - y_train) ** 2)
Test_error = np.mean((y_test_pred - y_test) ** 2)
plt.figure(figsize=(8, 5))
plt.plot(X_test, true_fun(X_test), label="True function")
plt.scatter(X_train, y_train, edgecolor="b", s=20, label="Training samples")
plt.scatter(X_test, y_test, edgecolor="r", s=20, label="Testing samples")
plt.plot(X_test, y_test_pred, label="Quadratic regression")
plt.xlabel("x")
plt.ylabel("y")
plt.xlim((-1, 1))
plt.ylim((0, 2))
plt.legend(loc="best")
plt.title("Quadratic Regression")
plt.show()


##============================================================

print("Traing error:",Train_error)
print("Test error:",Test_error)

**要点 4.4:** 你的任务是**通过pandas画表格总结“欠拟合”,“过拟合”和“适当拟合”的经验误差和测试误差的特点**。

##====================== 在这里填入代码 ======================= 
import pandas as pd

# 创建一个包含每个模型的训练和测试误差的DataFrame
data = {
    "Model": ["欠拟合-直线", "过拟合-15次多项式", "适当拟合-二次曲线"],
    "Training Error": [0.9152917547287205,  0.0049855989467431855, 0.011472369099747354],
    "Testing Error": [0.8076492825625751, 10.460822878355923, 0.011484239368453848],
    "feature":["经验误差和测试误差都大,训练集上的训练效果不好","经验误差小,测试误查大,测试集上的效果不好","经验误差和测试误差都小,能够较好拟合"]
}
df = pd.DataFrame(data)

# 输出DataFrame
print(df)
##============================================================
#Table

  • 5
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值