ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

机器学习实验

2022-06-09 19:35:18  阅读:137  来源: 互联网

标签:plt 机器 score df 学习 train 实验 test import


目录

实验二 线性回归

一、实验目的

  1. 掌握数据预处理方法。
  2. 掌握线性回归模型基本形式。
  3. 掌握线性回归模型目标函数。
  4. 掌握线性回归模型性能评价指标。

二、实验内容和要求
阅读P33页案例分析1:广告费用与销售预测,代码复现。
(1)数据预处理
建立data_processing.py文件,读取Advertising.csv数据,观察前5行数据,绘制TV(作为x轴)与sales(作为y轴)散点图;绘制radio(作为x轴)与sales(作为y轴)散点图;绘制newspaper(作为x轴)与sales(作为y轴)散点图。分离输入特征x与输出y(销量),对输入特征进行去量纲,拟合数据、标准化处理,将预处理后的特征数据x与输出y输出到processed.csv文件。
data_processing.py:

#数据处理,数据读取的工具包
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']
#读取数据
dpath = "./data/"
df = pd.read_csv(dpath + "Advertising.csv")
#df.columns = ['记录号','电视广告费用', '广播广告费用', '报纸广告费用', '产品销量']
df.columns = ['ID','TV', 'radio', 'newspaper', 'sales']
#通过观察前5行,了解数据每列(特征)的概况
df.head()
df.info()
# 对数值型特征,得到每个特征的描述统计量,查看特征的大致分布
df.describe()
#散点图查看单个特征与目标之间的关系
plt.scatter(df['TV'], df['sales'])
plt.xlabel(u'电视广告费用')
plt.ylabel(u'销量')
plt.show()
plt.scatter(df['radio'], df['sales'])
plt.xlabel(u'广播广告费用')
plt.ylabel(u'销量')
plt.show()
plt.scatter(df['newspaper'], df['sales'])
plt.xlabel(u'报纸广告费用')
plt.ylabel(u'销量')
plt.show()
#%%
# 数据总体信息
df.info()
## 3. 数据标准化
# 从原始数据中分离输入特征x和输出y
y = df['sales']
X = df.drop('sales', axis = 1)
#特征名称,用于后续显示权重系数对应的特征
feat_names = X.columns
#%%
# 数据标准化
# 本数据集中3个特征的单位相同,可以不做特征缩放,不影响正则
# 但3个特征的取值范围不同,如果采用梯度下降/随机梯度下降法求解,
# 还是将所有特征的取值范围缩放到相同区间

# 分别初始化对特征和目标值的标准化器
ss_X = StandardScaler()

# 对训练数据,先调用fit方法训练模型,得到模型参数;然后对训练数据和测试数据进行transform
X = ss_X.fit_transform(X)
#%% md

## 4. 保存特征工程的结果到文件,供机器学习模型使用
#%%
fe_df = pd.DataFrame(data = X, columns = feat_names, index = df.index)
#加上标签y
fe_df["sales"] = y
#保存结果到文件
fe_df.to_csv(dpath + 'processed.csv', index=False)
#%%
fe_df.head()

(2)线性回归模型应用
建立model_train.py文件,读取processed.csv文件,随机采样20%的数据构建测试样本,其余作为训练样本。
采用最小二乘线性回归训练数据,输出训模型参数,用训练好的模型对测试样本进行预测,将测试样本的真实值与预测值相减得到残差,绘制残差与真实值散点图,观察散点图的残差分布,看是否符合模型假设,噪声为0均值的高斯噪声。
采用Lasso训练数据,加入交叉验证训练,防止模型过拟合,输出模型参数,用训练好的模型对测试样本进行预测,绘制残差与Losso参数散点图,在散点图上绘制最优参数辅助线。

# 数据处理
import numpy as np
import pandas as pd
# 使用r2_score作为回归模型性能的评价
from sklearn.metrics import r2_score
# 将数据分割训练数据与测试数据
from sklearn.model_selection import train_test_split
# 线性回归
from sklearn.linear_model import LinearRegression
# 数据可视化
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
from sklearn.linear_model import LassoCV
font_set=FontProperties(fname=r"c:\windows\fonts\simsunb.ttf",size=15)
# 显示中文
plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']
# %% md
## 2. 读取数据
# 读取数据
dpath = "./data/"
df = pd.read_csv(dpath + "processed.csv")

# 通过观察前5行,了解数据每列(特征)的概况
df.head()

## 3. 数据准备

# %%
# 从原始数据中分离输入特征x和输出y
y = df['sales']
X = df.drop('sales', axis=1)

# 特征名称,用于后续显示权重系数对应的特征
feat_names = X.columns

# %%
# 随机采样20%的数据构建测试样本,其余作为训练样本
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=33, test_size=0.2)

## 4. 最小二乘线性回归

# %%
# 1.使用默认配置初始化学习器实例
lr = LinearRegression()
# 2.用训练数据训练模型参数
lr.fit(X_train, y_train)
# 3. 用训练好的模型对测试集进行预测
y_test_pred_lr = lr.predict(X_test)
y_train_pred_lr = lr.predict(X_train)

# 性能评估,R方分数
print("The r2 score of LinearRegression on test is %f" % (r2_score(y_test, y_test_pred_lr)))
print("The r2 score of LinearRegression on train is %f" % (r2_score(y_train, y_train_pred_lr)))
# 在训练集上观察预测残差的分布,看是否符合模型假设:噪声为0均值的高斯噪声
res = y_train_pred_lr - y_train
figsize = 11, 9
plt.scatter(y_train, res)
plt.xlabel(u'真实值', fontsize=16, fontproperties=font_set)
plt.ylabel(u'残差', fontsize=16,fontproperties=font_set)
plt.show()
# 1. 设置超参数搜索范围
# Lasso可以自动确定最大的alpha,所以另一种设置alpha的方式是设置最小的alpha值(eps) 和 超参数的数目(n_alphas),
# 然后LassoCV对最小值和最大值之间在log域上均匀取值n_alphas个
# np.logspace(np.log10(alpha_max * eps), np.log10(alpha_max),num=n_alphas)[::-1]
# 2 生成LassoCV实例(默认超参数搜索范围)
lasso = LassoCV()
# 3. 训练(内含CV)
lasso.fit(X_train, y_train)
# 4. 测试
y_test_pred_lasso = lasso.predict(X_test)
y_train_pred_lasso = lasso.predict(X_train)
# 评估,使用r2_score评价模型在测试集和训练集上的性能
print("The r2 score of lasso on test is %f" % (r2_score(y_test, y_test_pred_lasso)))
print("The r2 score of lasso on train is %f" % (r2_score(y_train, y_train_pred_lasso)))
#lasso.mese_path 每次交叉验证的均方误差,随着alpha值的变化,均方误差的变化曲线
mses = np.mean(lasso.mse_path_, axis=1)
plt.plot(np.log10(lasso.alphas_), mses)
# 最佳超参数
plt.axvline(np.log10(lasso.alpha_), color='r', ls='--')
plt.xlabel('log(alpha)', fontsize=16)
plt.ylabel('MSE', fontsize=16)
plt.show()
print('alpha is:', lasso.alpha_)

