参考资源
北京大学人工智能实践:Tensorflow笔记
上诉视频里面教我们一步一步如何制作属于自己的数据集。我自己通过实现了制作自己的数据改出了结合出了这篇文章。我会把改动的地方标识出来。
自制数据集讲解视频
import tensorflow as tf
from PIL import Image
import numpy as np
import os
from tensorflow.keras import backend as K #转换为张量
# 以下都是自己本地的图片数据的地址,以及保存的位置。(原视频是用了手写数字的数据集)
train_path = '../data/malan/'
train_txt = '../data/code.txt'
x_train_savepath = '../data/1.npy'
y_train_savepath = '../data/2.npy'
test_path = '../data/malan/'
test_txt = '../data/test.txt'
x_test_savepath = '../data/test1.npy'
y_test_savepath = '../data/test2.npy'
def generateds(path, txt): # path 图片的路径
f = open(txt, 'r') # 以只读形式打开txt文件
contents = f.readlines() # 读取文件中所有行
f.close() # 关闭txt文件
x, y_ = [], [] # 建立空列表
for content in contents: # 逐行取出
value = content.split() # 以空格分开,图片路径为value[0] , 标签为value[1] , 存入列表
img_path = path + value[0] # 拼出图片路径和文件名
#img = Image.open(img_path) # 读入图片 视频的读入图片方法
img_raw = tf.io.read_file(img_path) # 读入图片 用os读入图片的方式
img_tensor = tf.image.decode_image(img_raw)
# 原视频的手写数字的图片的大小是28*28 那样弄得太小了 所以我修改一下
img = tf.image.resize(img_tensor, [192, 192])
# 图片变为8位宽灰度值的np.array格式 原视频的图片都是灰度图 这里我是彩图需要变成灰度的自行把下面取消注释
#img = np.array(img.convert('L'))
img = img / 255. # 数据归一化 (实现预处理)
x.append(img) # 归一化后的数据,贴到列表x
y_.append(value[1]) # 标签贴到列表y_
print('loading : ' + content) # 打印状态提示
x = np.array(x) # 变为np.array格式
y_ = np.array(y_) # 变为np.array格式
y_ = y_.astype(np.int64) # 变为64位整型
return x, y_ # 返回输入特征x,返回标签y_
if os.path.exists(x_train_savepath) and os.path.exists(y_train_savepath) and os.path.exists(
x_test_savepath) and os.path.exists(y_test_savepath):
print('-------------Load Datasets-----------------')
# allow_pickle=True 具体其作用了不清楚 好像是numpy的硬件什么的
x_train_save = np.load(x_train_savepath, allow_pickle=True)
y_train = np.load(y_train_savepath, allow_pickle=True)
x_test_save = np.load(x_test_savepath, allow_pickle=True)
y_test = np.load(y_test_savepath, allow_pickle=True)
x_train = np.reshape(x_train_save, (len(x_train_save), 3, 192, 192)) # 图片是三通道的所以这里reshape应该注意后面得加3 192 192 图片通道及图片大小
x_test = np.reshape(x_test_save, (len(x_test_save), 3, 192, 192))
else:
print('-------------Generate Datasets-----------------')
x_train, y_train = generateds(train_path, train_txt)
x_test, y_test = generateds(test_path, test_txt)
print('-------------Save Datasets-----------------')
x_train_save = np.reshape(x_train, (len(x_train), -1))
x_test_save = np.reshape(x_test, (len(x_test), -1))
np.save(x_train_savepath, x_train_save)
np.save(y_train_savepath, y_train)
np.save(x_test_savepath, x_test_save)
np.save(y_test_savepath, y_test)
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax') # 10 个输出层 代表了0-9十个数字,自己修改成自己的图片分类的类别数目 这里修改app 对应的也得修改。
])
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
metrics=['sparse_categorical_accuracy'])
x_train = K.cast_to_floatx(x_train)
y_train = K.cast_to_floatx(y_train)
model.fit(x_train, y_train, batch_size=3, epochs=50, validation_data=(x_test, y_test), validation_freq=1)
model.summary()
#model.save(filepath=) 自己选择路径保存这里的神经网络层数不多其易实现。
#
checkpoint_save_path = "./checkpoint2/qf.ckpt"
if os.path.exists(checkpoint_save_path + '.index'):
print('-------------load the model-----------------')
model.load_weights(checkpoint_save_path)
cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path,
save_weights_only=True,
save_best_only=True)
history = model.fit(x_train, y_train, batch_size=2, epochs=5, validation_data=(x_test, y_test), validation_freq=1,
callbacks=[cp_callback])
print(model.trainable_variables)
file = open('./weights.txt', 'w')
for v in model.trainable_variables:
file.write(str(v.name) + '\n')
file.write(str(v.shape) + '\n')
file.write(str(v.numpy()) + '\n')
file.close()
app.py
给图识物老师的讲解视频
import tensorflow as tf
model_save_path = './checkpoint/qf.ckpt'
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')])
model.load_weights(model_save_path)
preNum = int(input("input the number of test pictures:"))
for i in range(preNum):
image_path = "../data/malan/malan_"
image_path += input("the path of test picture:")
image_path += ".jpg"
print(image_path)
img_raw = tf.io.read_file(image_path)
img_tensor = tf.image.decode_image(img_raw)
img = tf.image.resize(img_tensor, [192, 192])
# img = np.array(img.convert('L')) # 图片变为8位宽灰度值的np.array格式
# 数据归一化 (实现预处理)
img_arr = img / 255.0
print("img_arr:", img_arr.shape)
x_predict = img_arr[tf.newaxis, ...]
print("x_predict:", x_predict.shape)
result = model.predict(x_predict)
pred = tf.argmax(result, axis=1)
print('\n')
tf.print(pred)
上诉的视频mooc可以看,也有人上传的B站,可以去观看。