keras 3_mnist数据集分类_交叉熵

文章目录

import numpy as np
from keras.datasets import mnist
from keras.utils import np_utils        # 导入keras提供的numpy工具包
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import SGD

# 载入数据
(x_train,y_train),(x_test,y_test) = mnist.load_data()
print("x_shape:",x_train.shape,"y_shape:",y_train.shape)

# 将数据转换由(60000,28,28)转换为(60000,784,并进行归一化除以255
x_train = x_train.reshape(x_train.shape[0],-1)/255.0
x_test = x_test.reshape(x_test.shape[0], -1)/255.0
print(x_train.shape,x_test.shape)

# 将数据转换为one-hot编码的格式
y_train = np_utils.to_categorical(y_train, num_classes=10)
y_test = np_utils.to_categorical(y_test, num_classes=10)

# 创建模型,输入是784个神经元,输出为10个神经元
model = Sequential(
    [Dense(units=10,input_dim=784,bias_initializer="one",activation="softmax")]
)

# 自定义优化器
sgd=SGD(lr=0.01)
# 编译模型,定义优化器,loss_function,训练过程中计算准确率
# model.compile(optimizer=sgd,loss="mse",metrics=["accuracy"],)   # 使用均方差作为损失函数
model.compile(optimizer=sgd,loss="categorical_crossentropy",metrics=["accuracy"],)   # 使用交叉熵作为损失函数

# 喂入数据集,并规定每次喂入32张图像,设定迭代周期
model.fit(x_train,y_train,batch_size=32,epochs=100)

# 评估模型
loss,accuracy = model.evaluate(x_test, y_test)
print("test losee:",loss,"accuracy:",accuracy)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值