实验三 Logistic回归————LR_iris.py *

一、实验目的

  1. 掌握Logistic回归模型基本形式。
  2. 掌握Logistic回归模型优化求解。
  3. 掌握分类模型性能评价指标。

二、实验内容和要求
下载鸢尾花数据集,用2维特征、二分类进行本次逻辑回归实验。
(1)数据观察与预处理
建立LR_iris.py文件,读取鸢尾花数据集iris.csv,观察前5列,了解数据每列特征的概况。绘制不同类别下特征直方图,其中不同类别不同颜色,直方图x轴为特征,y轴为该特征下样本个数,4维特征请绘制4张直方图,了解特征可分性。根据直方图情况,选取2个特征属性用于2分类,setosa(类别为0)和非setosa(类别为1),在数据集添加一列class标签列,标注类别(0或1),采用StandardScaler对函数进行数据标准化。
(2)逻辑回归应用
随机采样20%的数据构建测试样本,其余作为训练样本。设置超参数搜索范围,10折交叉验证,网格搜索进行逻辑回归模型超参数的调优。用调优后的模型对测试样本进行预测。
(3)模型评估
绘制ROC曲线图。

# %% md
## Iris数据集上用2维特征、2类分类可视化
#决策边界
#ROC曲线
#PR曲线
# %%
import pandas as pd
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
# 特征缩放:数据标准化
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import roc_curve, auc
# 将数据分割训练数据与测试数据
from sklearn.model_selection import train_test_split

from sklearn.model_selection import GridSearchCV
from sklearn.linear_model import LogisticRegression

import seaborn as sns

# 显示中文
plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']

# %%

# 读取数据
# csv文件没有列名,增加列名
# 花萼长度、宽度;花瓣长度、宽度
feat_names = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'Class']
# 请撰写读取数据的代码######################输出命名为df
dpath = "./data/"
df = pd.read_csv(dpath + "iris.csv", names=feat_names, header=None)

# 通过观察前5行,了解数据每列(特征)的概况
df.head()

# %%

# 类别提取
unique_Class = df['Class'].unique()

# %%

# 只考虑两类分类:setosa vs. non_setosa
target_map = {'Iris-setosa': 0,  # 山鸢尾
              'Iris-versicolor': 1,  # 变色鸢尾
              'Iris-virginica': 1}  # 2,弗吉尼亚鸢尾

# Use the pandas apply method to numerically encode our attrition target variable
df['Class'] = df['Class'].apply(lambda x: target_map[x])


df.head()

# %%

# 查看不同类别下特征的直方图,初步了解特征的可分性
# 3个类别的颜色
colors = ['blue', 'red', 'green']
# plot histogramdf.shape[0]=150  for (int i=0;i<5;i++)(0,1,2,3,4)
for feature in range(df.shape[1] - 1):  # (shape = 150, 5), 5-1= 4,每维特征
    plt.subplot(2, 2, feature + 1)  # subplot starts from 1 (not 0)
    for label, color in zip(range(len(unique_Class)), colors):  # 每个类别
        feat_name = df.columns[feature]
        samples = df[df['Class'] == label][feat_name]  # 该类别的所有样本
        plt.hist(samples,
                 label=unique_Class[label],
                 color=color)
    plt.xlabel(df.columns[feature])
    plt.legend()
plt.show()

# %% md

#花瓣的长度和宽度比较能区分不同类别的鸢尾

# %%
#花瓣的长度和宽度比较能区分不同类别的鸢尾,请绘制#花萼长度和宽度的与类别关系的散点图#################
# 花萼长度和宽度的散点图
plt.scatter(df['sepal-length'], df['sepal-width'], c=df['Class']);
plt.show()

# %%

# 每2维特征的散点图
pd.plotting.scatter_matrix(df, c=df['Class'], figsize=(8, 8));
plt.show()

# %%

# 从原始数据中分离输入特征x和输出y
y = df['Class']
# X = df.drop(['petal-length', 'petal-width', 'Class'], axis = 1)
# X = df[['sepal-length','sepal-length']]
X = df.iloc[:, 0:2]  # 只取前两维特征

# %%

#####请撰写特征X标准化,特征缩放的代码####################################

# 模型训练
scaler = StandardScaler()
scaler.fit(X)

# 特征缩放
X = scaler.transform(X)

# %%

# 请撰写随机采样20%的数据构建测试样本,其余作为训练样本的代码##############################
# 随机采样20%的数据构建测试样本,其余作为训练样本
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=33, test_size=0.2)
X_train.shape

# %%

# 设置超参数搜索范围
Cs = [0.1, 1, 10, 100, 1000]
tuned_parameters = dict(C=Cs)

# 生成学习器实例
lr = LogisticRegression()

# 生成GridSearchCV实例
grid = GridSearchCV(lr, tuned_parameters, cv=10, scoring='neg_log_loss', n_jobs=4)

# 训练,交叉验证对超参数调优
grid.fit(X_train, y_train)

lr_best = grid.best_estimator_

# %%

test_means = - grid.cv_results_['mean_test_score']

n_Cs = len(Cs)

plt.plot(np.log10(Cs), test_means)

# 最佳超参数
best_C = grid.best_params_['C']
plt.axvline(np.log10(best_C), color='r', ls='--')

plt.legend()
plt.xlabel('log(C)')
plt.ylabel('logloss')

plt.show()

# %%

lr_best.coef_

# %%

lr_best.intercept_

# %%

# 画分类边界
h = .02  # step size in the mesh

N, M = 500, 500  # 横纵各采样多少个值
x1_min, x2_min = X.min(axis=0) - 1
x1_max, x2_max = X.max(axis=0) + 1

t1 = np.linspace(x1_min, x1_max, N)
t2 = np.linspace(x2_min, x2_max, M)

