飞桨AI Studio作为一款全面的AI开发平台,为AI爱好者们提供了丰富的学习资源和实践体验。然而,在学习的过程中,会遇到“无从下手”的困惑,其中最常见的问题便是作业难以完成。那么,面对这样的问题,如何做到拿到满分的作业答案呢?
以下是一些飞桨AI Studio作业的答案,希望能为你提供点帮助。
一、Python作业答案
1. 打印100以内的奇数(每行打印5个)
“`
for i in range(1, 101, 2):
print(i, end=’ ‘)
if i % 10 == 9:
print()
“`
2. 计算字符串中字母、数字、空格和其他字符的个数
“`
s = input(‘Enter a string: ‘)
letters, digits, spaces, others = 0, 0, 0, 0
for c in s:
if c.isalpha():
letters += 1
elif c.isdigit():
digits += 1
elif c.isspace():
spaces += 1
else:
others += 1
print(‘Letters:’, letters)
print(‘Digits:’, digits)
print(‘Spaces:’, spaces)
print(‘Others:’, others)
“`
二、机器学习作业答案
1. 利用飞桨完成手写数字识别(MNIST数据集)
“`
import paddle
import paddle.fluid as fluid
from paddle.fluid.dygraph.nn import Conv2D, Pool2D, Linear
from paddle.fluid.dygraph.base import to_variable
from paddle.dataset.mnist import train, test
import numpy as np
class MNIST(fluid.dygraph.Layer):
def __init__(self):
super(MNIST, self).__init__()
self.conv1 = Conv2D(num_channels=1, num_filters=6, filter_size=5, stride=1, padding=2, act=’relu’)
self.pool1 = Pool2D(pool_size=2, pool_stride=2, pool_type=’max’)
self.conv2 = Conv2D(num_channels=6, num_filters=16, filter_size=5, stride=1, padding=0, act=’relu’)
self.pool2 = Pool2D(pool_size=2, pool_stride=2, pool_type=’max’)
self.fc1 = Linear(input_DIM=16*5*5, output_dim=120, act=’relu’)
self.fc2 = Linear(input_dim=120, output_dim=84, act=’relu’)
self.fc3 = Linear(input_dim=84, output_dim=10, act=’softmax’)
def forward(self, inputs):
x = self.conv1(inputs)
x = self.pool1(x)
x = self.conv2(x)
x = self.pool2(x)
x = fluid.layers.reshape(x, [x.shape[0], -1])
x = self.fc1(x)
x = self.fc2(x)
x = self.fc3(x)
return x
# 开启动态图模式
fluid.enable_dygraph()
# 加载训练数据和测试数据
X_train, y_train = train(), train(labels=True)
X_test, y_test = test(), test(labels=True)
# 定义模型、优化器和损失
model = MNIST()
optimizer = fluid.optimizer.Adam(learning_rate=0.001, parameter_list=model.parameters())
criterion = fluid.dygraph.CrossEntropyLoss()
# 开始训练
model.train()
for epoch in range(20):
for i, (x, y) in enumerate(zip(X_train, y_train)):
x = to_variable(x.reshape([1, 1, 28, 28]).astype(np.float32))
y = to_variable(y.reshape([1]).astype(np.int64))
logits = model(x)
loss = criterion(logits, y)
loss.backward()
optimizer.minimize(loss)
model.clear_gradients()
if (i + 1) % 1000 == 0:
print(‘Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}’.format(epoch+1, 20, i+1, len(X_train), loss.numpy()[0]))
# 开始测试
model.eval()
with fluid.dygraph.no_grad():
for i, (x, y) in enumerate(zip(X_test, y_test)):
x = to_variable(x.reshape([1, 1, 28, 28]).astype(np.float32))
y = np.array(y).reshape([1]).astype(np.int64)
logits = model(x)
pred = np.argmax(logits.numpy())
if pred == y:
acc = 1
else:
acc = 0
if (i + 1) % 1000 == 0:
print(‘Step [{}/{}], Accuracy: {:.2f}%’.format(i+1, len(X_test), acc * 100))
“`
2. 利用飞桨完成图像风格转换
“`
import paddle
import paddle.fluid as fluid
from PIL import Image
import numpy as np
def load_image(path):
img = Image.open(path)
img = img.resize((256, 256), Image.ANTIALIAS)
img = np.array(img).transpose((2, 0, 1)).astype(‘float32’)
img = img / 255.0
img = img * 2.0 – 1.0
return img.reshape([1, 3, 256, 256])
class Transformer(fluid.dygraph.Layer):
def __init__(self):
super(Transformer, self).__init__()
self.conv1 = fluid.dygraph.Conv2D(num_channels=3, num_filters=32, filter_size=9, stride=1, padding=4)
self.in1 = fluid.dygraph.BatchNorm(32)
self.conv2 = fluid.dygraph.Conv2D(num_channels=32, num_filters=64, filter_size=3, stride=2, padding=1)
self.in2 = fluid.dygraph.BatchNorm(64)
self.conv3 = fluid.dygraph.Conv2D(num_channels=64, num_filters=128, filter_size=3, stride=2, padding=1)
self.in3 = fluid.dygraph.BatchNorm(128)
self.res1 = fluid.dygraph.Conv2D(num_channels=128, num_filters=128, filter_size=3, stride=1, padding=1, act=’relu’)
self.res2 = fluid.dygraph.Conv2D(num_channels=128, num_filters=128, filter_size=3, stride=1, padding=1, act=’relu’)
self.res3 = fluid.dygraph.Conv2D(num_channels=128, num_filters=128, filter_size=3, stride=1, padding=1, act=’relu’)
self.res4 = fluid.dygraph.Conv2D(num_channels=128, num_filters=128, filter_size=3, stride=1, padding=1, act=’relu’)
self.res5 = fluid.dygraph.Conv2D(num_channels=128, num_filters=128, filter_size=3, stride=1, padding=1, act=’relu’)
self.deconv1 = fluid.dygraph.Conv2DTranspose(num_channels=128, num_filters=64, filter_size=3, stride=2, padding=1, output_padding=1)
self.in4 = fluid.dygraph.BatchNorm(64)
self.deconv2 = fluid.dygraph.Conv2DTranspose(num_channels=64, num_filters=32, filter_size=3, stride=2, padding=1, output_padding=1)
self.in5 = fluid.dygraph.BatchNorm(32)
self.deconv3 = fluid.dygraph.Conv2D(num_channels=32, num_filters=3, filter_size=9, stride=1, padding=4, act=’tanh’)
def forward(self, inputs):
x = self.conv1(inputs)
x = self.in1(x)
x = fluid.layers.relu(x)
x = self.conv2(x)
x = self.in2(x)
x = fluid.layers.relu(x)
x = self.conv3(x)
x = self.in3(x)
x = fluid.layers.relu(x)
x = self.res1(x)
x = self.res2(x)
x = self.res3(x)
x = self.res4(x)
x = self.res5(x)
x = self.deconv1(x)
x = self.in4(x)
x = fluid.layers.relu(x)
x = self.deconv2(x)
x = self.in5(x)
x = fluid.layers.relu(x)
x = self.deconv3(x)
return x
# 开启动态图模式
fluid.enable_dygraph()
# 加载预训练模型和待转换的图像
model = Transformer()
params, _ = fluid.dygraph.load_dygraph(‘models/transformer.pdparams’)
model.load_dict(params)
content = load_image(‘images/content.jpg’)
style = load_image(‘images/style.jpg’)
# 开始转换
model.eval()
with fluid.dygraph.no_grad():
content_var = fluid.dygraph.to_variable(content)
style_var = fluid.dygraph.to_variable(style)
output_var = model(content_var, style_var)
# 保存转换后的图像
output = output_var.numpy()[0].transpose((1, 2, 0))
output = (output + 1.0) / 2.0
output = (output * 255.0).CLIP(0, 255).astype(‘uint8’)
output_img = Image.fromarray(output)
output_img.save(‘images/output.jpg’)
“`
三、自然语言处理作业答案
1. 对文本进行分词和词性标注
“`
import paddle
import paddle.fluid as fluid
import paddle.fluid.dygraph as dygraph
import jieba.posseg as pseg
text = ‘今天天气不错,适合出去旅游。’
words = pseg.cut(text)
for word, flag in words:
print(‘{}\t{}’.format(word, flag))
“`
2. 利用飞桨完成情感分析任务
“`
import paddle
import paddle.fluid as fluid
import jieba
import numpy as np
class SentimentAnalysis(fluid.dygraph.Layer):
def __init__(self, vocab_size, embed_size, num_filters, filter_sizes, num_labels):
super(SentimentAnalysis, self).__init__()
self.embedding = fluid.dygraph.Embedding(size=[vocab_size, embed_size], dtype=’float32′)
self.conv_0 = fluid.dygraph.Conv2D(num_channels=1, num_filters=num_filters, filter_size=[filter_sizes[0], embed_size], stride=1, padding=0, act=’relu’)
self.conv_1 = fluid.dygraph.Conv2D(num_channels=1, num_filters=num_filters, filter_size=[filter_sizes[1], embed_size], stride=1, padding=0, act=’relu’)
self.conv_2 = fluid.dygraph.Conv2D(num_channels=1, num_filters=num_filters, filter_size=[filter_sizes[2], embed_size], stride=1, padding=0, act=’relu’)
self.fc = fluid.dygraph.Linear(input_dim=3*num_filters, output_dim=num_labels, act=’softmax’)
def forward(self, inputs):
x = self.embedding(inputs)
x = fluid.layers.reshape(x, shape=[-1, 1, x.shape[1], x.shape[2]])
x_0 = self.conv_0(x)
x_1 = self.conv_1(x)
x_2 = self.conv_2(x)
x_0 = fluid.layers.pool2d(x_0, pool_size=[x_0.shape[2], 1], pool_type=’max’, pool_stride=[1, 1])
x_1 = fluid.layers.pool2d(x_1, pool_size=[x_1.shape[2], 1], pool_type=’max’, pool_stride=[1, 1])
x_2 = fluid.layers.pool2d(x_2, pool_size=[x_2.shape[2], 1], pool_type=’max’, pool_stride=[1, 1])
x = fluid.layers.concat([x_0, x_1, x_2], axis=1)
x = fluid.layers.flatten(x, axis=1)
x = self.fc(x)
return x
# 开启动态图模式
fluid.enable_dygraph()
# 预处理数据
vocab = {}
with open(‘data/stopwords.txt’, ‘r’, encoding=’utf-8′) as f:
for line in f:
word = line.strip()
vocab[word] = 1
def process_lines(lines):
texts = []
labels = []
for line in lines:
line = line.strip().split(‘\t’)
label = int(line[0])
text = line[1]
words = [word for word in jieba.cut(text) if word not in vocab]
seq = [word_dict.get(word, unk_idx) for word in words]
if len(seq) > max_length:
seq = seq[:max_length]
else:
seq += [pad_idx] * (max_length – len(seq))
texts.append(seq)
labels.append(label)
return np.array(texts, dtype=’int64′), np.array(labels, dtype=’int64′)
word_dict = {}
with open(‘data/word_dict.txt’, ‘r’, encoding=’utf-8′) as f:
for line in f:
word, freq = line.strip().split(‘\t’)
if int(freq) < 5:
continue
word_dict[word] = len(word_dict)
train_data = []
with open(‘data/train.txt’, ‘r’, encoding=’utf-8′) as f:
for line in f:
train_data.append(line)
train_data = process_lines(train_data)
val_data = []
with open(‘data/val.txt’, ‘r’, encoding=’utf-8′) as f:
for line in f:
val_data.append(line)
val_data = process_lines(val_data)
test_data = []
with open(‘data/test.txt’, ‘r’, encoding=’utf-8′) as f:
for line in f:
test_data.append(line)
test_data = process_lines(test_data)
# 定义模型、优化器和损失
batch_size = 128
vocab_size = len(word_dict)
embed_size = 256
num_filters = 128
filter_sizes = [3, 4, 5]
num_labels = 2
max_length = 64
pad_idx = 0
unk_idx = 1
model = SentimentAnalysis(vocab_size, embed_size, num_filters, filter_sizes, num_labels)
optimizer = fluid.optimizer.Adam(learning_rate=0.001, parameter_list=model.parameters())
criterion = fluid.dygraph.CrossEntropyLoss()
# 开始训练
model.train()
for epoch in range(10):
np.random.shuffle(train_data)
total_loss, total_acc = 0.0, 0.0
total_steps = len(train_data) // batch_size + 1
for i in range(total_steps):
batch_data = train_data[i*batch_size:min((i+1)*batch_size, len(train_data))]
inputs, labels = batch_data
inputs = fluid.dygraph.to_variable(inputs)
labels = fluid.dygraph.to_variable(labels)
logits = model(inputs)
loss = criterion(logits, labels)
loss.backward()
optimizer.minimize(loss)
model.clear_gradients()
pred = np.argmax(logits.numpy(), axis=1)
acc = np.mean(pred == labels.numpy())
total_loss += loss.numpy()[0]
total_acc += acc
if (i + 1) % 100 == 0:
print(‘Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}, Accuracy: {:.2f}%’.format(epoch+1, 10, i+1, total_steps, total_loss/100, total_acc*100/100))
total_loss, total_acc = 0.0, 0.0
# 在验证集上测试模型效果
model.eval()
total_loss, total_acc = 0.0, 0.0
total_steps = len(val_data) // batch_size + 1
with fluid.dygraph.no_grad():
for i in range(total_steps):
batch_data = val_data[i*batch_size:min((i+1)*batch_size, len(val_data))]
inputs, labels = batch_data
inputs = fluid.dygraph.to_variable(inputs)
labels = fluid.dygraph.to_variable(labels)
logits = model(inputs)
loss = criterion(logits, labels)
pred = np.argmax(logits.numpy(), axis=1)
acc = np.mean(pred == labels.numpy())
total_loss += loss.numpy()[0]
total_acc += acc
print(‘Validation, Loss: {:.4f}, Accuracy: {:.2f}%’.format(total_loss/total_steps, total_acc*100/total_steps))
model.train()
# 在测试集上测试模型效果
model.eval()
total_loss, total_acc = 0.0, 0.0
total_steps = len(test_data) // batch_size + 1
with fluid.dygraph.no_grad():
for i in range(total_steps):
batch_data = test_data[i*batch_size:min((i+1)*batch_size, len(test_data))]
inputs, labels = batch_data
inputs = fluid.dygraph.to_variable(inputs)
labels = fluid.dygraph.to_variable(labels)
logits = model(inputs)
loss = criterion(logits, labels)
pred = np.argmax(logits.numpy(), axis=1)
acc = np.mean(pred == labels.numpy())
total_loss += loss.numpy()[0]
total_acc += acc
print(‘Test, Loss: {:.4f}, Accuracy: {:.2f}%’.format(total_loss/total_steps, total_acc*100/total_steps))
“`
四、CV作业答案
1. 利用飞桨完成物体检测任务
“`
import paddle.fluid as fluid
import CV2
import numpy as np