用python写人工智能程序
时间: 2023-11-17 07:06:45 浏览: 108
作为AI语言, Python可以用于编写各种人工智能程序,下面是一个简单的例子,使用Python编写一个基于机器学习的手写数字识别程序。
首先,我们需要导入必要的库,包括numpy用于矩阵运算、matplotlib用于绘图、scikit-learn用于机器学习。
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
```
接着,我们加载手写数字数据集,其中包含了1797个数字图像,每个图像由8x8个像素组成,每个像素的取值范围为0~16。
```python
digits = load_digits()
X, y = digits.data, digits.target
```
我们可以随机选择几个图像进行可视化,以便更好地了解数据集。
```python
fig, axes = plt.subplots(4, 4)
for i, ax in enumerate(axes.flat):
ax.imshow(X[i].reshape(8, 8), cmap='gray')
ax.set_xticks([])
ax.set_yticks([])
plt.show()
```
接着,我们将数据集划分为训练集和测试集,其中75%的数据用于训练,25%的数据用于测试。
```python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
```
然后,我们使用SVM算法进行训练,并对测试集进行预测。
```python
clf = SVC(kernel='linear')
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
```
最后,我们可以计算模型的准确率,并输出混淆矩阵以进一步评估模型的性能。
```python
acc = np.mean(y_pred == y_test)
print("Accuracy:", acc)
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)
print("Confusion matrix:\n", cm)
```
完整代码如下:
```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
digits = load_digits()
X, y = digits.data, digits.target
fig, axes = plt.subplots(4, 4)
for i, ax in enumerate(axes.flat):
ax.imshow(X[i].reshape(8, 8), cmap='gray')
ax.set_xticks([])
ax.set_yticks([])
plt.show()
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
clf = SVC(kernel='linear')
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
acc = np.mean(y_pred == y_test)
print("Accuracy:", acc)
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)
print("Confusion matrix:\n", cm)
```
阅读全文