x1, x2 = np.meshgrid(t1, t2)  # 生成网格采样点

X_test = np.stack((x1.flat, x2.flat), axis=1)  # 测试点
y_test = lr_best.predict(X_test)
# y_test = lr_best.predict_proba(X_test)  #heatmap?

y_test = y_test.reshape(x1.shape)

# %%

cm_light = mpl.colors.ListedColormap(['#A0FFA0', '#FFA0A0', '#A0A0FF'])
cm_dark = mpl.colors.ListedColormap(['g', 'r', 'b'])

plt.figure(figsize=(4, 3))
plt.pcolormesh(x1, x2, y_test, cmap=plt.cm.Paired)
plt.pcolormesh(x1, x2, y_test, cmap=cm_light)
plt.colorbar()
# Plot also the training points

plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cm_dark, marker='o', edgecolors='k')

plt.xlabel('Sepal length')
plt.ylabel('Sepal width')

# plt.xlim(xx.min(), xx.max())
# plt.ylim(yy.min(), yy.max())
plt.xticks(())
plt.yticks(())

plt.show()


# %%

# 画出分类器的决策边界
def plot_2d_separator(classifier, X, fill=False, ax=None, eps=None):
    if eps is None:
        eps = X.std() / 2.

    x1_min, x2_min = X.min(axis=0) - eps
    x1_max, x2_max = X.max(axis=0) + eps

    x1 = np.linspace(x1_min, x1_max, 500)
    x2 = np.linspace(x2_min, x2_max, 500)

    # 生成网格采样点
    X1, X2 = np.meshgrid(x1, x2)
    X_grid = np.c_[X1.ravel(), X2.ravel()]

    try:
        decision_values = classifier.decision_function(X_grid)
        levels = [0]
        fill_levels = [decision_values.min(), 0, decision_values.max()]
    except AttributeError:
        # no decision_function
        decision_values = classifier.predict_proba(X_grid)[:, 1]
        levels = [.5]
        fill_levels = [0, .5, 1]

    if ax is None:
        ax = plt.gca()
    if fill:
        ax.contourf(X1, X2, decision_values.reshape(X1.shape),
                    levels=fill_levels, colors=['blue', 'red'])
    else:
        ax.contour(X1, X2, decision_values.reshape(X1.shape), levels=levels,
                   colors="black")

    ax.set_xlim(x1_min, x1_max)
    ax.set_ylim(x2_min, x2_max)

    my_x1_ticks = np.linspace(x1_min, x1_max, 10)
    my_x2_ticks = np.linspace(x2_min, x2_max, 10)

    ax.set_xticks(my_x1_ticks)
    ax.set_yticks(my_x2_ticks)

# %%

plt.scatter(X[y == 0, 0], X[y == 0, 1],
            c='red', marker='o', s=40, label=u'变色鸢尾')

plt.scatter(X[y == 1, 0], X[y == 1, 1],
            c='blue', marker='^', s=40, label=u'非变色鸢尾')

# plt.scatter(X[:, 0], X[:, 1], c = y, cmap=cm_dark,marker='o',edgecolors='k')

plot_2d_separator(lr_best, X_test)  # plot the boundary
# plt.xlabel(df.columns[feature])
# plt.ylabel(df.columns[feature])

plt.xlabel(u'花萼长度')
plt.ylabel(u'花萼宽度')

plt.legend()
plt.show()

# %% md

## ROC曲线


def plot_roc(labels, predict_prob):
    false_positive_rate, true_positive_rate, thresholds = roc_curve(labels, predict_prob)
    roc_auc = auc(false_positive_rate, true_positive_rate)

    # plt.title('ROC')
    plt.plot(false_positive_rate, true_positive_rate, 'b', label='AUC = %0.4f' % roc_auc)

    plt.legend(loc='lower right', fontsize=16)

    plt.plot([0, 1], [0, 1], 'r--')

    plt.ylabel('TPR', fontsize=16)
    plt.xlabel('FPR', fontsize=16)
# %%

scores = lr_best.decision_function(X)

plt.figure(figsize=(6, 6))
#################请调用plot_roc函数,输出ROP曲线图##################
plot_roc(y, scores)
plt.show()

实验四 支持向量机SVM————SVM.py *

一、实验目的

  1. 掌握支持向量机基本概念。
  2. 掌握基于核方法的支持向量机模型构造。
  3. 掌握采用支持向量机解决问题的思路。

二、实验内容和要求
下载共享单车骑行量数据集,阅读P86页,案例分析2:共享单车骑行量预测,采用基于RBF的SVM模型进行本次实验。
(1)共享单车骑行量预测
阅读案例分析2,复现代码,随机采样20%的数据构建测试样本,其余作为训练样本,采用L2正则,设置模型超参数正则参数C、RBF核宽度gammma搜索范围。绘制不同参数对应模型通过交叉验证的误差分析图,如图4-12所示。输出模型在测试集上的均方根误差。

# 导入必要的工具包
# 数据读取及基本处理
import pandas as pd
import numpy as np
#模型
from sklearn.svm import SVR
from sklearn.model_selection import GridSearchCV
#模型评估
from sklearn.metrics import mean_squared_error
from sklearn.metrics import r2_score  #评价回归预测模型的性能
#可视化
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
plt.rcParams['font.sans-serif'] = ['SimHei']
# plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']
# 请输入准确的绝对或相对路径,读取FE_day.csv,输出为df
dpath = "./data/"
df = pd.read_csv(dpath + "FE_day.csv")
df.head()
#cnt是给定日期(天)时间(每小时)总租车人数,我们根据其他特征来推测cnt,所以cnt是输出y。是要预测的
y = df['cnt']
X = df.drop(['cnt'], axis=1)
# 用train_test_split 分割训练数据和测试数据,输出为X_train, X_test, y_train, y_test
# 随机采样20%的数据构建测试样本,其余作为训练样本
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0, test_size=0.2)

print("train samples:" ,X_train.shape)
#保存测试样本序号 保存测试ID,用于结果提交
testID = X_test['instant']

#踢出去样本序号,不参加数据训练 ID不参与预测
X_train.drop(['instant'], axis=1, inplace = True)
X_test.drop(['instant'], axis=1, inplace = True)

#保存特征名字以备后用(可视化)
feat_names = X_train.columns

## SVR, RBF
#1. 需要调优的参数
gammas = [ 0.03]
Cs = [ 1, 10, 100, 1000, 10000, 100000]
tuned_parameters = dict(gamma = gammas, C = Cs)

