感知机实现异或运算MATLAB代码
时间: 2023-05-29 10:07:26 浏览: 77
以下是感知机实现异或运算的MATLAB代码:
% 定义输入数据
X = [0 0; 0 1; 1 0; 1 1];
Y = [0; 1; 1; 0];
% 初始化参数
w = rand(2, 1);
b = rand();
% 定义学习率和迭代次数
lr = 0.1;
epochs = 10000;
% 训练模型
for i = 1:epochs
% 随机选择一个样本
idx = randi(length(Y));
x = X(idx, :)';
y = Y(idx);
% 计算预测值和误差
z = w' * x + b;
pred = sign(z);
error = y - pred;
% 更新参数
w = w + lr * error * x;
b = b + lr * error;
% 计算训练误差
loss = sum((Y - sign(X * w + b)).^2);
% 输出训练结果
if mod(i, 1000) == 0
fprintf('Epoch %d, Loss %f\n', i, loss);
end
end
% 预测结果
pred = sign(X * w + b);
fprintf('Predictions: %s\n', mat2str(pred'));
相关问题
多层感知机实现异或代码
以下是使用PyTorch实现的多层感知机解决异或问题的代码:
```python
import torch
import torch.nn as nn
import torch.optim as optim
# 定义模型结构
class MLP(nn.Module):
def __init__(self):
super(MLP, self).__init__()
self.fc1 = nn.Linear(2, 4) # 输入层到隐藏层
self.fc2 = nn.Linear(4, 1) # 隐藏层到输出层
self.act = nn.Sigmoid() # 激活函数
def forward(self, x):
x = self.fc1(x)
x = self.act(x)
x = self.fc2(x)
x = self.act(x)
return x
# 数据集
x = torch.Tensor([[0, 0], [0, 1], [1, 0], [1, 1]])
y = torch.Tensor([[0], [1], [1], [0]])
# 模型、损失函数、优化器
model = MLP()
criterion = nn.MSELoss()
optimizer = optim.SGD(model.parameters(), lr=0.1)
# 训练
for epoch in range(10000):
optimizer.zero_grad()
output = model(x)
loss = criterion(output, y)
loss.backward()
optimizer.step()
if epoch % 1000 == 0:
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, 10000, loss.item()))
# 测试
with torch.no_grad():
output = model(x)
print('Output: {}'.format(output))
```
在此代码中,我们定义了一个包含一个隐藏层的MLP,使用Sigmoid函数作为激活函数,使用均方误差作为损失函数,使用随机梯度下降算法作为优化器。然后,我们使用数据集进行训练,最终输出模型的预测结果。
多层感知器实现异或的pytorch代码
以下是多层感知器实现异或的PyTorch代码:
```python
import torch
import torch.nn as nn
# 定义多层感知器模型
class MLP(nn.Module):
def __init__(self):
super(MLP, self).__init__()
self.layer1 = nn.Linear(2, 4) # 输入层到隐藏层
self.layer2 = nn.Linear(4, 1) # 隐藏层到输出层
self.activation = nn.Sigmoid() # 激活函数为Sigmoid
def forward(self, x):
x = self.layer1(x)
x = self.activation(x)
x = self.layer2(x)
x = self.activation(x)
return x
# 定义训练数据
x_train = torch.tensor([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=torch.float32)
y_train = torch.tensor([[0], [1], [1], [0]], dtype=torch.float32)
# 初始化模型和优化器
model = MLP()
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
# 开始训练
epochs = 10000
for epoch in range(epochs):
# 前向传播
y_pred = model(x_train)
# 计算损失
loss = nn.functional.binary_cross_entropy(y_pred, y_train)
# 反向传播
optimizer.zero_grad()
loss.backward()
optimizer.step()
# 输出训练过程
if (epoch+1) % 1000 == 0:
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, epochs, loss.item()))
# 测试模型
with torch.no_grad():
y_pred = model(x_train)
y_pred = (y_pred > 0.5).float()
print('Predicted Values:', y_pred)
```
在这个例子中,我们定义了一个包含一个输入层、一个隐藏层和一个输出层的多层感知器。输入是一个2维的张量,输出是一个标量。我们使用Sigmoid作为激活函数,并使用二元交叉熵作为损失函数。我们使用随机梯度下降作为优化器,训练10000个epoch,每1000个epoch输出一次损失值。最后我们对模型进行测试,输出预测的结果。