【问题标题】:Python: Linear Regression, reshaping numpy arrays for use in modelPython:线性回归,重塑 numpy 数组以用于模型
【发布时间】:2017-04-29 23:19:48
【问题描述】:

抱歉这个菜鸟问题...这是我的代码:

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)

那么,如何让数组适用于我的脚本中的所有函数,而不会出现结构略有不同的相同数据的不同数组?

感谢您的帮助!

【问题讨论】:

    标签: python arrays numpy machine-learning linear-regression


    【解决方案1】:

    更改这些行

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

    或者只是删除它们

    【讨论】:

    • 嗨 Feras,抱歉,如果我没有在问题中说清楚,但我已经尝试过了,这会导致其他地方出现不同的错误......(ValueError)
    • 这很有趣..我得到 ValueError: Found input variables with contrast numbers of samples: [1, 5] 适合模型 model.fit(X,Y) 的代码行
    • 是的,但是您还没有编写引发错误的代码,即:model.fit(X,Y)。你是对的,代码的第一部分(绘制图表)运行良好
    • 如果您阅读此处的链接,您会发现问题所在。 scikit-learn.org/stable/modules/generated/….
    • 您应该将数据更改为 [5,1] 形状以适合模型,但当然您不能将此形状与绘图功能一起使用。因此,只需为每个模型使用另一个数据重塑。
    猜你喜欢
    • 2015-03-21
    • 2018-12-11
    • 2017-07-22
    • 1970-01-01
    • 2019-12-29
    • 1970-01-01
    • 2012-11-18
    • 2019-10-09
    • 1970-01-01
    相关资源
    最近更新 更多