首页 > 解决方案 > 如何格式化 scikit-learn 输出数据?

问题描述

目前正在学习一个机器学习应用程序和一个方法的输出真的让我很难过,我从来没有见过这样的输出。

代码:

def IsCloseTogether(data):
    amount_of_data = len(data) #i have an array loaded with examples
    local_feature = np.reshape(data, (amount_of_data,-1)) #changes the array so it would work with the clf.fit
    labels = [1, 0, 0, 0, 1, 1] # 1 means it matches, 0 means it doesn't (supervised learning)
    clf = tree.DecisionTreeClassifier()
    clf = clf.fit(local_feature, labels)
    prediction = clf.predict([["111011101"], ["101"]]) #these number strings are the strings im making the machine predict whether they are similar enough to be deemed "similar" or "different"
    return prediction

打印后我得到这个输出:

[1 0]

尽管数字本身是有意义的,但我理想情况下希望元素显示为实际的列表元素,例如:

['1','0']

我试过使用.join,但它不是一个字符串,所以我似乎无法让它工作,知道如何格式化这个输出吗?

标签: pythonarraysmachine-learningscikit-learn

解决方案


clf.predict返回一个 Numpy 数组:

from sklearn import tree
X = [[0, 0], [1, 1]]
Y = [0, 1]
clf = tree.DecisionTreeClassifier()
clf = clf.fit(X, Y)

print(clf.predict(X))
# [0 1]

type(clf.predict(X))
# numpy.ndarray

想打印就打印,应该先把数组元素转换成字符串,然后join;您可以使用单个列表推导执行这两个操作:

pred = clf.predict(X)
[",".join(item) for item in pred.astype(str)]
# ['0', '1']

推荐阅读