#2. 生成学习器实例,用SVR实例化,输出为svr
svr= SVR()

#3.用训练数据度模型进行训练  参考实验三“生成GridSearchCV实例”用GridSearchCV函数,其中cv=5,scoring='neg_mean_squared_error',网络参数搜索,输出grid
#再用grid.fit 训练数据,一共写2行代码,可参考实验三
grid = GridSearchCV(svr, tuned_parameters, cv=5, scoring='neg_mean_squared_error', n_jobs=4)
# 训练,交叉验证对超参数调优
grid.fit(X_train, y_train)

#通过交叉验证得到的最佳超参数alpha
# examine the best model
print(-grid.best_score_)
print("Best params: ", grid.best_params_)

# 训练集上测试,训练误差  grid.predict分别预测训练集X_train输出为y_train_pred  预测测试集X_test输出为y_test_pred
##2行代码,参考实验三
y_train_pred = grid.predict(X_train)
y_test_pred = grid.predict(X_test)

####用r2_score分别得出训练集准确率,输出为r2_score_train,测试集的准确率,输出为r2_score_test
##2行代码参考实验三
r2_score_train = r2_score(y_train,y_train_pred)
r2_score_test = r2_score(y_test,y_test_pred)

print("r2_score on Training set :" ,r2_score_train)
print("r2_score on Test set :" ,r2_score_test)
#%%
# plot CV误差曲线
test_means = grid.cv_results_[ 'mean_test_score' ]
test_stds = grid.cv_results_[ 'std_test_score' ]
# plot results
n_Cs = len(Cs)
number_gammas = len(gammas)
test_scores = np.array(test_means).reshape(n_Cs,number_gammas)
test_stds = np.array(test_stds).reshape(n_Cs,number_gammas)

linestyle_list = [ '-', '--', '-.' ,':']
x_axis = np.log10(Cs)
for i, value in enumerate(gammas):
    #pyplot.plot(log(Cs), test_scores[i], label= 'penalty:'   + str(value))
    plt.errorbar(x_axis, -test_scores[:,i], yerr=test_stds[:,i] ,label = 'gamma = ' + str(gammas[i]), ls = linestyle_list[i])
    #plt.errorbar(x_axis, -train_scores[:,i], yerr=train_stds[:,i] ,label = penaltys[i] +' Train')

#最佳超参数
plt.axvline(np.log10(grid.best_params_['C']), color='r', ls='--')

plt.legend(fontsize = 14)
plt.xlabel( 'log(C)',fontsize = 14 )
plt.ylabel( u'均方误差(MSE)',fontsize = 14 )
plt.show()
#%%
# Plot important coefficients
#只有线性SVR才有回归系数

#%%

#最佳模型的支持向量的数目
n_sv = len(grid.best_estimator_.support_)
print ('number of support vectors is: ', n_sv)

#%% md

gamma = 0.001
C=10^8 #支持向量数目 584
gamma = 0.01
C=10^7  #支持向量数目 584
gamma = 0.01
C=10^4#支持向量数目 584
#%% md
## 对测试集进行测试,生成提交文件
#%%
y_test_pred = grid.predict(X_test)
#生成提交测试结果
df_test_result = pd.DataFrame({"instant":testID, 'cnt':y_test_pred})
df_test_result.to_csv('submission.csv')
#%%

(2)核函数
运行成功下方核函数代码,每一行代码要标注注释,理解代码流程、理解代码含义,理解核函数高维可分性。

'''
核方法的必要性
升到高维空间线性可分
核函数不是仅仅在SVM里使用,它只是一个工具,把低维数据映射到高维数据的工具。本来是二维的数据,现在我们把它映射到高维。
这里也需要说明下,低维到高维,维数没有一个数量上的标准,可能就是无限维到无限维。
为什么要用核函数
因为在机器学习中,我们求解的过程要用到内积,而变换后的高维空间的内积我们不好求,所以我们定义了这个核函数,
可以把高维空间的内积运算转化成内维空间的某些运算,这样求起来简单
'''

# 导入必要的工具包
# 数据读取及基本处理
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_circles
from sklearn import svm
plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']
# Sklearn中的make_circles方法生成训练样本
X, Y = make_circles(n_samples=500, noise=0.02)

# np.where()返回符合某一条件的下标的函数
idx_0 = np.where(Y == 0)
idx_1 = np.where(Y == 1)
X_0 = X[idx_0]
X_1 = X[idx_1]

# visualizing data  可视化数据
plt.scatter(X_0[:, 0], X_0[:, 1], c='r', marker='*')
plt.scatter(X_1[:, 0], X_1[:, 1], c='b', marker='.')
plt.show()
# %%
# adding a new dimension to X  向X添加新维度
'''
在新版sklearn中,所有数据都应该是二维矩阵,哪怕它只是单独一行或一列,需要使用.reshape(1,-1)进行转换
使用reshape来更改数据的列数和行数 reshape(行,列)可以根据指定的数值将数据转换为特定的行数和列数
使用了reshape(-1,1)之后,数据集变成了一列 reshape(1,-1)呢?也就是直接变成了一行了。
那这个-1在这里要怎么理解呢?
跟进numpy库官网的介绍,这里的-1被理解为unspecified value,意思是未指定为给定的。
如果我只需要特定的行数,列数多少我无所谓,我只需要指定行数,那么列数直接用-1代替就行了,计算机帮我们算赢有多少列,反之亦然。
所以-1在这里应该可以理解为一个正整数通配符,它代替任何整数。
链接:https://www.jianshu.com/p/d9df005636a6
'''
X1_0 = X_0[:, 0].reshape((-1, 1))
X2_0 = X_0[:, 1].reshape((-1, 1))
X3_0 = (X1_0 ** 2 + X2_0 ** 2)
X_0 = np.hstack((X_0, X3_0))

X1_1 = X_1[:, 0].reshape((-1, 1))
X2_1 = X_1[:, 1].reshape((-1, 1))
X3_1 = (X1_1 ** 2 + X2_1 ** 2)
X_1 = np.hstack((X_1, X1_0))

# visualizing data in higher dimension  高维数据可视化/在更高维度上可视化数据
fig = plt.figure()
axes = fig.add_subplot(111, projection='3d')
# axes.scatter(X1, X2, X1**2 + X2**2, c = Y, depthshade = True)
axes.scatter(X1_0, X2_0, X1_0 ** 2 + X2_0 ** 2, c='r', marker='*', depthshade=True)
axes.scatter(X1_1, X2_1, X1_1 ** 2 + X2_1 ** 2, c='b', marker='.', depthshade=True)
plt.show()

