{ "cells": [ { "cell_type": "code", "execution_count": 2, "id": "8ec813b5-ae63-40d8-9fe2-82d19373afa5", "metadata": { "tags": [] }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/Applications/Anaconda3/anaconda3/lib/python3.11/site-packages/sklearn/datasets/_openml.py:1002: FutureWarning: The default value of `parser` will change from `'liac-arff'` to `'auto'` in 1.4. You can set `parser='auto'` to silence this warning. Therefore, an `ImportError` will be raised from 1.4 if the dataset is dense and pandas is not installed. Note that the pandas parser may return different data types. See the Notes Section in fetch_openml's API doc for details.\n", " warn(\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Accuracy: 97.64%\n", "Training time: 182.25 seconds\n" ] } ], "source": [ "import numpy as np\n", "from sklearn import svm\n", "from sklearn.metrics import accuracy_score\n", "from sklearn.datasets import fetch_openml\n", "from sklearn.model_selection import train_test_split\n", "import time\n", "\n", "# 下载和加载MNIST数据集\n", "X, y = fetch_openml('mnist_784', version=1, return_X_y=True)\n", "X = X / 255.0 # 将图像像素值缩放到0-1范围\n", "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", "\n", "# 创建SVM分类器\n", "clf = svm.SVC()\n", "\n", "# 训练模型\n", "start_time = time.time()\n", "clf.fit(X_train, y_train)\n", "end_time = time.time()\n", "\n", "# 在测试集上进行预测\n", "y_pred = clf.predict(X_test)\n", "\n", "# 计算准确率\n", "accuracy = accuracy_score(y_test, y_pred)\n", "print(\"Accuracy: {:.2f}%\".format(accuracy * 100))\n", "\n", "# 打印训练时间\n", "training_time = end_time - start_time\n", "print(\"Training time: {:.2f} seconds\".format(training_time))\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.5" } }, "nbformat": 4, "nbformat_minor": 5 }