简体   繁体   中英

A different situation of “ValueError: x and y must have same first dimension”

I am wondering why the same code runs differently in Spyder and Pycharm? It shows graph in Spyder, but it doesn't in Pycharm. Although there is the same error, the results are different. I don't know how to deal with it, I look for answers in stackoverflow, the answers all says the lengths of x and y are different, but I don't know how to correct in my example.

import numpy as np
from numpy.linalg import inv
import matplotlib.pyplot as plt

np.random.seed(1)

N = 30

mean = (1, 2)
cov = [[1.8, 0], [0, 1.8]]
x1 = np.random.multivariate_normal(mean, cov, N)
mean = (2, 1)
x2 = np.random.multivariate_normal(mean, cov, N)

x12 = np.concatenate((x1, x2), axis=0)

mean = (1, -1)
x3 = np.random.multivariate_normal(mean, cov, N)
mean = (1.5, -1.5)
x4 = np.random.multivariate_normal(mean, cov, N)

x34 = np.concatenate((x3, x4), axis=0)

plt.plot(x12[:, 0], x12[:, 1], 'o', color='b')
plt.plot(x34[:, 0], x34[:, 1], 'o', color='r')

X = np.concatenate((x12, x34), axis=0)
X_1 = np.concatenate((np.ones((120, 1)), X), axis=1)

y = np.ones(2*N)
y = np.concatenate((y, 0*y), axis=0)

beta = np.dot(inv(np.dot(X_1.transpose(), X_1)),
              np.dot(X_1.transpose(), y))

intercept = beta[0]  # beta_0
coef = beta[:1]  # beta_1 and beta_2

# Calculate RSS
rss = np.dot(y - np.dot(X_1, beta), y - np.dot(X_1, beta))

print("\nThe estimated model parameters are")
print(intercept)
print(coef)
print(rss)

p1x = -3  # Left x limit
p2x = 6  # Right x Limit
p1y = (0.5 - beta[0] - beta[1]*p1x)/beta[2]  # Y value at p1x (left)
p2y = (0.5 - beta[0] - beta[1]*p2x)/beta[2]  # Y value at p2x (right)
Pts = np.array([[p1x, p1y], [p2x, p2y]])
# Now draw the boundary
plt.plot(Pts[:, 0], Pts[:1], '_', color='black')

Thank u guys for your attention. The following answer did solve the error I posted, but I still can't get any graph in Pycharm. I have already tried add "plt.show()" at the end, but it doesn't work. The following result is all I get in console:

The estimated model parameters are
0.394336889526
[ 0.39433689]
15.2577282371

Pts is an array with shape (2,2). From this array you select the first column by Pts[:, 0] and the first row by Pts[:1] . However the shapes are different. While Pts[:, 0] is a 1D array, Pts[:1] is a 2D array (although only one dimension is filled.

Since it's not clear from the question what the purpose of this is, I have to guess that in reality you want to plot the second column of the array agains the first, which would be done using Pts[:,1]

plt.plot(Pts[:, 0], Pts[:,1], '_', color='black')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM