机器学习(二)

回归

回归是研究一组随机变量(X1,X2,X3…Xn)和另一组随机变量(Y1,Y2,Y3…Yn)之间关系的统计分析方法。分类问题预测的是样本所属的有限个类别,其预测目标是离散的,而回归问题预测的是样本的某项属性值,此属性值的取值范围可能有无限多个,其预测目标是连续的。

#coding=utf-8
import pandas as pd
import numpy as np
from sklearn.datasets import load_boston
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt


#获取数据
data=load_boston()

#设定x,y
x=data['data']
y=data['target']

#使用线性回归模型来构造模型预测数据
Linear=LinearRegression()

Linear.fit(x,y)

prey=Linear.predict(x[:20])


#绘制房价预测图
plt.figure(figsize=(10,5))

#绘制
plt.plot(prey,label='predction',linestyle='--',color='g')

plt.plot(y[:20], color='r', label='predction')

plt.show()

在这里插入图片描述
回归模型评价


print("MSE",mean_squared_error(prey,y[:20]))
print("MAE", mean_absolute_error(prey, y[:20]))
print("r2_score", r2_score(prey, y[:20]))

在这里插入图片描述

聚类

  • 聚类是指将数据集合中相似的对象分成多个类的过程,与分类不同的是,聚类的训练数据是没有类别标签的,这种没有预设标签的机器学习任务被称为非监督学习,而分类和回归这种有标签的机器学习任务称为监督学习
  • 在聚类任务中,预先并不知道有多少个类别,每个类别是什么,我们的目的只是将相似的样本归入同一类,不同的样本归入不同的类,组内的样本相似度越大,组间的样本相似度越小,聚类效果就越好

K-means

K-means聚类算法是一种迭代求解的聚类算法。K-means算法需要预先设定总类别数量K。如果类别数量设置得不够好的话,最终的聚类结果可能会不太理想。
K-means的训练思路:

  • 随机选定K个中心点
  • 将数据集中的数据根据到各中心点的距离归入不同聚类(靠近哪个中心点就归为哪一类)
  • 根据聚类结果重新计算每个聚类的中心点
  • 重复第2步~第3步,直到每个聚类的内部元素不再变化为止,最后得到的所有中心点坐标即为训练得到的模型参数

DBSCAN

DBSCAN是一种基于密度的聚类算法,不需要设置类别数量,但是需要设置类内样本的最大可接受距离,这个算法对空间样本聚类效果较好。

DBSCAN的训练思路如下:

  • 先设定好DBSCAN中的最短聚类距离eps,从数据集中任一点开始,寻找周围到此点距离小于eps的点,加入当前聚类
  • 加入新的数据点之后,再从新的数据点出发继续寻找距离小于eps的点,如此循环往复
  • 如果当前点的eps半径范围内没有未加入聚类的数据点,则跳到当前聚类外任意未被聚类的点,继续搜索新的聚类
  • 对于周围eps范围内没有任何数据点的数据,归为离群
data, label = make_blobs(n_samples=100, n_features=2, centers=3, cluster_std=1.0, center_box=(-10.0, 10.0), shuffle=True, random_state=None)
n_features :表示每一个样本有多少特征值 ,默认2
n_samples :表示样本的个数 ,默认100
centers: 是聚类中心点的个数,可以理解为label的种类数 ,默认3
random_state :是随机种子,可以固定生成的数据
cluster_std :设置每个类别的方差, 例如我们希望生成3类数据,可以将cluster_std设置为[1.0,3.0,5.0]。代表最后一类方差最大,分布的最散乱
shuffle: 是否打乱数据。默认打乱
center_box :每个簇中心随机生成时的包围框?不懂啥意思

from sklearn.datasets import make_blobs,make_moons
from sklearn.cluster import KMeans,DBSCAN

#创建数据集
data = make_blobs(centers=2)

model_km=KMeans(n_clusters=2)
model_db=DBSCAN()

x=data[0]


#使用km聚类算法来聚类
y_pred_km=model_km.fit_predict(x)
#使用db聚类算法来聚类
y_pred_bd=model_db.fit_predict(x)

markers=["x","s","^","h","*","<"]
colors=['r','g','b','y','o','tomato']
plt.subplot(121)
plt.title('KMeans')
for i,y in enumerate(y_pred_km):

    plt.scatter(x[i,0],x[i,1],marker=markers[y],color=colors[y])

#plt.scatter()函数用于生成一个scatter散点图。
plt.subplot(122)
plt.title('DBSCAN')
for i,y in enumerate(y_pred_bd):
    if y!=-1:
        plt.scatter(x[i, 0], x[i, 1], marker=markers[y], color=colors[y])
    else:
        plt.scatter(x[i, 0], x[i, 1], marker=markers[y], color='black')
plt.show()

在这里插入图片描述

降维

