2017-05-08 70 views
0

我正在實現Perceptron 3D,在這種情況下,我有n個可分離的點,在這種情況下,藍色點和紅色點,我需要從我的字典,我試着這樣做:在Python中繪製可分離3D點的最簡單方法

training_data = { 
'0.46,0.98,-0.43' : 'Blue', 
'0.66,0.24,0.0' : 'Blue', 
'0.35,0.01,-0.11' : 'Blue', 
'-0.11,0.1,0.35' : 'Red', 
'-0.43,-0.65,0.46' : 'Red', 
'0.57,-0.97,0.8' : 'Red' 
} 

def get_points_of_color(data, color): 
    x_coords = [point.split(",")[0] for point in data.keys() if 
data[point] == color] 
    y_coords = [point.split(",")[1] for point in data.keys() if 
data[point] == color] 
    z_coords = [point.split(",")[2] for point in data.keys() if 
data[point] == color] 
    return x_coords, y_coords, z_coords 

fig = plt.figure() 
ax = fig.add_subplot(111, projection='3d') 

# Plot blue points 
x_coords, y_coords, z_coords = get_points_of_color(training_data, 'Blue') 
ax.scatter(x_coords, y_coords, z_coords, 'bo') 

# Plot red points 
x_coords, y_coords, z_coords = get_points_of_color(training_data, 'Red') 
ax.scatter(x_coords, y_coords, z_coords, 'ro') 

ax.set_xlim(-1, 1) 
ax.set_ylim(-1, 1) 
ax.set_zlim(-1, 1) 
ax.set_xlabel('X') 
ax.set_ylabel('Y') 
ax.set_zlabel('Z') 

plt.show() 

但沒有成功,我得到了以下錯誤消息:

TypeError: Cannot cast array data from dtype('float64') to dtype('S32') according to the rule 'safe' 

PS:我使用的是:

import matplotlib.pyplot as plt 
from mpl_toolkits.mplot3d import Axes3D 

我想知道我做錯了什麼,以及如何正確繪製它們。

+0

你的座標是字符串,甚至分裂你有'「0.46」後',而不是'0.46'。你需要將它們轉換爲浮點數,float(「0.46」)== 0.46'。 – ImportanceOfBeingErnest

回答

1

你的座標是字符串,即使分裂後你有"0.46",而不是0.46。您需要將它們投射到浮動物上,例如float("0.46") == 0.46

因此,在這種情況下,轉換可能會發生內部列表生成:

x_coords = [float(point.split(",")[0]) for point in data.keys() if data[point] == color] 
相關問題