(self, X_p)
| 117 | """ |
| 118 | |
| 119 | def predict(self, X_p): |
| 120 | k = 11 # 超参数取11 |
| 121 | |
| 122 | predict_true = 0 # the num of right predicted |
| 123 | max = X_p.shape[0] # the max num of iteration |
| 124 | y_p = [] |
| 125 | for i in range(max): |
| 126 | x_p = X_p[i] |
| 127 | |
| 128 | distances = [np.sqrt(np.sum((x_p - x) ** 2)) for x in self.X_train] |
| 129 | # calculate the distance between point in x_p and point in x |
| 130 | d = np.sort(distances) |
| 131 | # sort the distances |
| 132 | nearest = np.argsort(distances) |
| 133 | # the index of sorted data |
| 134 | # print(nearest) |
| 135 | |
| 136 | topk_y = [self.y_train[j] for j in nearest[:k]] |
| 137 | # select k nearest num |
| 138 | |
| 139 | for i in range(k): |
| 140 | if topk_y[i] == 'pear': |
| 141 | color = 'b' |
| 142 | elif topk_y[i] == 'poplar': |
| 143 | color = 'y' |
| 144 | else: |
| 145 | color = 'g' |
| 146 | plt.scatter(self.X_train[nearest[i], 0], self.X_train[nearest[i], 1], color=color) |
| 147 | classCount = {} |
| 148 | for i in range(0, k): |
| 149 | voteLabel = topk_y[i] |
| 150 | weight = gaussian(distances[nearest[i]]) |
| 151 | # print(index, dist[index],weight) |
| 152 | ## 这里不再是加一,而是权重*1 |
| 153 | classCount[voteLabel] = classCount.get(voteLabel, 0) + weight * 1 |
| 154 | |
| 155 | maxCount = 0 |
| 156 | |
| 157 | for key, value in classCount.items(): |
| 158 | if value > maxCount: |
| 159 | maxCount = value |
| 160 | classes = key |
| 161 | # select the type of max num |
| 162 | y_p.append(classes) |
| 163 | if topk_y[i] == 'pear': |
| 164 | color = 'b' |
| 165 | elif topk_y[i] == 'poplar': |
| 166 | color = 'y' |
| 167 | else: |
| 168 | color = 'g' |
| 169 | plt.scatter(x_p[0], x_p[1], color=color, s=100, edgecolors='r') |
| 170 | # plt.savefig("./Pictures/result.png") # 保存原始数据分布图 |
| 171 | |
| 172 | return y_p |
| 173 | |
| 174 | |
| 175 | def visualize(self, ssler, x, y) : |
nothing calls this directly
no test coverage detected