降维算法即将高维数据投射到低维空间,并尽可能地保留最多的信息。这类算法及可以用于去除高维数据的冗余信息,也可以用于数据的可视化。比如我们可以使用降维算法将鸢尾花数据集的数据分布情况直观地展示出来。

PCA降维

#coding=utf-8
from sklearn.datasets import load_iris
from sklearn.decomposition import PCA
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

data=load_iris()

#获取x,y值
x=data['data']
y=data['target']

#使用PCA降维
pca = PCA(n_components=2)  #加载pca算法,设置降维后主成分数目为2
rex = pca.fit_transform(x)  #对原始数据进行降维,保存在reduced_x中
markers=["x","s","^","h","*","<"]
colors=['r','g','b','y','o','tomato']
fig=plt.figure()
plt.subplot(121)
# ax=Axes3D(fig)#转变为三维图像

for i,item in enumerate(rex):
    plt.scatter(item[0],item[1],color=colors[y[i]],marker=markers[y[i]])

plt.show()

在这里插入图片描述

LDA降维

from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA

lda=LDA(n_components=2)
x_2d=lda.fit_transform(x,y)
plt.figure()
for i,item in enumerate(x_2d):
    plt.scatter(item[0], item[1], color=colors[y[i]], marker=markers[y[i]])
plt.show()

在这里插入图片描述

模型验证

过拟合的三种情况:

  1. 数据有噪声
  2. 数据集过小
  3. 模型太复杂
    留出验证法的操作方式是在训练之前,从总数据集中按一定规则(或随机)抽取一部分数据作为验证数据集,然后在模型训练完成之后,在验证集上的效果很差,就说明模型出现了过拟合现象
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn import linear_model
from sklearn.preprocessing import PolynomialFeatures
from sklearn.metrics import r2_score

#样本数量
n_sample=20
x=np.array([i+2 for i in range(n_sample)]) *4


#使用x生成y并加上噪音点
# np.random.randint(low, high=None, size=None, dtype='l')

# low—–为最小值
# high—-为最大值
# size—–为数组维度大小
# dtype—为数据类型,默认的数据类型是np.int。

y=3*np.log(x)+np.random.randint(0,3,n_sample)
y1 = 3 * np.log(x)
# plt.scatter(x,y)
# plt.scatter(x,y1,color='r')
# plt.legend(['change', 'real'], loc='upper left')
# plt.show()

# np.argsort(a, axis=-1, kind='quicksort', order=None)
# 函数功能:将a中的元素从小到大排列,提取其在排列前对应的index(索引)输出。
#使用有噪音点的数据来预估
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3)
#编写测试函数
def poly_fit(degree):
    poly=PolynomialFeatures(degree)
    #将训练集转为为二项式
    x_poly_train=poly.fit_transform(x_train.reshape(-1,1))
    #将测试集转为为二项式
    x_poly_test=poly.fit_transform(x_test.reshape(-1,1))
    #建立回归算法
    regress=linear_model.LinearRegression()
    #使用回归算法建立模型
    regress.fit(x_poly_train,y_train.reshape(-1,1))
    #使用训练好的模型预测
    y_train_pred=regress.predict(x_poly_train)
    #将原始训练数据排序
    sorted_index=np.argsort(x_train)
    plt.subplot(121)
    #将预测数据和训练数据画成直线
    plt.plot(x_train[sorted_index],y_train_pred[sorted_index])
    #将正真实数据显示出来
    plt.scatter(x_train,y_train)
    plt.legend(['predction', 'real'], loc='upper left')

    #使用测试集来预测
    y_test_pred=regress.predict(x_poly_test)
    #将数据排序
    sorted_test_index=np.argsort(x_test)
    #将数据显示出来
    plt.subplot(122)
    plt.plot(x_test[sorted_test_index],y_test_pred[sorted_test_index])
    plt.scatter(x_test,y_test)
    plt.legend(['predction', 'real'], loc='upper left')
    
    #计算r2
    print("Train R2 score",r2_score(y_train_pred,y_train))
    print("Test R2 score",r2_score(y_test_pred,y_test))

poly_fit(2)
plt.show()

在这里插入图片描述

模型持久化

训练好一个机器学习模型后,就会希望以后不用重复训练过程也可以使用这个模型,可以使用模型持久化工具保存模型

joblib


import joblib
x=[[0,0],[1,1]]
y=[0,1]

regress=linear_model.LinearRegression()

regress.fit(x,y)
#保存模型
joblib.dump(regress,"lr.m")

clf=joblib.load("lr.m")
print(clf.predict(x))

pickle


import pickle
x=[[0,0],[1,1]]
y=[0,1]

regress=linear_model.LinearRegression()

regress.fit(x,y)
#保存模型
s=pickle.dumps(regress)
f=open("lr.pkl","wb")
f.write(s)
f.close()

#打开加载模型
g=open("lr.pkl","rb")
w=g.read()
clf=pickle.loads(w)
print(clf.predict(x))

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值