2016-12-14 110 views
0

对不起,noob问题...这里是我的代码:的Python:线性回归,重塑使用numpy的阵列模型

from __future__ import division 
import sklearn 
import numpy as np 
from scipy import stats 
from sklearn.linear_model import LinearRegression 
import matplotlib.pyplot as plt 

X =np.array([6,8,10,14,18]) 
Y = np.array([7,9,13,17.5,18]) 
X = np.reshape(X,(1,5)) 
Y = np.reshape(Y,(1,5)) 

print X 
print Y 

plt.figure() 
plt.title('Pizza Price as a function of Pizza Diameter') 
plt.xlabel('Pizza Diameter (Inches)') 
plt.ylabel('Pizza Price (Dollars)') 
axis = plt.axis([0, 25, 0 ,25]) 
m, b = np.polyfit(X,Y,1) 
plt.grid(True) 
plt.plot(X,Y, 'k.') 
plt.plot(X, m*X + b, '-') 

#plt.show() 


#training data 
#x= [[6],[8],[10],[14],[18]] 
#y= [[7],[9],[13],[17.5],[18]] 

# create and fit linear regression model 
model = LinearRegression() 
model.fit(X,Y) 
print 'A 12" pizza should cost $% .2f' % model.predict(19) 

#work out cost function, which is residual sum of squares 
print 'Residual sum of squares: %.2f' % np.mean((model.predict(x)- y) ** 2) 

#work out variance (AKA Mean squared error) 
xMean = np.mean(x) 
print 'Variance is: %.2f' %np.var([x], ddof=1) 

#work out covariance (this is whether the x axis data and y axis data correlate with eachother) 
#When a and b are 1-dimensional sequences, numpy.cov(x,y)[0][1] calculates covariance 
print 'Covariance is: %.2f' %np.cov(X, Y, ddof = 1)[0][1] 


#test the model on new test data, printing the r squared coefficient 
X_test = [[8], [9], [11], [16], [12]] 
y_test = [[11], [8.5], [15], [18], [11]] 
print 'R squared for model on test data is: %.2f' %model.score(X_test,y_test) 

基本上,其中的一些功能工作,因为我已经叫X和Y变量有些则没有。

例如,作为代码,它抛出了这个错误:

TypeError: expected 1D vector for x 

为线

m, b = np.polyfit(X,Y,1) 

然而,当我注释掉两行重塑这样的变量:

#X = np.reshape(X,(1,5)) 
#Y = np.reshape(Y,(1,5)) 

我得到的错误:

ValueError: Found input variables with inconsistent numbers of samples: [1, 5] 
上线

model.fit(X,Y) 

那么

,我怎么数组在我的脚本所有功能操作,而不是用稍微不同的结构相同数据的不同排列?

感谢您的帮助!

回答

1

更改这些行

X = np.reshape(X,(5)) 
Y = np.reshape(Y,(5)) 

或只是删除他们两个enter image description here

+0

嗨Feras,对不起,如果我没有让它在这个问题清楚,但我已经尝试过,并导致不同的错误在其他地方。 ..(ValueError) – HereItIs

+0

我只是运行你的代码,它工作正常 – Feras

+0

这很有趣..我得到 ValueError:发现输入变量与不一致的样本数量:[1,5] 代码行,适合型号(X,Y) – HereItIs