请帮我解决这个 Python 错误 - “无效的语法”

数据挖掘 机器学习 Python 线性回归
2022-02-17 22:56:16

代码:

import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
house_price = [245, 312, 279, 308, 199, 219, 405, 324, 319, 255]
size = [1400, 1600, 1700, 1875, 1100, 1550, 2350, 2450, 1425, 1700]
size2 = np.array(size).reshape((-1, 1))
#fitting into the model
regr = linear_model.LinearRegression()
regr.fit(size2, house_price)
print("Coefficients: \n", regr.coef_)
print("intercept: \n", regr.intercept_)
#############################
#formula obtained for the trained model
def graph(formula, x_range):
   x = np.array(x_range)
   y = eval(formula)
   plt.plot(x, y)
#plotting the prediction line 
graph('regr.coef_*x + regr.intercept_', range(1000, 2700))
print(regr.score(size2, house_price))
plt.scatter (size,house_price, color='black')
plt.ylabel('house price')
plt.xlabel('size of house')
plt.show()

错误

**Error Line:print regr.predict([2000])**
Error: File "<ipython-input-4-9afa91ca7f9e>", line 1
    print regr.predict([2000])
             ^
SyntaxError: invalid syntax
1个回答

在您当前的行中

print regr.predict([2000])

这行不通。第一个错误是 Python 3 中需要的 print 语句的内容周围缺少括号。首先将其更改为

print(regr.predict([2000]))

但是,您会发现这也不起作用。我怀疑您正在尝试评估新产品的价格size=2000. 您需要重新调整回归的输入才能使其正常工作。

new_size = np.array([2000]).reshape((-1, 1))
print(regr.predict(new_size))

[ 317.78380528]