Reputation: 1358
I am trying to fit a plane to a point cloud using RANSAC in scikit.
I am not able to understand how to do it, how to plot the plane which I obtain from ransac.predict
.
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from sklearn import datasets, linear_model
diabetes = datasets.load_diabetes()
X_train = diabetes.data[:-20, (0,1)]
y_train = diabetes.target[:-20]
ransac = linear_model.RANSACRegressor(
linear_model.LinearRegression()
)
ransac.fit(X_train, y_train)
fig = plt.figure()
plt.clf()
ax = Axes3D(fig)
ax.plot_surface([-5,5],[-5,5], ransac.predict(X_train))
I am getting error message
ValueError: shape mismatch: objects cannot be broadcast to a single shape
Upvotes: 2
Views: 10225
Reputation: 33127
In this example, you only use 2 features to the fit is not a PLANE but a line.
This can also be seen from:
ransac.estimator_.coef_
array([266.63361536, -48.86064441])
that contains a weight for each of the 2 features that you have.
Let's make a real 3D case:
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from sklearn import datasets, linear_model
diabetes = datasets.load_diabetes()
X_train = diabetes.data[:-20, (0,1,2)]
y_train = diabetes.target[:-20]
ransac = linear_model.RANSACRegressor(linear_model.LinearRegression())
ransac.fit(X_train, y_train)
# the plane equation
z = lambda x,y: (-ransac.estimator_.intercept_ - ransac.estimator_.coef_[0]*x - ransac.estimator_.coef_[1]*y) / ransac.estimator_.coef_[2]
tmp = np.linspace(-5,5,50)
x,y = np.meshgrid(tmp,tmp)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot3D(X_train[:,0], X_train[:,1], X_train[:,2], 'or')
ax.plot_surface(x, y, z(x,y))
ax.view_init(10, 60)
plt.show()
Upvotes: 3