# %%
# create support vector classifier using a linear kernel  使用线性核创建支持向量分类器
# adding a new dimension to X  向X添加新维度
X1 = X[:, 0].reshape((-1, 1))
X2 = X[:, 1].reshape((-1, 1))
X3 = (X1 ** 2 + X2 ** 2)
# numpy.hstack()函数是将数组沿水平方向堆叠起来。
X_3D = np.hstack((X, X3))
'''
sklearn.svm.SVC()函数全称为C-支持向量分类器。
kernel : string,optional(default =‘rbf’)
核函数类型,str类型,默认为’rbf’。可选参数为:
’linear’:线性核函数
‘poly’:多项式核函数
‘rbf’:径像核函数/高斯核
‘sigmod’:sigmod核函数
‘precomputed’:核矩阵
precomputed表示自己提前计算好核函数矩阵,这时候算法内部就不再用核函数去计算核矩阵,而是直接用你给的核矩阵,核矩阵需要为n*n的。
csdn.net/tags/MtTaEgxsMDc4OTEtYmxvZwO0O0OO0O0O.html
'''
svc = svm.SVC(kernel='linear')
svc.fit(X_3D, Y)
'''
绘制支撑向量所在的直线
svc.coef_:算法模型的系数,有两个值,因为样本有两种特征,每个特征对应一个系数;
系数:特征与样本分类结果的关系系数;
svc.intercept_:模型的截距,一维向量,只有一个数,因为只有一条直线;
系数:w = svc.coef_
截距:b = svc.intercept_
'''
w = svc.coef_
b = svc.intercept_

# plotting the separating hyperplane  绘制分离超平面
x1 = X[:, 0].reshape((-1, 1))
x2 = X[:, 1].reshape((-1, 1))
# numpy.meshgrid() 生成网格点坐标矩阵 二维坐标下,形成的一个一个的网格点 每个交叉点都是网格点,描述这些网格点的坐标的矩阵,就是坐标矩阵
# 给定X轴和Y轴所有的点,将X和Y放到两个数组,进行笛卡尔乘积,从而得到所有的点。
# https://zhuanlan.zhihu.com/p/41968396
x1, x2 = np.meshgrid(x1, x2)
x3 = -(w[0][0] * x1 + w[0][1] * x2 + b) / w[0][2]

fig = plt.figure()
# .add_subplot()作为单个整数编码的子绘图网格参数。例如,“111”表示“1×1网格,第一子图”,“234”表示“2×3网格,第四子图”。
# https://www.jianshu.com/p/7b68e01952b4
# 子图(m,n,i)将图窗口分成一个小的子图的m×n矩阵,并选择当前图的子图。绘图沿图形窗口的顶行编号,然后编号为第二行,依此类推。
axes2 = fig.add_subplot(111, projection='3d')
# .scatter() 绘制散点图
axes2.scatter(X1_0, X2_0, X1_0 ** 2 + X2_0 ** 2, c='r', marker='*', depthshade=True)
axes2.scatter(X1_1, X2_1, X1_1 ** 2 + X2_1 ** 2, c='b', marker='.', depthshade=True)
'''
gca:获取当前图形窗口中当前坐标轴的句柄值。
gcf:获取当前图形窗口的句柄值。
gco:获取当前图形窗口中当前对象的句柄值。
gcbf:获取回调函数正在执行的对象所在窗口的句柄。
gcbo:获取调函数正在执行的对象的句柄。
当前的图表和子图可以使用plt.gcf()和plt.gca()获得,分别表示Get Current Figure和Get Current Axes。
在pyplot模块中,许多函数都是对当前的Figure或Axes对象进行处理,比如说:plt.plot()实际上会通过plt.gca()获得当前的Axes对象ax,
然后再调用ax.plot()方法实现真正的绘图。
'''
axes1 = fig.gca(projection='3d')
axes1.plot_surface(x1, x2, x3, alpha=0.01)
plt.show()

dim = range(1, 1000)
# np.zeros()用法:zeros(shape, dtype=float, order='C')
# 返回:返回来一个给定形状和类型的用0填充的数组;
ratio = np.zeros(len(dim))

for j in range(1, 1000):
    n_points = 500
    # .random.randn()
    # 1)当函数括号内没有参数时,则返回一个浮点数;
    # 2)当函数括号内有一个参数时,则返回秩为1的数组,不能表示向量和矩阵;
    # 3)当函数括号内有两个及以上参数时,则返回指定维度的数组,能表示向量或矩阵;
    points = np.random.randn(n_points, j)

    # .linalg.norm() 求范数  axis:处理类型 axis=1表示按行向量处理,求多个行向量的范数
    # https://blog.csdn.net/u010660276/article/details/95936916
    dist = np.linalg.norm(points, axis=1)
    dist = np.sqrt(dist)
    Dmin = dist.min()
    Dmax = dist.max()
    ratio[j - 1] = np.log((Dmax - Dmin) / (Dmin * j))

plt.plot(dim, ratio)
plt.xlabel(u'特征空间维度', fontsize=14)
plt.ylabel('log((Dmax-Dmin)/Dmin)', fontsize=14)
plt.show()

plt.scatter(dim, ratio)
plt.xlabel(u'特征空间维度', fontsize=14)
plt.ylabel('log((Dmax-Dmin)/Dmin)', fontsize=14)
plt.show()

实验五 生成式分类器————PCALDA.py*

一、实验目的

  1. 掌握贝叶斯公式及原理
  2. 掌握朴素贝叶斯分类器及高斯判别分类器
  3. 掌握采用生成式分类器解决问题的思路。

二、实验内容和要求
下载MINIST数据集,阅读P102页,案例分析3:MINIST手写数字识别,采用PCA+LDA算法完成本次实验。
(1)数据预处理:根据测试集与训练集从[0,255]变换成[0,1]。再调用用PCA在测试集和训练集上进行降维,参数n_components=0.95
(2)实例化LinearDiscriminantAnalysis分类器。输入参数为降维后的训练集及y_train类别。训练后的模型对降维后的测试集进行测试。采用五折交叉验证评估模型性能。
PCALDA.py

# 导入必要的工具包
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.model_selection import cross_val_score
# %%

# 读取训练数据和测试数据
train = pd.read_csv('./data/MNIST_train.csv')
test = pd.read_csv('./data/MNIST_test.csv')

