在python中为矩阵拟合一行
我有一个256x256形状的矩阵,我正试图找到一条最适合它的线。顺便说一下,这是一幅图像,所以这些只是强度值。让我们假设我想通过所有的强度找到最合适的线,我该怎么做呢?链接描述了如何使用svd在三维数据集上执行此操作。然而,我有点困惑,这将如何应用到我的numpy阵列 编辑:下面是我用%timeit分析的一个随机双精度值示例:在python中为矩阵拟合一行,python,arrays,numpy,matplotlib,curve-fitting,Python,Arrays,Numpy,Matplotlib,Curve Fitting,我有一个256x256形状的矩阵,我正试图找到一条最适合它的线。顺便说一下,这是一幅图像,所以这些只是强度值。让我们假设我想通过所有的强度找到最合适的线,我该怎么做呢?链接描述了如何使用svd在三维数据集上执行此操作。然而,我有点困惑,这将如何应用到我的numpy阵列 编辑:下面是我用%timeit分析的一个随机双精度值示例: ran = [25,50,75,100,125] for i in ran:
ran = [25,50,75,100,125]
for i in ran:
J = np.random.random((i,i))
y,x=np.indices(J.shape)
x = x.ravel()
y = y.ravel()
J=J.ravel()
data = np.concatenate((x[:, np.newaxis],
y[:, np.newaxis],
J[:, np.newaxis]),axis=1)
datamean = data.mean(axis=0)
print "Doing %d now" %i
%timeit U, S, V = np.linalg.svd(data - datamean)
我得到以下输出:
Doing 25 now
100 loops, best of 3: 10.4 ms per loop
Doing 50 now
1 loops, best of 3: 285 ms per loop
Doing 75 now
1 loops, best of 3: 3 s per loop
Doing 100 now
1 loops, best of 3: 5.83 s per loop
Doing 125 now
1 loops, best of 3: 15.1 s per loop
编辑2:。我刚刚以numpy的npy格式保存了它通过以下操作直接适用于您的问题:
import numpy as np
z = your_matrix_256_x_256
y, x = np.indices(z.shape)
x = x.ravel()
y = y.ravel()
z = z.ravel()
请注意,x
和y
的间隔可以通过将这些数组乘以适当的标量来重新调整
编辑: 查看您的数据后,您的问题似乎更多的是二维曲线拟合,可以使用
np.polyfit()
,如下例所示
z = np.load('arr.npy').astype(np.int32)
y, x = np.indices(z.shape)
valid_z = (y.ravel()>0) & (z.ravel()>0)
x_valid = x.ravel()[valid_z]
y_valid = y.ravel()[valid_z]
z_valid = z.ravel()[valid_z]
# fitting best curve
fig = plt.figure(figsize=(5,3))
ax = fig.add_subplot(111)
ax.scatter(x_valid, y_valid, c=z_valid, alpha=0.2, s=20, edgecolor='none',
cmap=plt.cm.jet)
# finding best-fit curve
z = np.polyfit(x_valid, y_valid, w=z_valid**0.5, deg=1)
p = np.poly1d(z)
# plotting
x_plot = np.linspace(x_valid.min(), x_valid.max(), 100)
y_plot = p(x_plot)
ax.plot(x_plot, y_plot, '-r', lw=2)
ax.set_xlim(0, x.shape[1])
ax.set_ylim(0, y.shape[0])
ax.legend(loc='lower left', frameon=False, fontsize=8)
fig.savefig('test.png', bbox_inches='tight')
其中:
通过执行以下操作直接适用于您的问题:
import numpy as np
z = your_matrix_256_x_256
y, x = np.indices(z.shape)
x = x.ravel()
y = y.ravel()
z = z.ravel()
请注意,x
和y
的间隔可以通过将这些数组乘以适当的标量来重新调整
编辑: 查看您的数据后,您的问题似乎更多的是二维曲线拟合,可以使用
np.polyfit()
,如下例所示
z = np.load('arr.npy').astype(np.int32)
y, x = np.indices(z.shape)
valid_z = (y.ravel()>0) & (z.ravel()>0)
x_valid = x.ravel()[valid_z]
y_valid = y.ravel()[valid_z]
z_valid = z.ravel()[valid_z]
# fitting best curve
fig = plt.figure(figsize=(5,3))
ax = fig.add_subplot(111)
ax.scatter(x_valid, y_valid, c=z_valid, alpha=0.2, s=20, edgecolor='none',
cmap=plt.cm.jet)
# finding best-fit curve
z = np.polyfit(x_valid, y_valid, w=z_valid**0.5, deg=1)
p = np.poly1d(z)
# plotting
x_plot = np.linspace(x_valid.min(), x_valid.max(), 100)
y_plot = p(x_plot)
ax.plot(x_plot, y_plot, '-r', lw=2)
ax.set_xlim(0, x.shape[1])
ax.set_ylim(0, y.shape[0])
ax.legend(loc='lower left', frameon=False, fontsize=8)
fig.savefig('test.png', bbox_inches='tight')
其中:
通过避免复制数据并考虑复制的观察结果,您可以获得更快的结果。我还忽略了聚集在数据底部边缘的可能是坏数据
import numpy
import matplotlib.pyplot as plt
# Load the data
arr = numpy.load('arr.npy')
# Extract the counts from the data
data = numpy.array([(j, i, n) for (i, j), n in numpy.ndenumerate(arr)
if n != 0.0 and i > 0])
x, y, n = data.T
weight = numpy.sqrt(n)
# Fit the data, weighting appropriately for the number of points
p = numpy.polyfit(x, y, 1, w=weight)
# Evaluate the polynomial - this is here to make it easier to use
# other orders
smoothx = numpy.linspace(x.min(), x.max(), 100)
smoothy = numpy.polyval(p, smoothx)
# Plot the data and the fit
plt.pcolor(numpy.log(arr+1))
plt.plot(smoothx, smoothy, color='red', linewidth=2)
plt.xlim([0, 255])
plt.ylim([0, 255])
plt.show()
通过避免复制数据并考虑复制的观察结果,您可以获得更快的结果。我还忽略了聚集在数据底部边缘的可能是坏数据
import numpy
import matplotlib.pyplot as plt
# Load the data
arr = numpy.load('arr.npy')
# Extract the counts from the data
data = numpy.array([(j, i, n) for (i, j), n in numpy.ndenumerate(arr)
if n != 0.0 and i > 0])
x, y, n = data.T
weight = numpy.sqrt(n)
# Fit the data, weighting appropriately for the number of points
p = numpy.polyfit(x, y, 1, w=weight)
# Evaluate the polynomial - this is here to make it easier to use
# other orders
smoothx = numpy.linspace(x.min(), x.max(), 100)
smoothy = numpy.polyval(p, smoothx)
# Plot the data and the fit
plt.pcolor(numpy.log(arr+1))
plt.plot(smoothx, smoothy, color='red', linewidth=2)
plt.xlim([0, 255])
plt.ylim([0, 255])
plt.show()
啊,非常感谢!哇,这套动作需要很长时间才能完成。已经两个小时了,正常吗?我在一张联合直方图图像上试过,所以是一个数据类型为float64的256x256 np数组。@benbran我从来没有试过引用答案的例程。。。你能以某种方式提供你的矩阵,这样我就可以用一个新的例程进行测试吗?对不起,我没有读到你想要的是实际的矩阵。我通过一个投递箱提供了它link@benbran我创造了一个我觉得有希望的解决方案。。。你能试试吗?啊,非常感谢!哇,这套动作需要很长时间才能完成。已经两个小时了,正常吗?我在一张联合直方图图像上试过,所以是一个数据类型为float64的256x256 np数组。@benbran我从来没有试过引用答案的例程。。。你能以某种方式提供你的矩阵,这样我就可以用一个新的例程进行测试吗?对不起,我没有读到你想要的是实际的矩阵。我通过一个投递箱提供了它link@benbran我创造了一个我觉得有希望的解决方案。。。你能试试吗?+1谢谢你关于使用重量的提示。。。我不知道这个功能…+1谢谢你关于使用重量的提示。。。我不知道这个能力。。。