环境安装
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple scikit-learn
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple keras
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt
# 加载数据
iris = load_iris()
X=iris.data
y=iris.target
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2,random_state=42)
# 数据预处理
X_train=(X_train-np.mean(X_train,axis=0))/np.std(X_train,axis=0)
X_test=(X_test-np.mean(X_test,axis=0))/np.std(X_test,axis=0)
# 构建多层神经网络模型
model = Sequential()
model.add(Dense(64,activation="relu",input_shape=(4,)))
model.add(Dense(64,activation="relu"))
model.add(Dense(3,activation="softmax"))
# 编译模型
model.compile(optimizer="adam",loss="sparse_categorical_crossentropy",metrics=['accuracy'])
# 训练模型
history=model.fit(X_train,y_train,epochs=100,batch_size=32,validation_split=0.2)
# 评估模型
loss,accuracy=model.evaluate(X_test,y_test)
print("测试集上的损失:",loss)
print("测试集上的准确率:",accuracy)
# 可视化训练过程中的损失和准确率变化
plt.figure(figsize=(12,4))
plt.subplot(1,2,1)
plt.plot(history.history['loss'],label="Train Loss")
plt.plot(history.history["val_loss"],label="validation Loss")
plt.xlabel("Epoch")
plt.ylabel("Loss")
plt.legend()
plt.subplot(1,2,2)
plt.plot(history.history['accuracy'],label="Train Accuracy")
plt.plot(history.history["val_accuracy"],label="validation Accuracy")
plt.xlabel("Epoch")
plt.ylabel("Accuracy")
plt.legend()
plt.show()
标签:plt,机器,多层,神经网络,train,test,import,model,history
From: https://www.cnblogs.com/mllt/p/18243227/py_ai_base_test04