Knn algorithm using iris dataset

Monalisha: <p>so i am doing a code in jupyter notebook on knn algorithm in which one step has error, n i dont know how to fix this… so can anyone help? so here is the code:</p>
<h1>
<a name="calculating-errors-1" class="anchor" href="#calculating-errors-1"></a>Calculating errors</h1>
<p>train_error= []<br>
test_error= []</p>
<p>for k in range(1, 31):<br>
knn= KNeighborsClassifier(n_neighbors=k)<br>
knn.fit(X_train_scaled, y_train)</p>
<pre><code>y_pred1= knn.predict(X_train_scaled)
train_error.append(np.mean(y_train!=y_pred1))

y_pred2= knn.predict(X_test_scaled)
test_error.append(np.mean(y_test!=y_pred2))
</code></pre>
<h1>
<a name="plotting-error-curve-2" class="anchor" href="#plotting-error-curve-2"></a>Plotting error curve</h1>
<p>plt.figure(figsize=(10, 5))<br>
plt.plot(range(1, 15), train_error, color=‘b’, label=“Train”)<br>
plt.plot(range(1, 15), test_error, color=‘r’, label=“Test”)<br>
plt.xlabel(‘Number of nearest neighbors (k)’, fontsize=14)<br>
plt.ylabel(‘Error’, fontsize=14)<br>
plt.title(‘Finding optimal value of K using error curves’, fontsize=18, pad=15)<br>
plt.legend()<br>
plt.show()<br>
n here is the error:<br>
ValueError                                Traceback (most recent call last)<br>
Input In [8], in &lt;cell line: 17&gt;()<br>
15 # Plotting error curve<br>
16 plt.figure(figsize=(10, 5))<br>
—&gt; 17 plt.plot(range(1, 15), train_error, color=‘b’, label=“Train”)<br>
18 plt.plot(range(1, 15), test_error, color=‘r’, label=“Test”)<br>
19 plt.xlabel(‘Number of nearest neighbors (k)’, fontsize=14)</p>
<p>File ~\anaconda3\lib\site-packages\matplotlib\pyplot.py:2757, in plot(scalex, scaley, data, *args, **kwargs)<br>
2755 <span class="mention">@_copy_docstring_and_deprecators</span>(Axes.plot)<br>
2756 def plot(*args, scalex=True, scaley=True, data=None, **kwargs):<br>
 → 2757     return gca().plot(<br>
2758         *args, scalex=scalex, scaley=scaley,<br>
2759         **({“data”: data} if data is not None else {}), **kwargs)</p>
<p>File ~\anaconda3\lib\site-packages\matplotlib\axes_axes.py:1632, in Axes.plot(self, scalex, scaley, data, *args, **kwargs)<br>
1390 “”"<br>
1391 Plot y versus x as lines and/or markers.<br>
1392<br>
(…)<br>
1629 (<code>'green'</code>) or hex strings (<code>'#008000'</code>).<br>
1630 “”"<br>
1631 kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D)<br>
 → 1632 lines = [*self._get_lines(*args, data=data, **kwargs)]<br>
1633 for line in lines:<br>
1634     self.add_line(line)</p>
<p>File ~\anaconda3\lib\site-packages\matplotlib\axes_base.py:312, in _process_plot_var_args.<strong>call</strong>(self, data, *args, **kwargs)<br>
310     this += args[0],<br>
311     args = args[1:]<br>
 → 312 yield from self._plot_args(this, kwargs)</p>
<p>File ~\anaconda3\lib\site-packages\matplotlib\axes_base.py:498, in _process_plot_var_args._plot_args(self, tup, kwargs, return_kwargs)<br>
495     self.axes.yaxis.update_units(y)<br>
497 if x.shape[0] != y.shape[0]:<br>
 → 498     raise ValueError(f"x and y must have same first dimension, but "<br>
499                      f"have shapes {x.shape} and {y.shape}“)<br>
500 if x.ndim &gt; 2 or y.ndim &gt; 2:<br>
501     raise ValueError(f"x and y can be no greater than 2D, but have "<br>
502                      f"shapes {x.shape} and {y.shape}”)</p>
<p>ValueError: x and y must have same first dimension, but have shapes (14,) and (30,)</p>

ptrblck: <p>The error is raised in <code>plt.plot(range(1, 15), train_error, color='b', label="Train")</code> as the <code>x</code> value (first argument passed as <code>range(1, 15)</code>) has a shape of <code>(14,)</code> while the <code>y</code> argument (second argument passed as <code>train_error</code>) has a shape of <code>(30,)</code>.<br>
You could try to use <code>range(len(train_error))</code> or remove the first argument.</p>
<p>Note that your use case doesn’t seem to be PyTorch-related, so you might get a faster response in other discussion boards. <img src="https://discuss.pytorch.org/images/emoji/apple/wink.png?v=12" title=":wink:" class="emoji" alt=":wink:" loading="lazy" width="20" height="20"></p>
<p>PS: you can post code snippets by wrapping them into three backticks ```, which makes debugging easier.</p>