y_train = train.label.values
X_train = train.drop("label", axis=1).values
X_test = test.values

# %%
# 将像素值[0,255]  --> [0,1]
X_train = X_train / 255.0
X_test = X_test / 255.0
## PCA降维
pca = PCA(n_components=0.95, svd_solver='full')
pca.fit(X_train)

# 在训练集和测试集降维
X_train_pca = pca.transform(X_train)
X_test_pca = pca.transform(X_test)

## LDA分类器

lda = LinearDiscriminantAnalysis()
lda.fit(X_train_pca, y_train)
# %%
# 用在降维后的全体训练数据集上训练的模型对测试集进行测试
y_predict = lda.predict(X_test_pca)
##  交叉验证, 评估模型性能
loss = cross_val_score(lda, X_train_pca, y_train, cv=5)
print('accuracy of each fold is: ', loss)
print('cv accuracy is:', loss.mean())

实验六 决策树

一、实验目的

  1. 掌握决策树公式及原理
  2. 掌握ID3、C4.5计算过程
  3. 掌握采用决策树解决问题的思路。
#  md
#
# # 决策树:Bike Sharing 数据集上的回归分析
#
# ## R2分数为评价指标
# 1、 任务描述 请在Capital Bikeshare (美国Washington, D.C.的一个共享单车公司)提供的自行车数据上进行回归分析。训练数据为2011年的数据,要求预测2012年每天的单车共享数量。
#
# 原始数据集地址:http://archive.ics.uci.edu/ml/datasets/Bike+Sharing+Dataset 1) 文件说明
# day.csv: 按天计的单车共享次数(作业只需使用该文件)
# hour.csv: 按小时计的单车共享次数(无需理会)
# readme:数据说明文件
#
# 2) 字段说明
# Instant记录号
# Dteday:日期
# Season:季节(1=春天、2=夏天、3=秋天、4=冬天)
# yr:年份,(0: 2011, 1:2012)
# mnth:月份( 1 to 12)
# hr:小时 (0 to 23) (只在hour.csv有,作业忽略此字段)
# holiday:是否是节假日
# weekday:星期中的哪天,取值为0~6
# workingday:是否工作日 1=工作日 (是否为工作日,1为工作日,0为非周末或节假日 weathersit:天气(1:晴天,多云
2:雾天,阴天
3:小雪,小雨
4:大雨,大雪,大雾) temp:气温摄氏度
# atemp:体感温度
# hum:湿度
# windspeed:风速
#
# casual:非注册用户个数
# registered:注册用户个数
# cnt:给定日期(天)时间(每小时)总租车人数,响应变量y
# casual、registered和cnt三个特征均为要预测的y,作业里只需对cnt进行预测

#%%

# 导入必要的工具包
# 数据读取及基本处理
import pandas as pd
import numpy as np

#模型
from sklearn.tree import DecisionTreeRegressor
from sklearn.model_selection import GridSearchCV

#模型评估
from sklearn.metrics import mean_squared_error
from sklearn.metrics import r2_score  #评价回归预测模型的性能

#可视化
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
#显示中文
plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']

#%%

# 读入数据
dpath = "./data/"

df = pd.read_csv(dpath + "FE_day.csv")
df.head()

#%% md

#**准备训练数据**

#%%

# get labels
y = df['cnt']
X = df.drop(['cnt'], axis=1)

#%%

# 用train_test_split 分割训练数据和测试数据

X_train, X_test, y_train, y_test = train_test_split(X, y, train_size = 0.8,random_state = 0)

print("train samples:" ,X_train.shape)

#%%

#保存测试ID,用于结果提交
testID = X_test['instant']

#ID不参与预测
X_train.drop(['instant'], axis=1, inplace = True)
X_test.drop(['instant'], axis=1, inplace = True)

#保存特征名字以备后用(可视化)
feat_names = X_train.columns

#%% md

## 决策树:默认参数

#%%

DT1 = DecisionTreeRegressor()

DT1.fit(X_train, y_train)

#训练上测试,训练误差,实际任务中这一步不需要
y_train_pred = DT1.predict(X_train)
rmse_train = np.sqrt(mean_squared_error(y_train,y_train_pred))

y_test_pred = DT1.predict(X_test)
rmse_test = np.sqrt(mean_squared_error(y_test,y_test_pred))

print("RMSE on Training set :", rmse_train)
print("RMSE on Test set :" ,rmse_test)

r2_score_train = r2_score(y_train,y_train_pred)
r2_score_test = r2_score(y_test,y_test_pred)
print("r2_score on Training set :" ,r2_score_train)
print("r2_score on Test set :" ,r2_score_test)

#%% md
#
# 训练集上的性能完美,测试集上性能不好,决策树很容易过拟合。
#
# #%% md
#
# ## 决策树:超参数调优
#
# #%% md
#
# 决策树的超参数有:
# 1. max_depth(树的深度)或max_leaf_nodes(叶子结点的数目)、
# 2. min_samples_leaf(叶子结点的最小样本数)、min_samples_split(中间结点的最小样本树)、
# 3. min_weight_fraction_leaf(叶子节点的样本权重占总权重的比例)
# 4. min_impurity_split(最小不纯净度)也可以调整
# 5. max_features(最大特征数目)、
#
#
# 在sklearn框架下,不同学习器的参数调整步骤相同:
# 设置参数搜索范围
# 生成GridSearchCV的实例(参数)
# 调用GridSearchCV的fit方法
#
# #%%

#1.需要调优的参数
max_depth = range(2,20,1)
min_samples_leaf = range(1,8,1)
tuned_parameters = dict(max_depth=max_depth, min_samples_leaf=min_samples_leaf)

#2. 生成学习器实例
DT2 = DecisionTreeRegressor()

# 3. 用训练数据度模型进行训练
grid = GridSearchCV(DT2, tuned_parameters,cv=10, scoring='neg_mean_squared_error')
grid.fit(X_train,y_train)

#%%

#通过交叉验证得到的最佳超参数alpha
# examine the best model
print(-grid.best_score_)
print("Best params: ", grid.best_params_)

#训练上测试,训练误差,实际任务中这一步不需要
y_train_pred = grid.predict(X_train)
rmse_train = np.sqrt(mean_squared_error(y_train,y_train_pred))

y_test_pred = grid.predict(X_test)
rmse_test = np.sqrt(mean_squared_error(y_test,y_test_pred))

