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

在PyCharm编写分类代码时遇TypeError: 'int'对象不可订阅错误求助

Fixing TypeError: 'int' object is not subscriptable in Your Data Classification Code

Let's break down the problem and fix your code step by step. The core error TypeError: 'int' object is not subscriptable comes from a mismatch between your variable types and how you're trying to access them, plus several other structural issues in your code.

1. Root Cause of the int Subscript Error

Looking at your code:

net1 = np.matmul(W1, Xi[i]) + b1
y1 = AF(net1)
net2 = np.matmul(W2, y1[i]) + b2
  • W1 is defined as a 1D array (np.zeros(2)), and Xi[i] is a 1D list. np.matmul(W1, Xi[i]) returns a scalar value.
  • Your AF function returns either 1 or -1 (integers), so y1 is a single integer, not an array. Trying to access y1[i] is invalid—integers don't have subscripts!

2. Fixing Variable Dimensions & Network Structure

It looks like you're trying to implement a two-layer perceptron with a hidden layer (judging by the for K in range(3) loop). Here's how to correct your variable definitions to match that structure:

  • Input layer: 2 features
  • Hidden layer: 3 neurons (so W1 should be a (3, 2) array, b1 a (3,) array)
  • Output layer: 1 neuron (so W2 should be a (1, 3) array, b2 a scalar)

3. Full Corrected Code with Explanations

import numpy as np
import matplotlib.pyplot as plt

def AF(x):
    if x >= 0:
        return 1
    else:
        return -1

Q1 = 3
Q2 = 1
# Convert Xi to numpy array for proper indexing later
Xi = np.array([[-1, -1], [0, 1], [1, -1], [0, 0]])
T = np.concatenate((np.ones((1, Q1)), -1 * np.ones((1, Q2))), axis=1)
T = np.squeeze(T)

# Correct dimensions for a 2-layer perceptron (3 hidden neurons)
W1 = np.zeros((3, 2))  # 3 hidden neurons, each with 2 input weights
W2 = np.ones((1, 3))   # Output neuron with 3 hidden layer inputs
b1 = np.zeros(3)       # Bias for each hidden neuron
b2 = 0                 # Bias for output neuron

N = Q1 + Q2
k = 0

for i in range(4):
    # Calculate net input for hidden layer (3 values, one per neuron)
    net1 = np.matmul(W1, Xi[i]) + b1
    # Apply activation function to each hidden neuron output
    y1 = np.array([AF(x) for x in net1])
    # Calculate net input for output layer
    net2 = np.matmul(W2, y1) + b2
    output = AF(net2[0])  # net2 is a 1D array, extract scalar value

    if output != T[i]:
        if T[i] == 1:
            # Find the hidden neuron with maximum net input
            J = np.argmax(net1)
            # Update bias and weights for that hidden neuron
            b1[J] += (1 - net1[J])
            W1[J] += (1 - net1[J]) * Xi[i]
        elif T[i] == -1:
            # Update all hidden neurons' bias and weights
            for K in range(3):
                b1[K] += (-1 - net2[0])
                W1[K] += (-1 - net2[0]) * Xi[i]

# Uncomment and adjust if you want to plot decision boundaries
# xx1 = np.arange(-3, 3)
# Example: Plot one of the hidden layer's decision boundary
# xx2 = (-b1[0] - W1[0, 0] * xx1) / W1[0, 1]

# Plot the data points
plt.plot(Xi[T == -1, 0], Xi[T == -1, 1], 'go', label='Class -1')
plt.plot(Xi[T == 1, 0], Xi[T == 1, 1], 'r^', label='Class 1')
# plt.plot(xx1, xx2, 'g', label='Decision Boundary')
plt.legend()
plt.show()

Key Fixes Made:

  • Converted Xi to a numpy array to enable advanced indexing for plotting.
  • Corrected the dimensions of W1, W2, and b1 to match a 2-layer perceptron with 3 hidden neurons.
  • Modified y1 to be an array of activation values (one per hidden neuron) instead of a single integer.
  • Fixed weight/bias update logic: replaced invalid W[i,J] and b[J] with the correct variables (W1[J], b1[J]), and used scalar multiplication instead of unnecessary np.matmul for scalar-array operations.
  • Fixed access to net2 (it's a 1D array, so we use net2[0] to get the scalar value).

Additional Notes:

  • The decision boundary code was commented out because your original code references W and b which no longer exist (we have W1, W2, b1, b2 instead). You can adjust it to plot boundaries for individual hidden neurons or the output layer as needed.
  • Make sure your training loop logic aligns with the learning rule you're trying to implement (e.g., perceptron learning rule for the hidden layer).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:39:28