监督机器学习,产生训练有素的估计器

Supervised Machine Learning, producing a trained estimator

我有一个作业,我应该在其中使用 scikit、numpy 和 pylab 来执行以下操作:

"以下所有内容都应使用 training_data.csv 文件中的数据 假如。 training_data 给你一组带标签的整数对, 代表两个运动队的分数,标签给出 运动。

编写如下函数:

plot_scores() 应该绘制数据的散点图。

predict(dataset) 应该产生一个训练有素的 Estimator 来猜测这项运动 这导致了给定的分数(来自我们保留的数据集,这将 作为 1000 x 2 np 数组输入)。您可以使用 scikit 中的任何算法。

名为 "preprocess" 的可选附加函数将处理数据集 在我们将其传递给预测之前。 “

这是我目前所做的:

import numpy as np
import scipy as sp
import pylab as pl
from random import shuffle

def plot_scores():
    k=open('training_data.csv')
    lst=[]
    for triple in k:
        temp=triple.split(',')
        lst.append([int(temp[0]), int(temp[1]), int(temp[2][:1])])
    array=np.array(lst)
    pl.scatter(array[:,0], array[:,1])
    pl.show()

def preprocess(dataset):
    k=open('training_data.csv')
    lst=[]
    for triple in k:
        temp=triple.split(',')
        lst.append([int(temp[0]), int(temp[1]), int(temp[2][:1])])
    shuffle(lst)
    return lst

在预处理中,我打乱了数据,因为我应该使用其中的一些进行训练,一些进行测试,但原始数据完全不是随机的。我的问题是,我应该如何 "produce a trained estimator" in predict(dataset)?这应该是 returns 另一个函数的函数吗?哪种算法最适合根据如下所示的数据集进行分类:

该任务可能希望您训练一个标准的 scikit 分类器模型并 return 它,即

from sklearn.svm import SVC
def predict(dataset):
    X = ... # features, extract from dataset
    y = ... # labels, extract from dataset
    clf = SVC() # create classifier
    clf.fit(X, y) # train
    return clf

尽管从函数的名称 (predict) 判断,您应该检查它是否真的希望您 return 一个训练有素的分类器或 return 对给定 [=12] 的预测=] 参数,因为那会更典型。

作为分类器,您基本上可以使用任何您喜欢的分类器。你的情节看起来你的数据集是线性可分离的(类 没有颜色,但我假设斑点是两个 类)。在线性可分数据上几乎没有任何事情会失败。尝试支持向量机、逻辑回归、随机森林、朴素贝叶斯……为了获得更多乐趣,您可以尝试绘制决策边界,请参阅 here(其中还包含可用分类器的概述)。

我建议你看看这个结构:

from random import shuffle
import matplotlib.pyplot as plt
# import a classifier you need


def get_data():
    # open your file and parse data to prepare X as a set of input vectors and Y as a set of targets
    return X, Y


def split_data(X, Y):
    size = len(X)
    indices = range(size)
    shuffle(indices)
    train_indices = indices[:size/2]
    test_indices = indices[size/2:]
    X_train = [X[i] for i in train_indices]
    Y_train = [Y[i] for i in train_indices]
    X_test = [X[i] for i in test_indices]
    Y_test = [Y[i] for i in test_indices]
    return X_train, Y_train, X_test, Y_test


def plot_scatter(Y1, Y2):
    plt.figure()
    plt.scatter(Y1, Y2, 'bo')
    plt.show()


# get data
X, Y = get_data()

# split data
X_train, Y_train, X_test, Y_test = split_data(X, Y)

# create a classifier as an object
classifier = YourImportedClassifier()

# train the classifier, after that the classifier is the trained estimator you need
classifier.train(X_train, Y_train) # or .fit(X_train, Y_train) or another train routine

# make a prediction
Y_prediction = classifier.predict(X_test)

# plot the scatter
plot_scatter(Y_prediction, Y_test)

我认为您正在寻找的是 clf.fit() 函数,而不是创建产生另一个函数的函数