【机器学习】多层神经网络实验

环境安装

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple scikit-learn
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple keras

image

tensorflow-cpu 2.4.0
scikit-learn 1.0.2

image

image

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()

运行结果

image

image

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

萌狼蓝天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值