python - 如何修复在里面切片列表?
问题描述
我有一个分类数据集,我实现了LabelEncoder
以数字形式更改它,然后我实现了StandardScaler()
以 2D 形式更改它的函数。现在我想使用 SVM Kernel 函数来分离 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
and 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
or X1_orig
,它会给出这个错误:
Traceback (most recent call last):
X0_orig = A[:, 0]
IndexError: too many indices for array
解决方案
它已解决,问题是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)
推荐阅读
- hibernate - 如何使用 WebSphere 和 DB2 在 Spring 中覆盖事务隔离
- vbscript - 使用 Alt Tab 并等待窗口变为活动状态
- parsing - Parser 的使用有意义吗?
- mocking - 你如何用玩笑来模拟 lodash debounce.cancel?
- java - 无论程序是从 jar 还是从 IDE 运行,如何将文件写入正确的目录?
- android - 从我的应用程序打开的 PDF 文件无法共享
- sql - 如何选择由 2 个单词组成的所有名称
- python-3.x - 没有模块命名的套接字
- angular - 在 Mapbox 中添加新标记之前删除以前的标记
- node.js - 如何通过 HTTP Get 请求使用 Express、Node JS 和 Angular 返回对象数组