You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

单输出感知器验证AND逻辑后,双输出感知器实现同类问题技术咨询

Two-Output Perceptron for Custom Binary Classification

Great to hear you've already nailed the single-output perceptron for the AND problem! Extending this to a two-output setup for your new classification task is totally doable—let's break down how to implement it step by step, using the same threshold (0.2) and learning rate (1) you specified.

Key Background

A two-output perceptron works by having separate weight sets and activation logic for each output unit. Each input (plus a bias term to handle the threshold) feeds into both output units, and each unit independently computes its output using the perceptron rule. Your task is essentially two separate linear classifications:

  • Output 1 should fire (1) only when inputs are (1.0, 1.0), else 0
  • Output 2 should fire (1) for all inputs except (1.0, 1.0), else 0

Since both tasks are linearly separable, the perceptron will converge to the correct weights.

Implementation Steps & Code

First, let's structure the code to mirror your existing single-output setup, but expand it for two outputs:

1. Define Training Data

We'll format inputs as tuples, and paired expected outputs as lists:

# Training data: (input_x1, input_x2) → [expected_output1, expected_output2]
training_data = [
    ((1.0, 1.0), [1, 0]),
    ((1.0, 0.0), [0, 1]),
    ((0.0, 1.0), [0, 1]),
    ((0.0, 0.0), [0, 1])
]

2. Initialize Weights & Hyperparameters

We'll include a bias term (fixed input of 1.0) to handle the threshold. For two output units, we'll use a 2x3 weight matrix (each row = weights for one output unit: [bias_weight, x1_weight, x2_weight]). We'll initialize weights to 0 (small random values work too, but 0 is perfectly fine here):

learning_rate = 1.0
threshold = 0.2

# Weights: 2 output units × 3 inputs (bias + x1 + x2)
weights = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]

3. Perceptron Activation Function

We'll use a step function that returns 1 if the net input meets/exceeds the threshold, else 0:

def activation(net_input):
    return 1 if net_input >= threshold else 0

4. Training Loop

For each training sample, we'll compute the output for both units, calculate the error, and update weights using the perceptron learning rule:

def train_perceptron():
    global weights
    converged = False
    epoch = 0
    while not converged:
        converged = True
        epoch += 1
        print(f"\nEpoch {epoch}:")
        for (x1, x2), expected in training_data:
            # Add bias term to input vector
            inputs = [1.0, x1, x2]
            # Compute outputs for both units
            outputs = []
            for unit_weights in weights:
                net_input = sum(w * inp for w, inp in zip(unit_weights, inputs))
                outputs.append(activation(net_input))
            # Update weights for each output unit if there's an error
            for i in range(2):
                error = expected[i] - outputs[i]
                if error != 0:
                    converged = False
                    # Update each weight for unit i
                    for j in range(3):
                        weights[i][j] += learning_rate * error * inputs[j]
            # Print progress for this sample
            print(f"Input: ({x1}, {x2}) → Expected: {expected} | Predicted: {outputs}")
    print(f"\nTraining converged after {epoch} epochs!")
    return weights

5. Test the Trained Perceptron

Once trained, we can test it on all samples to verify correctness:

# Train the perceptron
final_weights = train_perceptron()

# Test the trained model
print("\nFinal Test Results:")
for (x1, x2), expected in training_data:
    inputs = [1.0, x1, x2]
    outputs = []
    for unit_weights in final_weights:
        net_input = sum(w * inp for w, inp in zip(unit_weights, inputs))
        outputs.append(activation(net_input))
    print(f"Input: ({x1}, {x2}) → Expected: {expected} | Predicted: {outputs}")

How It Works

  • Bias & Threshold: The bias weight (first element in each weight row) adjusts the net input to account for the 0.2 threshold. Over training, the bias will tune itself so that the net input crosses the threshold exactly when needed.
  • Weight Updates: Each output unit's weights are updated independently based on its own error. For example, when training on (1.0,1.0), the first unit's error will be 1 - predicted_output, triggering weight updates to push its net input above the threshold, while the second unit's error will be 0 - predicted_output, pushing its net input below the threshold.
  • Convergence: Since this problem is linearly separable, the perceptron will always converge to a solution (you'll see it stop once all predictions match the expected outputs).

Sample Output

When you run the code, you'll see the epochs progress until all predictions are correct. The final weights will look something like:

  • Output Unit 1 weights: [-0.2, 1.0, 1.0] (net input = -0.2 + x1 + x2; hits threshold 0.2 only when x1=x2=1)
  • Output Unit 2 weights: [0.8, -1.0, -1.0] (net input = 0.8 -x1 -x2; stays above 0.2 for all inputs except x1=x2=1)

内容的提问来源于stack exchange,提问作者Orsu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:40:30