<jupyter_start><jupyter_text>Recognizing hand-written digitsAn example showing how the scikit-learn can be used to recognize images ofhand-written digits.This example is commented in the`tutorial section of the user manual `.<jupyter_code># Standard scientific Python imports
import matplotlib.pyplot as plt
import numpy as np

# Import datasets, classifiers and performance metrics
from sklearn import datasets, svm, metrics
from sklearn.neighbors import KNeighborsClassifier, NearestNeighbors

from ipywidgets import interact_manual
# The digits dataset
digits = datasets.load_digits()
# The data that we are interested in is made of 8x8 images of digits, let's
# have a look at the first 4 images, stored in the `images` attribute of the
# dataset.  If we were working from image files, we could load them using
# matplotlib.pyplot.imread.  Note that each image must have the same size. For these
# images, we know which digit they represent: it is given in the 'target' of
# the dataset.
images_and_labels = list(zip(digits.images, digits.target))
for index, (image, label) in enumerate(images_and_labels[:4]):
    plt.subplot(2, 4, index + 1)
    plt.axis('off')
    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
    plt.title('Training: %i' % label)
    plt.show()
# To apply a classifier on this data, we need to flatten the image, to
# turn the data in a (samples, feature) matrix:
n_samples = len(digits.images)
data = digits.images.reshape((n_samples, -1))
# Create a classifier: a support vector classifier
classifier = svm.SVC(gamma=0.001)

# We learn the digits on the first half of the digits
classifier.fit(data[:n_samples // 2], digits.target[:n_samples // 2])
# Now predict the value of the digit on the second half:
expected = digits.target[n_samples // 2:]
predicted = classifier.predict(data[n_samples // 2:])

print("Classification report for classifier %s:\n%s\n"
      % (classifier, metrics.classification_report(expected, predicted)))
print("Confusion matrix:\n%s" % metrics.confusion_matrix(expected, predicted))
images_and_predictions = list(zip(digits.images[n_samples // 2:], predicted))
for index, (image, prediction) in enumerate(images_and_predictions[:4]):
    plt.subplot(2, 4, index + 5)
    plt.axis('off')
    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
    plt.title('Prediction: %i' % prediction)
plt.show()<jupyter_output><empty_output><jupyter_text>Clasificador de Vecinos Cercanos<jupyter_code>neigh = None

@interact_manual(k=(1, 20))
def make_nn_classifier(k):
    global neigh
    neigh = KNeighborsClassifier(n_neighbors=k)
    print('training...')
    neigh.fit(data[:n_samples // 2], digits.target[:n_samples // 2])
    print('done!')
    print(neigh)
# Now predict the value of the digit on the second half:
expected = digits.target[n_samples // 2:]
predicted = neigh.predict(data[n_samples // 2:])

print("Classification report for classifier %s:\n%s\n"
      % (neigh, metrics.classification_report(expected, predicted)))
print("Confusion matrix:\n%s" % metrics.confusion_matrix(expected, predicted))
images_and_predictions = list(zip(digits.images[n_samples // 2:], predicted))
for index, (image, prediction) in enumerate(images_and_predictions[:4]):
    plt.subplot(2, 4, index + 5)
    plt.axis('off')
    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
    plt.title('Prediction: %i' % prediction)
plt.show()<jupyter_output><empty_output><jupyter_text>KNN No Supervisado<jupyter_code>neigh = None
kk = None
rr = None
algo = None
@interact_manual(k=(1, 20), 
                 r=(0, 50, 0.1),
                 algorithm=['auto', 'ball_tree', 'kd_tree', 'brute'])
def make_knn(k, r, algorithm):
    global neigh
    global kk, rr, algo
    kk, rr, algo = k, r, algorithm
    neigh = NearestNeighbors(n_neighbors=k, radius=r, algorithm=algorithm)
    print('training...')
    neigh.fit(data[:n_samples // 2])
    print('done!')
    print(neigh)
# Now predict the value of the digit on the second half:
distances, indices = neigh.kneighbors(data[n_samples // 2:], 4)
distances
indices
neigh.kneighbors_graph(data[n_samples // 2:], n_neighbors=kk).toarray()
help(neigh.kneighbors_graph)<jupyter_output>Help on method kneighbors_graph in module sklearn.neighbors.base:

kneighbors_graph(X=None, n_neighbors=None, mode='connectivity') method of sklearn.neighbors.unsupervised.NearestNeighbors instance
    Computes the (weighted) graph of k-Neighbors for points in X
    
    Parameters
    ----------
    X : array-like, shape (n_query, n_features),                 or (n_query, n_indexed) if metric == 'precomputed'
        The query point or points.
        If not provided, neighbors of each indexed point are returned.
        In this case, the query point is not considered its own neighbor.
    
    n_neighbors : int
        Number of neighbors for each sample.
        (default is value passed to the constructor).
    
    mode : {'connectivity', 'distance'}, optional
        Type of returned matrix: 'connectivity' will return the
        connectivity matrix with ones and zeros, in 'distance' the
        edges are Euclidean distance between points.
    
    Returns
    -------
    A : spar[...]
{'fraction_non_alphanumeric': 0.11426925292874976, 'fraction_numerical': 0.008642212406376032, 'mean_word_length': 4.208, 'pattern_counts': {'":': 0, '<': 12, '<?xml version=': 0, '>': 12, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '56813', 'license': 'MIT', 'n_tokens_mistral': 1730, 'n_tokens_neox': 1628, 'n_words': 501, 'path': 'plot_digits_classification.ipynb', 'repo_name': 'alorozco53/RPYAApublic', 'size': '5207'}