老师,请问为什么我这样写不能执行

来源:4-3 训练数据集,测试数据集

慕云19

2018-12-30

from sklearn import datasets
from math import sqrt
import numpy as np
from collections import Counter

# digits=datasets.load_digits()
iris=datasets.load_iris()
# print(iris)
X=iris.data
y=iris.target

def train_test_split(X,y,test_ratio=0.2):
    shuffle_indexes = np.random.permutation(len(X))

    test_size = int(len(X) * test_ratio)

    test_indexes = shuffle_indexes[:test_size]
    train_indexes = shuffle_indexes[test_size:]

    X_train = X[train_indexes]
    y_train = y[train_indexes]
    # print(X_train.shape)
    # print(y_train.shape)

    X_test = X[test_indexes]
    y_test = y[test_indexes]
    # print(X_test.shape)
    # print(y_test.shape)

    return X_train,X_test,y_train,y_test



class KNNClassifier:
    def __init__(self,k):
        self.k=k
        self._X_train=None
        self._y_train=None

    def fit(self,X_train,y_train):
        self._X_train=X_train
        self._y_trian=y_train
        return self

    def predict(self,X_predict):
        y_predict = [self._predict(x) for x in X_predict]
        return np.array(y_predict)

    def _predict(self,x):
        distances = []
        for x_train in self._X_train:
            d = sqrt(np.sum((x_train - x) ** 2))
            distances.append(d)

        nearest = np.argsort(distances)
        topK_y = [self._y_train[i] for i in nearest[:self.k]]

        votes = Counter(topK_y)
        return votes.most_common(1)[0][0]

    def _repr_(self):
        return "KNN(k=%d)"% self.k

X_train,X_test,y_train,y_test=train_test_split(X,y)
knn_clf=KNNClassifier(3)
knn_clf.fit(X_train,y_train)
y_predict=knn_clf.predict(X_test)
print(y_predict)


Traceback (most recent call last):
File “E:/软件/PyCharm/works/MachineL/KNN.py”, line 67, in
y_predict=knn_clf.predict(X_test)
File “E:/软件/PyCharm/works/MachineL/KNN.py”, line 46, in predict
y_predict = [self._predict(x) for x in X_predict]
File “E:/软件/PyCharm/works/MachineL/KNN.py”, line 46, in
y_predict = [self._predict(x) for x in X_predict]
File “E:/软件/PyCharm/works/MachineL/KNN.py”, line 56, in _predict
topK_y = [self._y_train[i] for i in nearest[:self.k]]
File “E:/软件/PyCharm/works/MachineL/KNN.py”, line 56, in
topK_y = [self._y_train[i] for i in nearest[:self.k]]
TypeError: ‘NoneType’ object is not subscriptable

写回答

2回答

liuyubobobo

2018-12-30

目测最后 topK_y = [self._y_train[i] for i in nearest[:self.k]] 一句话,或者是_y_train,或者是nearest为空。如果你确定你的knn算法和课程一致的话,请确认你的调用过程没有问题,尤其是传给knn的X_train,y_train和predict的x是正确的。


这个课程的所有代码,都可以通过课程的官方github获得。可以先尝试在你的环境下运行课程的官方代码,看看是否有问题?如果没有问题,请仔细调试比对,看看自己的代码哪里有问题?传送门:https://github.com/liuyubobobo/Play-with-Machine-Learning-Algorithms    


如果访问github有困难,也可以使用慕课网内部该课程的官方代码仓:https://git.imooc.com/coding-169/coding-169   


加油!:)

0
1
慕云19
嗯嗯,谢谢老师,这么快就回复我了,而且确实是y_train那个地方写错了,导致传的值为空
2018-12-30
共1条回复

慕云19

提问者

2018-12-30

老师我知道了,有个地方写错了

0
0

Python3入门机器学习 经典算法与应用  

Python3+sklearn,兼顾原理、算法底层实现和框架使用。

5839 学习 · 2437 问题

查看课程