matplotlib:为什么LinearRegression行没有出现?

时间:2017-11-19 16:04:30

标签: python machine-learning

使用Geany IDE

python file.py运行iTerm2命令时,我得到以下信息 错误讯息:

/usr/local/lib/python2.7/site-packages/scipy/linalg/basic.py:1226: RuntimeWarning: internal gelsd driver lwork query error, required iwork dimension not returned. This is likely the result of LAPACK bug 0038, fixed in LAPACK 3.2.2 (released July 21, 2010). Falling back to 'gelss' driver.
  warnings.warn(mesg, RuntimeWarning)
A 12" pizza should cost: $13.68

'这是我的代码:

    import numpy as np
    import matplotlib.pyplot as plt
    from sklearn.linear_model import LinearRegression 


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

    # In[2]:
    model = LinearRegression()  # Create an instance of the estimator
    model.fit(X, y)  # Fit the model on the training data 

    # Predict the price of a pizza with a diameter that has never been                              seen before 
     test_pizza = np.array([[12]]) 
     predicted_price = model.predict(test_pizza)[0] 



     plt.figure()
     plt.title('pizza thing')
     plt.xlabel('x-axis diam')
     plt.ylabel('y-axis price dollar dollar')
     plt.plot(X,y, 'k.')
     plt.axis([0,25,0,25])
     plt.grid(True)
     plt.show()

     print('A 12" pizza should cost: $%.2f' % predicted_price) `

编辑:添加了预期的图表。谢谢你们。

post

Expected Graph

更新:GRAPH OUTPUT

1 个答案:

答案 0 :(得分:0)

您似乎正试图在y旁边绘制y的预测结果。为此,您需要对代码进行一些更改:

  • predicted_price = model.predict(X)代替predicted_price = model.predict(test_pizza)[0]
  • plt.plot(X,predicted_price)
  • 之后添加plt.plot(X,y, 'k.')

总体而言,以下是更改后代码的外观:

import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression 
X = np.array([[6], [8], [10], [14], [18]]).reshape(-1,1)
y = [7,9,13,17.5,18]

# In[2]:
model = LinearRegression()  # Create an instance of the estimator
model.fit(X, y)  # Fit the model on the training data 

# Predict the price of a pizza with a diameter that has never been                              seen before 
#test_pizza = np.array([[12]])  
predicted_price = model.predict(X)


plt.figure()
plt.title('pizza thing')
plt.xlabel('x-axis diam')
plt.ylabel('y-axis price dollar dollar')
plt.plot(X,y, 'k.')
plt.plot(X,predicted_price)
plt.axis([0,25,0,25])
plt.grid(True)
plt.show()

print('A 12" pizza should cost: $%.2f' % predicted_price)