0插入语
本人显卡1050 2G性能不足,因此将resnet18([2,2,2,2])改为了resnet10([1,1,1,1]),并且在cirfar100数据集为50000的情况下,将batchsiz设置为了8.显卡配置过关的同学请将本程序中的这两块改回去。
解决方法:使用Google的Colab,本人将在下一篇博客中介绍利用Colab跑tf
1主程序
import tensorflow as tf
from tensorflow.keras import layers, optimizers, datasets, Sequential
import os
from resnet import resnet18
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
tf.random.set_seed(2345)
# 4)设置下加载的数据集
# 4.1)预处理一下
def preprocess(x, y):
# [-1~1]
x = 2 * tf.cast(x, dtype=tf.float32)/255. - 1
y = tf.cast(y, dtype=tf.int32)
return x, y
# 4.2)数据的加载
# 此处按道理来讲tf会自动从官网上下载,但是由于数据量太大100多兆,容易出错(链接更新了),或者时间很慢
# 因此百度数据集提前下载好,放在文件夹“C:\Users\wanfuchun\.keras\datasets”无需解压,程序会自动解压
(x, y), (x_test, y_test) = datasets.cifar100.load_data()
y = tf.squeeze(y, axis=1) # axis=1,把‘1’维度挤压掉
y_test = tf.squeeze(y_test, axis=1) # axis=1,把‘1’维度挤压掉
print(x.shape, y.shape, x_test.shape, y_test.shape)
# 5)设置下dataset
train_db = tf.data.Dataset.from_tensor_slices((x, y))
train_db = train_db.shuffle(1000).map(preprocess).batch(8)
test_db = tf.data.Dataset.from_tensor_slices((x_test, y_test))
test_db = test_db.map(preprocess).batch(8)
sample = next(iter(train_db))
print('sample:', sample[0].shape, sample[1].shape,
tf.reduce_min(sample[0]), tf.reduce_max(sample[0]))
def main():
# 测试代码:
# [b, 32, 32, 3] => [b, 1, 1, 3]
model = resnet18()
model.build(input_shape=(None, 32, 32, 3))
model.summary()
# 8)优化器的更新
optimizer = optimizers.Adam(lr=1e-4)
# 6)到此为止,数据集的部分已经加载完了,接下来设置一个测试的部分。
for epoch in range(50):
for step, (x, y) in enumerate(train_db):
# [b, 32, 32, 3] => [b,100]
with tf.GradientTape() as tape:
# [b, 32, 32, 3] => [b, 100]
logits = model(x)
# [b] => [b, 100]
y_onehot = tf.one_hot(y, depth=100)
# compute loss
loss = tf.losses.categorical_crossentropy(y_onehot, logits, from_logits=True)
loss = tf.reduce_mean(loss)
grads = tape.gradient(loss, model.trainable_variables)
# 9)把定义好的优化器传过来
optimizer.apply_gradients(zip(grads, model.trainable_variables))
# 10)打印一下
if step%100 == 0:
print(epoch, step, 'loss:', float(loss))
# 11)测试代码:(1)这里是在每一次数据集迭代完成之后(2)也可以在每一个100个step完