from keras.optimizers import SGD、from keras.utils import to_categorical报错

本文介绍如何将使用Keras库编写的代码迁移到TensorFlow框架中,具体包括两个关键部分:导入优化器SGD及实用工具to_categorical的方法更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

将from keras.optimizers import SGD 改为:

from tensorflow.keras.optimizers import SGD

将from keras.utils import to_categorical 改为:

from tensorflow.keras.utils import to_categorical

试试

import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense,Dropout,Convolution2D,MaxPooling2D,Flatten from tensorflow.keras.optimizers import Adam,SGD from tensorflow.keras.utils import to_categorical import numpy as np mnist = tf.keras.datasets.mnist (x_train,y_train) ,(x_test,y_test) = mnist.load_data() x_train = x_train.reshape(x_train.shape[0],-1)/255 x_test = x_test.reshape(x_test.shape[0],-1)/255 y_train = to_categorical(y_train,num_classes=10) # convert to one hot format y_test = to_categorical(y_test,num_classes=10) model = Sequential() model.add(Dense(units=30, #输出维度,表示有几个神经元 input_dim=784, #输入尺寸 activation='sigmoid', name='lay1')) model.add(Dense(units=10, #输出维度,表示有几个神经元 activation='sigmoid', name='lay2')) # sgd = SGD(lr=0.2) from tensorflow.keras import optimizers sgd = optimizers.SGD(learning_rate=0.2) model.compile( optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001), loss = 'categorical_crossentropy', metrics= ['accuracy'] ) model.fit(x_train, y_train, batch_size=64, epochs=50) loss,accuracy = model.evaluate(x_test,y_test) print(loss) print('accuracy',accuracy) weight_Dense,bias_Dense = model.get_layer('lay1').get_weights() np.savetxt('weight1.txt',weight_Dense,fmt='%.06f,') np.savetxt('bias1.txt',bias_Dense,fmt='%.06f,') # print(weight_Dense,bias_Dense) weight_Dense,bias_Dense = model.get_layer('lay2').get_weights() np.savetxt('weight2.txt',weight_Dense,fmt='%.06f,') np.savetxt('bias2.txt',bias_Dense,fmt='%.06f,') # print(weight_Dense,bias_Dense) model.save('2lays.h5') 以上代码的功能
最新发布
07-24
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值