print("RMSE on Training set :", rmse_train)
print("RMSE on Test set :" ,rmse_test)

r2_score_train = r2_score(y_train,y_train_pred)
r2_score_test = r2_score(y_test,y_test_pred)
print("r2_score on Training set :" ,r2_score_train)
print("r2_score on Test set :" ,r2_score_test)

#%%

# plot CV误差曲线
test_means = grid.cv_results_[ 'mean_test_score' ]
test_stds = grid.cv_results_[ 'std_test_score' ]

# plot results
n_Cs = len(max_depth)
number_gammas = len(min_samples_leaf)
test_scores = np.array(test_means).reshape(n_Cs,number_gammas)
test_stds = np.array(test_stds).reshape(n_Cs,number_gammas)

linestyle_list = [ '-', '--', '-.' ,':']
#, ls = linestyle_list[i]
x_axis = max_depth
for i, value in enumerate(min_samples_leaf):
    #pyplot.plot(log(Cs), test_scores[i], label= 'penalty:'   + str(value))
    plt.errorbar(x_axis, -test_scores[:,i], yerr=test_stds[:,i] ,label = 'min_samples_leaf = ' + str(min_samples_leaf[i]))
    #plt.errorbar(x_axis, -train_scores[:,i], yerr=train_stds[:,i] ,label = penaltys[i] +' Train')

#最佳超参数
plt.axvline(grid.best_params_['max_depth'], color='r', ls='--')

plt.legend(fontsize = 10)
plt.xlabel( 'max_depth',fontsize = 14 )
plt.ylabel( u'均方误差(MSE)',fontsize = 14 )

plt.show()

#%% md
#
# max_depth在5-20之间,min_samples_leaf在3-7之间性能差异不太大
#
# 最佳模型的性能比默认参数情况下略好
# 性能比线性回归和SVR差,模型处于过拟合状态,决策树很容易过拟合

#%% md

## 特征重要性

#%%
columns = X_train.columns

df_importance = pd.DataFrame({"columns":list(columns), "importance":list(grid.best_estimator_.feature_importances_.T)})
df_importance.sort_values(by=['importance'],ascending=False)

#%% md

## 对测试集进行测试,生成提交文件

#%%
y_test_pred = grid.predict(X_test)

#生成提交测试结果
df_test_result = pd.DataFrame({"instant":testID, 'cnt':y_test_pred})
df_test_result.to_csv(dpath + 'submission.csv')

#%%

实验八 神经网络————letnet.py *

一、实验目的

  1. 掌握神经网络结构及分类
  2. 掌握反向传播公式推导
  3. 掌握采用神经网络解决问题的思路
    二、实验内容和要求
    请参考以下链接或github源码,独立完成采用神经网络实现MINIST手写数字识别。
    pythonsklearn做手写识别_Python scikit-learn 学习笔记—手写数字识别
    MINST手写数字识别(二)—— 卷积神经网络(CNN)
    神经网络初识——MINIST手写数字识别(可视化输出结果)
    使用MNIST数据集训练第一个pytorch CNN手写数字识别神经网络
from keras.optimizers import SGD
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from sklearn import datasets
from keras import backend as K
import matplotlib.pyplot as plt
import numpy as np


class LeNet:
    @staticmethod
    def build(width, height, depth, classes, weightsPath=None):
        # initialize the model
        model = Sequential()

        # first set of CONV => RELU => POOL valid
        model.add(Convolution2D(20, 5, 5, border_mode="valid",
                                input_shape=(depth, height, width)))
        model.add(Activation("relu"))
        model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))

        # second set of CONV => RELU => POOL
        model.add(Convolution2D(50, 5, 5, border_mode="valid"))
        model.add(Activation("relu"))
        model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))

        # set of FC => RELU layers
        model.add(Flatten())
        model.add(Dense(500))
        model.add(Activation("relu"))
        # softmax classifier
        model.add(Dense(classes))
        model.add(Activation("softmax"))

        # if weightsPath is specified load the weights
        if weightsPath is not None:
            model.load_weights(weightsPath)

        return model
print("[INFP] accessing MNIST...")
# 从磁盘加载MNIST数据集
dataset=datasets.fetch_mldata("MNIST Original")
data=datasets.data

# reshape the design matrix such that the matrix is:
# num_sample x depth x row x columns
if K.image_data_format()=="channels_first":
    data=data.reshape(data.shape[0],1,28,28)
#otherwise,we are using "channels last"ordering,so the design matrix shape should be:
else:
    data=data.reshape(data.shape[0],28,28,1)

# scale the input data to the range[0,1] and perform a train/test split
(trainX,testX,trainY,testY)=train_test_split(data/255.0, dataset.target.astype("int"),test_size=0.25,random_state=42)
# convert the labels from integers to vectors
le=LabelBinarizer()
trainY=le.fit_transform(trainY)
testY=le.transform(testY)

# initialize the optimizer and model
print("[INFO] compiling model...")
opt=SGD(lr=0.01)
model=LeNet.build(width=28,height=28,depth=1,classes=10)
model.compile(loss="categorical_crossentropy",optimizer=opt,metrics=["accuracy"])
# train the network
print("[INFO] training network...")
H=model.fit(trainX,trainY,validation_data=(testX,testY),batch_size=128,epochs=20,verbose=1)

# evaluates the network
print("[INFO] evaluating network...")
predictions=model.predict(testX,batch_size=128)
print(classification_report(testY.argmax(axis=1),predictions.argmax(axis=1),target_names=[str(x) for x in le.classes_]))
# plot the training loss and accuracy
plt.style.use("ggplot")
plt.figure()
plt.plot(np.arange(0,20),H.history["loss"],label="train_loss")
plt.plot(np.arange(0,20),H.history["val_loss"],label="val_loss")
plt.plot(np.arange(0,20),H.history["acc"],label="train_acc")
plt.plot(np.arange(0,20),H.history["val_acc"],label="val_acc")
plt.title("Training Loss and Accuracy")
plt.legend()
plt.show()

实验九 降维————DR_Mnist.py *

一、实验目的

  1. 掌握降维原理
  2. 掌握PCA公式推导过程
  3. 掌握采用降维解决问题的思路。
    二、实验内容和要求
    采用PCA对Mnist手写数字集进行降维,显示主成分,将DR_Mnist.py代码运行成功。
    DR_Mnist.py:
