gpt4 book ai didi

python - scikit 的 MLPClassifier(和其他分类器)的训练分数低

转载 作者:太空宇宙 更新时间:2023-11-04 09:57:40 26 4
gpt4 key购买 nike

(更新:Posted 最终调查结果作为单独的答案)

我开始尝试了解如何使用 scikit 模型进行训练。我已经尝试过众所周知的数据集,如 iris、MNIST 等——它们都是结构良好的数据,随时可用。这是我第一次尝试自己用原始数据构建模型,结果并不理想。

我选择使用的数据是NHSTA's crash data在过去的 3 年里。

这是数据的快照,让您无需下载数据即可了解字段。

Snapshot of crash data columns

我的第一个实验很简单 - 尝试构建一个给定“驾照州代码”和“年龄”的模型,尝试预测性别(男或女)。

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn import metrics
from sklearn.neural_network import MLPClassifier
from sklearn.model_selection import learning_curve
from sklearn.model_selection import ShuffleSplit
import tensorflow.contrib.learn as skflow
from tensorflow.contrib.learn.python.learn.estimators import run_config
from sklearn.svm import SVC
import pickle, seaborn


def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None,
n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)):
#http://scikit-learn.org/stable/auto_examples/model_selection/plot_learning_curve.html
plt.figure()
plt.title(title)
if ylim is not None:
plt.ylim(*ylim)
plt.xlabel("Training examples")
plt.ylabel("Score")
train_sizes, train_scores, test_scores = learning_curve(
estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)
train_scores_mean = np.mean(train_scores, axis=1)
train_scores_std = np.std(train_scores, axis=1)
test_scores_mean = np.mean(test_scores, axis=1)
test_scores_std = np.std(test_scores, axis=1)
plt.grid()

plt.fill_between(train_sizes, train_scores_mean - train_scores_std,
train_scores_mean + train_scores_std, alpha=0.1,
color="r")
plt.fill_between(train_sizes, test_scores_mean - test_scores_std,
test_scores_mean + test_scores_std, alpha=0.1, color="g")
plt.plot(train_sizes, train_scores_mean, 'o-', color="r",
label="Training score")
plt.plot(train_sizes, test_scores_mean, 'o-', color="g",
label="Cross-validation score")

plt.legend(loc="best")
plt.show()

#MAIN

crashes = pd.read_csv("crashes.csv", nrows=100000)

# drop useless cols

crashes.drop(["Year","Case Individual ID", "Case Vehicle ID", "Transported
By", "Injury Location", "Role Type"],axis=1, inplace=True)

crashes = crashes [pd.notnull(crashes['Age'])]
crashes = crashes[crashes.Age >= 10 ] # There are ages < 10 - likely junk data. I don't think they drive


# lets drop rows that are empty
crashes = crashes [pd.notnull(crashes['License State Code'])]
crashes = crashes [pd.notnull(crashes['Injury Severity'])]
crashes = crashes [pd.notnull(crashes['Safety Equipment'])]
crashes = crashes [pd.notnull(crashes['Sex'])]

# converts text fields to numerical values
le = LabelEncoder()
crashes = crashes[crashes.columns[:]].apply(le.fit_transform)
crashes = crashes._get_numeric_data()

# lets plot a heat map to show correlation
corr = crashes.corr()
ax = seaborn.heatmap (corr, xticklabels=corr.columns.values,
yticklabels=corr.columns.values, annot=True)
plt.setp( ax.xaxis.get_majorticklabels(), rotation=45 )
plt.setp( ax.yaxis.get_majorticklabels(), rotation=-45 )
plt.show()

crashes_train, crashes_test = train_test_split(crashes, test_size = 0.2)
Y_train = crashes_train['Sex']
X_train = crashes_train[[ 'Age', 'License State Code']]
Y_test = crashes_test['Sex']
X_test = crashes_test[[ 'Age', 'License State Code']]


names_train = crashes_train.columns.values

print "train size ",len (X_train)
print "test size",len (X_test)
#
# cls = RandomForestClassifier(verbose = True)
#
cls = MLPClassifier(hidden_layer_sizes=(10,10,10), max_iter=500, alpha=1e-4,
solver='sgd', verbose=10, tol=1e-4, random_state=1,
learning_rate_init=0.01)

#cls = tf.contrib.learn.DNNClassifier(feature_columns=feats,
# hidden_units=[50, 50, 50],
# n_classes=3)

#
#

#cls = SVC(verbose = True)

print "Fitting..."
cls.fit(X_train, Y_train)

plot_learning_curve(cls,"Crash Learning", X_train, Y_train)


print("Training set score: %f" % cls.score(X_train, Y_train))
print("Test set score: %f" % cls.score(X_test, Y_test))

我尝试了多种模型(从 RandomForest、SVC 到 MLP 等)——它们都得出了大约 0.56 的训练分数和 0.6 倍的损失

最后,这是在当前配置中为 MLP 生成的图: enter image description here

这是我切换到 RandomForest 时的情节。 enter image description here

在 RandomForest 中看起来分数下降,但总体上它的结局与 MLP 相似。我做错了什么以及如何改进这种方法?谢谢

编辑:基于下面的两个答案,我绘制了所有列之间相关性的热图(在删除明显无用的列之后)——这很糟糕,但这是正确的方法吗?我也可以做 PCA,但如果基本的场间相关性很差,是否表明数据集在很大程度上无法用于挖掘预测?

heatmap vis <code>df.corr</code>

最佳答案

My first experiment is simple - try and build a model that given "License State Code" and "Age", try and predict the gender (M or F).

嗯,事情没那么简单。您不能简单地获取任何数据并尝试预测某些事情。数据至少需要相互关联。

一些好事要做:

  • 绘制数据。绘制这 3 个变量(年龄与性别、执照州代码与性别)并查看它们是否存在某种相关性。
  • 计算变量之间的相关性,如Person's Correlation Coefficient .
  • 使用您拥有的所有特征和 RandomForest/DecisionTree 分类器,它们有一个名为 feature_importances_ 的属性。此属性告诉您哪些功能在您的数据集中最重要(当然根据模型)特征重要性(越高,特征越重要)。
  • 详细了解 MLP 和分类器的一般工作原理。

分类算法只是将输入数据映射到一个类别。但是,如果您的输入和输出之间没有任何关系,则此任务不可行。特征选择是机器学习中一个非常重要的领域。来自 wikipedia :

In machine learning and statistics, feature selection, also known as variable selection, attribute selection or variable subset selection, is the process of selecting a subset of relevant features (variables, predictors) for use in model construction.

关于python - scikit 的 MLPClassifier(和其他分类器)的训练分数低,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45145991/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com