import numpy as np
import paddle
print("当前paddle版本为{}".format(paddle.__version__))
import os
data_path = r"I:\数据集\手势识别\Dataset\Dataset"
character_folders = os.listdir(data_path)
if os.path.exists(r"I:\数据集\手势识别\Dataset\test_data.txt"):
os.remove(r"I:\数据集\手势识别\Dataset\train_data.txt")
if os.path.exists(r"I:\数据集\手势识别\Dataset\test_data.txt"):
os.remove(r"I:\数据集\手势识别\Dataset\test_data.txt")
for character_folder in character_folders:
with open(r"I:\数据集\手势识别\Dataset\test_data.txt", 'a') as f_test:
with open(r"I:\数据集\手势识别\Dataset\train_data.txt", 'a') as f_train:
character_imgs = os.listdir(os.path.join(data_path, character_folder))
count = 0
for img in character_imgs:
if count % 10 == 0:
f_test.write(os.path.join(data_path, character_folder, img) + '\t' + character_folder + '\n')
else:
f_train.write(os.path.join(data_path, character_folder, img) + '\t' + character_folder + '\n')
count += 1
print("列表已生成")
from PIL import Image
class FoodDataset(paddle.io.Dataset):
def __init__(self, mode='train_data'):
self.data = []
with open(f'I:/数据集/手势识别/Dataset/{mode}.txt', 'r') as f:
for line in f.readlines():
info = line.strip().split('\t')
if len(info) > 0:
self.data.append([info[0].strip(), info[1].strip()])
def __getitem__(self, index):
image_file, label = self.data[index]
img = Image.open(image_file)
img = img.resize((100, 100), Image.ANTIALIAS)
img = np.array(img).astype('float32')
img = img.transpose((2, 0, 1))
img = img / 255.0
return img, np.array(label, dtype='int64')
def __len__(self):
return len(self.data)
train_dataset = FoodDataset(mode='train_data')
eval_dataset = FoodDataset(mode='test_data')
print('train大小:', train_dataset.__len__())
print('eval大小:', eval_dataset.__len__())
from paddle.nn import Linear
import paddle.nn.functional as F
import paddle
Net = paddle.nn.Sequential(
Linear(100, 100),
paddle.nn.ReLU(),
Linear(100, 100),
paddle.nn.ReLU(),
Linear(100, 100),
paddle.nn.ReLU(),
paddle.nn.Flatten(),
Linear(3 * 100 * 100, 10),
paddle.nn.Softmax()
)
paddle.summary(Net, (1, 3, 100, 100))
model = paddle.Model(Net)
model.prepare(paddle.optimizer.Adam(learning_rate=0.001, parameters=model.parameters()),
paddle.nn.CrossEntropyLoss(),
paddle.metric.Accuracy())
model.fit(train_dataset,
eval_dataset,
epochs=5,
batch_size=64,
verbose=1,
)
result = model.evaluate(eval_dataset, verbose=1)
print(result)
model.save(r'F:\PyCharm\PyCharm文件\手势识别')
|