# %% md
# # 在MNIST数据集上进行降维分析
# 图像数据维数高,而且特征之间(像素之间)相关性很高,因此我们预计用很少的维数就能保留足够多的信息
#
# 降维技术:
# PCA: PCA
# MNIST数据集介绍:
# 本数据来源于Kaggle竞赛提供的数据:Digit
# Recognizer (https: // www.kaggle.com / c / digit - recognizer / data)
# 训练集包含42, 000
# 个样本,测试集包含28, 000
# 个样本。
# 每个样本为28 * 28
# 的灰度图像,像素值在[0, 255]
# 数据排列形式:
# 000
# 001
# 002
# 003...
# 026
# 027
# 02
# 8
# 02
# 9
# 030
# 031...
# 054
# 055
# 056
# 057
# 05
# 8
# 05
# 9...
# 0
# 82
# 0
# 83
# | | | | ... | |
# 728
# 729
# 730
# 731...
# 754
# 755
# 756
# 757
# 758
# 759...
# 782
# 783
#
# # %%

# 导入必要的工具包
import pandas as pd
import numpy as np

import time

from matplotlib import cm
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
# % matplotlib
# inline

import seaborn as sns

# 显示中文
plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']

# %%

# 读取训练数据,训练集中有42000个样本
train = pd.read_csv('MNIST_train.csv')

y_train = train.label.values
X_train = train.drop("label", axis=1).values

# 将像素值[0,255]  --> [0,1]
X_train = X_train / 255.0

# 原始输入的特征维数和样本数目
print('the shape of train_image: {}'.format(X_train.shape))

# %% md

### 显示原始图像(64个)

# %%

plt.figure(figsize=(14, 12))
for digit_num in range(0, 64):
    plt.subplot(8, 8, digit_num + 1)
    grid_data = X_train[digit_num].reshape(28, 28)  # reshape from 1d to 2d pixel array
    plt.imshow(grid_data, interpolation="none", cmap='gray')
    plt.xticks([])
    plt.yticks([])
plt.tight_layout()

# %%

# 对Isomap等计算量大的降维技术来说,4w+样本太多,随机抽取其中20%做实验
from sklearn.model_selection import train_test_split

# from sklearn.utils import shuffle
X_selected, X_val, y_selected, y_val = train_test_split(X_train, y_train, train_size=0.2, random_state=0)

# 原始输入的特征维数和样本数目
print('the shape of input: {}'.format(X_selected.shape))

# %% md

## PCA

# %%
start = time.time()

# PCA(n_components=None, copy=True, whiten=False, svd_solver=’auto’, tol=0.0, iterated_power=’auto’, random_state=None)
# 默认参数,保留所有成分,可以根据每个分成能解释的方差,人工确定合适的成分数目n_components
pca = PCA()
print("PCA begin...");
pca.fit(X_selected)

# 降维
X_pca = pca.transform(X_selected)

end = time.time()
print("PCA time elaps:{}".format(int(end - start)))

# %%

# explained_variance_:每个主成分能解释的方差的的百分比,即X的协方差矩阵的特征值
# explained_variance_ratio_:每个主成分能解释的方差的的百分比
# 绘制不同PCA维数下模型的性能,找到最佳模型/参数(分数最高)
plt.plot(pca.explained_variance_ratio_, 'b-')

plt.xlabel(u"主成分数目", fontsize=14)
plt.ylabel(u"能解释的方差的比例", fontsize=14)

# %%

# 主成分数目通常有三种方式:
# 1. 直接确定主成分数目:如30
# 2. 根据主成分的累计贡献率确定主成分数目,如累计贡献率大于85%。
# 3. 肘部法(the elbow rule):根据每个成分对应的特征值(解释的方差比例),寻找一个截止点(elbow),在该截止点,特征值显著下降。
# 根据上图,主成分数目可以取50-100.

# %%

sum_explained_variance_ratio_ = np.zeros(X_selected.shape[1])

sum_explained_variance_ratio_[0] = pca.explained_variance_ratio_[0]
for i in range(1, X_selected.shape[1]):
    sum_explained_variance_ratio_[i] = sum_explained_variance_ratio_[i - 1] + pca.explained_variance_ratio_[i]
plt.plot(sum_explained_variance_ratio_, 'b-')

plt.xlabel(u"主成分数目", fontsize=14)
plt.ylabel(u"能解释的累计方差的比例", fontsize=14)

# %%

for i in range(0, X_selected.shape[1]):
    if sum_explained_variance_ratio_[i] > 0.85:
        print("%d number of components explain %d variance", i + 1, int(sum_explained_variance_ratio_[i] * 100))
        break

# %%

for i in range(0, X_selected.shape[1]):
    if sum_explained_variance_ratio_[i] > 0.90:
        print("%d number of components explain %d variance", i + 1, int(sum_explained_variance_ratio_[i] * 100))
        break

# %% md

### 显示主成分

# %%
# n_components:这个参数可以帮我们指定希望PCA降维后的特征维度数目
n_components = 32
eigenvalues = pca.components_

n_row = 4
n_col = 8

# Plot the first 8 eignenvalues
plt.figure(figsize=(13, 12))
for i in list(range(n_row * n_col)):
    offset = 0
    plt.subplot(n_row, n_col, i + 1)
    plt.imshow(eigenvalues[i].reshape(28, 28), cmap='gray')
    title_text = 'Eigenvalue ' + str(i + 1)
    plt.title(title_text, size=6.5)
    plt.xticks(())
    plt.yticks(())
plt.show()
# %%

def plot_embedding(data, label, title):
    x_min, x_max = np.min(data, 0), np.max(data, 0)
    data = (data - x_min) / (x_max - x_min)

    fig = plt.figure()
    for i in range(data.shape[0]):
        plt.text(data[i, 0], data[i, 1], str(label[i]),
                 color=plt.cm.Set1(label[i] / 10.),
                 fontdict={'weight': 'bold', 'size': 9})
    plt.xticks([])
    plt.yticks([])
    plt.title(title, fontsize=14)

    # plt.scatter(data[:, 0], data[:, 1],
    #        c=label, edgecolor='none', alpha=0.5,
    #        cmap=plt.cm.get_cmap('spectral', 10))
    plt.xlabel(u'成分1', fontsize=14)
    plt.ylabel(u'成分2', fontsize=14)
    # plt.colorbar();
    # return fig
# %%
plot_embedding(X_pca[:, 0:2], y_selected, u'PCA')

# %% md
# Isomap
# %%

标签:plt,机器,score,df,学习,train,实验,test,import
来源: https://www.cnblogs.com/lx0113/p/16350351.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有