paddle_temp
作者:互联网
import paddle
from paddle.io import Dataset
BATCH_SIZE = 64
BATCH_NUM = 20
IMAGE_SIZE = [17]
CLASS_NUM = 5
import numpy as np
class MyDataset(Dataset):
"""
步骤一:继承paddle.io.Dataset类
"""
def __init__(self, num_samples):
"""
步骤二:实现构造函数,定义数据集大小
"""
super(MyDataset, self).__init__()
self.num_samples = num_samples
self.data = np.random.randn(5,17)
def __getitem__(self, index):
"""
步骤三:实现__getitem__方法,定义指定index时如何获取数据,并返回单条数据(训练数据,对应的标签)
"""
# data = paddle.uniform(IMAGE_SIZE, dtype='float32')
# print(type(data))
data = self.data[index].reshape(17)
# data = np.dtype(np.float32)
data = data.astype(np.float32)
# label = paddle.randint(0, CLASS_NUM-1, dtype='int64')
label = np.array(np.random.randint(4)).reshape(1)
print(label)
return data, label
def __len__(self):
"""
步骤四:实现__len__方法,返回数据集总数目
"""
return self.num_samples
# 测试定义的数据集
custom_dataset = MyDataset(5)
print('=============custom dataset=============')
for data, label in custom_dataset:
print(data.shape, label.shape)
print(data, label)
break
mnist = paddle.nn.Sequential(
paddle.nn.Flatten(),
paddle.nn.Linear(17, 512),
paddle.nn.ReLU(),
paddle.nn.Dropout(0.2),
paddle.nn.Linear(512, 5)
)
# 预计模型结构生成模型对象,便于进行后续的配置、训练和验证
model = paddle.Model(mnist)
# 模型训练相关配置,准备损失计算方法,优化器和精度计算方法
model.prepare(paddle.optimizer.Adam(parameters=model.parameters()),
paddle.nn.CrossEntropyLoss(),
paddle.metric.Accuracy())
# 开始模型训练
model.fit(custom_dataset,
epochs=5,
batch_size=64,
verbose=1)
标签:__,nn,temp,self,paddle,label,data 来源: https://www.cnblogs.com/hiccuplh/p/16217501.html