{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-10-26T16:37:26.396015Z","iopub.execute_input":"2023-10-26T16:37:26.396456Z","iopub.status.idle":"2023-10-26T16:37:26.874021Z","shell.execute_reply.started":"2023-10-26T16:37:26.396424Z","shell.execute_reply":"2023-10-26T16:37:26.872731Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import datasets\nfrom sklearn import svm\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import accuracy_score\n\n# Загружаем MNIST данные\ndigits = datasets.load_digits()","metadata":{"execution":{"iopub.status.busy":"2023-10-26T16:37:26.876241Z","iopub.execute_input":"2023-10-26T16:37:26.876739Z","iopub.status.idle":"2023-10-26T16:37:26.905088Z","shell.execute_reply.started":"2023-10-26T16:37:26.876706Z","shell.execute_reply":"2023-10-26T16:37:26.903851Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Масштабируем данные\nscaler = StandardScaler()\nscaler.fit(digits.data)\nX_scaled = scaler.transform(digits.data)\n\n# Применяем PCA\npca = PCA(n_components=40)\nX_pca = pca.fit_transform(X_scaled)","metadata":{"execution":{"iopub.status.busy":"2023-10-26T16:37:26.907281Z","iopub.execute_input":"2023-10-26T16:37:26.907748Z","iopub.status.idle":"2023-10-26T16:37:27.035924Z","shell.execute_reply.started":"2023-10-26T16:37:26.907706Z","shell.execute_reply":"2023-10-26T16:37:27.033825Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Разделение данных на обучающую и тестовую выборки\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test, y_train, y_test = train_test_split(X_pca, digits.target, test_size=0.3, random_state=42)","metadata":{"execution":{"iopub.status.busy":"2023-10-26T16:37:27.040241Z","iopub.execute_input":"2023-10-26T16:37:27.040951Z","iopub.status.idle":"2023-10-26T16:37:27.057426Z","shell.execute_reply.started":"2023-10-26T16:37:27.040893Z","shell.execute_reply":"2023-10-26T16:37:27.055210Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Обучение классификатора\nclf = svm.SVC(gamma=0.001, C=100.)\nclf.fit(X_train, y_train)","metadata":{"execution":{"iopub.status.busy":"2023-10-26T16:37:27.060184Z","iopub.execute_input":"2023-10-26T16:37:27.060931Z","iopub.status.idle":"2023-10-26T16:37:27.170131Z","shell.execute_reply.started":"2023-10-26T16:37:27.060863Z","shell.execute_reply":"2023-10-26T16:37:27.168956Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Проверка точности\ny_pred = clf.predict(X_test)\nprint('Accuracy: ', accuracy_score(y_test, y_pred))","metadata":{"execution":{"iopub.status.busy":"2023-10-26T16:37:27.171642Z","iopub.execute_input":"2023-10-26T16:37:27.172026Z","iopub.status.idle":"2023-10-26T16:37:27.202073Z","shell.execute_reply.started":"2023-10-26T16:37:27.171994Z","shell.execute_reply":"2023-10-26T16:37:27.200875Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Выбираем несколько случайных изображений из тестовой выборки и поверяем предсказания\nnum_samples = 5\nindices = np.random.choice(range(len(X_test)), num_samples)\n\nfor i, idx in enumerate(indices):\n    img_reconstructed = scaler.inverse_transform(pca.inverse_transform(X_test[idx].reshape(1, -1)))\n    img_reconstructed = img_reconstructed.reshape(8, 8)\n    pred = clf.predict(X_test[idx].reshape(1, -1))\n\n    plt.figure(figsize=(3, 3))\n    plt.imshow(img_reconstructed, cmap='gray')\n    plt.title(f\"Predicted label: {pred[0]}\")\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2023-10-26T16:37:27.203748Z","iopub.execute_input":"2023-10-26T16:37:27.204159Z","iopub.status.idle":"2023-10-26T16:37:28.646336Z","shell.execute_reply.started":"2023-10-26T16:37:27.204127Z","shell.execute_reply":"2023-10-26T16:37:28.645083Z"},"trusted":true},"execution_count":null,"outputs":[]}]}