根据上述问题写出python代码
时间: 2024-12-26 09:04:23 浏览: 8
当然,以下是使用Python和scikit-learn实现感知机和神经网络在MNIST数据集上进行简单分类的一个示例代码:
```python
# 导入所需库
from sklearn.datasets import fetch_openml
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Perceptron
from keras.models import Sequential
from keras.layers import Dense
from sklearn.metrics import accuracy_score, plot_loss
# 1. 获取数据集
mnist = fetch_openml('mnist_784', version=1)
X = mnist.data.astype('float32') / 255.
y = mnist.target
# 2. 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 3. 预处理数据
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# 4. 实现感知机
perceptron = Perceptron(max_iter=10, random_state=42)
perceptron.fit(X_train, y_train)
# 训练感知机
y_pred_perceptron = perceptron.predict(X_test)
print(f"Perceptron accuracy: {accuracy_score(y_test, y_pred_perceptron)}")
# 5. 实现神经网络(使用Keras)
model = Sequential([
Dense(64, activation='relu', input_shape=(784,)),
Dense(10, activation='softmax')
])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
history = model.fit(X_train, y_train, epochs=5, validation_data=(X_test, y_test))
# 6. 可视化结果
plot_loss(history.history['loss'], history.history['val_loss'])
plt.title("Loss vs Epochs")
plt.show()
# 神经网络预测
y_pred_neural_network = model.predict_classes(X_test)
print(f"Neural Network accuracy: {accuracy_score(y_test, y_pred_neural_network)}")
```
阅读全文