我有一个分类数据集,我实现了LabelEncoder
以对其进行数值更改,然后实现了StandardScaler()
函数以对其进行了二维更改。现在,我想使用SVM内核功能来分离3D数据。它给我X0_org
,Y0_orig
和X1_orig
,Y1_orig
的错误。错误是索引太多...
def randrange(n, vmin, vmax):
return (vmax-vmin)*np.random.rand(n) + vmin
def fn_kernel(x1, x2):
""" Implements a kernel phi(x1,y1) = [x1, y1, x1^2 + y1^2] """
return np.array([x1, x2, x1**2.0 + x2**2.0])
""" Generate linearly nonseparable dataset (in R^2) """
# # Read the CSV file
dataset = pd.read_csv('raw_train.csv')
X = dataset.iloc[:, 1:3].values
y = dataset.iloc[:, 0].values
df_X = pd.DataFrame(X)
df_y = pd.DataFrame(y)
# Encoding categorical data
le = LabelEncoder()
X_encode = df_X.apply(le.fit_transform)
# print(X)
y_encode = df_y.apply(le.fit_transform)
# print(y)
# splitting the datset into the training set and test set.
X_train, X_test, y_train, y_test = train_test_split(X_encode, y_encode,test_size=0.34, random_state=0)
# Changed the data in 2D
from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X_s = sc_X.fit_transform(X_train)
Y_s = sc_X.transform(X_test)
X = np.array(X_s)
Y = np.array(Y_s)
print(X)
print()
print(Y)
A = X[np.where(Y <= 0)]
B = X[np.where(Y >= 1)]
print(A)
print()
print(B)
X0_orig = A[:, 0]
Y0_orig = A[:, 1]
print(X0_orig)
X1_orig = B[:, 0]
Y1_orig = B[:, 1]
frac0 = len(np.where(Y == 0)[0]) / float(len(Y))
frac1 = len(np.where(Y == 1)[0]) / float(len(Y))
print("Percentage of '0' labels:", frac0)
print("Percentage of '1' labels:", frac1)
A = np.array([fn_kernel(x, y) for x, y in zip(np.ravel(X0_orig), np.ravel(Y0_orig))])
X0 = A[:, 0]
Y0 = A[:, 1]
Z0 = A[:, 2]
A = np.array([fn_kernel(x, y) for x, y in zip(np.ravel(X1_orig), np.ravel(Y1_orig))])
X1 = A[:, 0]
Y1 = A[:, 1]
Z1 = A[:, 2]
def plot_no_decision_boundary():
fig = plt.figure(figsize=(20, 8))
ax = fig.add_subplot(122, projection='3d')
ax.scatter(X0, Y0, Z0, c='r', marker='o')
ax.scatter(X1, Y1, Z1, c='b', marker='^')
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
ax.set_title("Data in R^3 (separable)")
# Project data to X/Y plane
ax2d = fig.add_subplot(121)
ax2d.scatter(X0, Y0, c='r', marker='o')
ax2d.scatter(X1, Y1, c='b', marker='^')
ax2d.set_xlabel('X Label')
ax2d.set_ylabel('Y Label')
ax2d.set_title("Data projected to R^2 (nonseparable)")
plt.show()
def plot_decision_boundary():
fig = plt.figure(figsize=(20, 8))
ax = fig.add_subplot(121, projection='3d')
ax.scatter(X0, Y0, Z0, c='r', marker='o')
ax.scatter(X1, Y1, Z1, c='b', marker='^')
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
ax.set_title("Data in R^3 (separable w/ hyperplane)")
x = np.arange(-1.25, 1.25, 0.1)
y = np.arange(-1.25, 1.25, 0.1)
X, Y = np.meshgrid(x, y)
Z = np.zeros(X.shape)
Z[:, :] = 0.5
ax.plot_surface(X, Y, Z, color='#09F911')
# Project data to X/Y plane
ax2d = fig.add_subplot(122)
ax2d.scatter(X0, Y0, c='r', marker='o')
ax2d.scatter(X1, Y1, c='b', marker='^')
ax2d.add_patch(pl.Circle((0, 0), radius=sqrt(0.5), fill=False, linestyle='solid', linewidth=4.0, color='black'))
ax2d.add_patch(pl.Circle((0, 0), radius=sqrt(0.5), fill=False, linestyle='dashed', linewidth=1.5, color='#09F911'))
ax2d.set_xlabel('X Label')
ax2d.set_ylabel('Y Label')
ax2d.set_title("Data projected to R^2 (hyperplane projection shown)")
plt.show()
def main():
print("...Projecting dataset to R^3 (no decision boundary)...")
plot_no_decision_boundary()
print("...Projecting dataset to R^3 (with decision boundary)...")
plot_decision_boundary()
print("...Done.")
if __name__ == '__main__':
main()
如果我打印A
和B
,它将得到此输出。
A: [-0.03689752 -0.84216039 -0.27461752 -0.84216039 -0.17987541 -0.84216039
-1.4666764 -0.84216039 1.32139242 1.14423966 0.53501403 -0.84216039
0.24905826 -0.84216039 -1.10923168 -0.75178696 -0.68029802 1.99555397
1.10692559 -0.84216039 -0.84216039 -0.3228533 1.24990347 1.03543664]
B: [ 1.14423966 0.00915392 -0.84216039 1.14423966 0.57669679 -0.84216039]
但是,如果我打印X0_orig
或X1_orig
,则会出现此错误:
Traceback (most recent call last):
X0_orig = A[:, 0]
IndexError: too many indices for array
答案 0 :(得分:1)
此问题已解决,问题是np.where
返回了1D
数组。在这里,我改变了。我使用了np.argwhere
,现在它在2D
中给了我。
A = X_s[np.argwhere(Y_s <= 0)]
B = X_s[np.argwhere(Y_s >= 1)]
print(A.shape)
答案 1 :(得分:0)
A
和B
是一维数组。因此,尝试访问第一列将导致错误。仅当您可以确切指定要查找的信息时。
使用A.shape
监视数组的形状,并在必要时使用A.reshape
使其二维化