我用scikit-learn 获得了掌握机器学习的副本,我开始研究它。但是,似乎很多代码现在已经过时了。
本书中的第一个代码段,
import matplotlib.pyplot as plt
X = [[6], [8], [10], [14], [18]]
y = [[7], [9], [13], [17.5], [18]]
plt.figure()
plt.title('Pizza price plotted against diameter')
plt.xlabel('Diameter in inches')
plt.ylabel('Price in dollars')
plt.plot(X, y, 'k.')
plt.axis([0, 25, 0, 25])
plt.grid(True)
plt.show()
跑得很好。但是,当我转到第二个时:
from sklearn.linear_model import LinearRegression
# Training data
X = [[6], [8], [10], [14], [18]]
y = [[7], [9], [13], [17.5], [18]]
# Create and fit the model
model = LinearRegression()
model.fit(X, y)
print 'A 12" pizza should cost: $%.2f' % model.predict([12])[0]
它给了我一个错误:
A 12-inch pizza should cost: $%.2f
/home/dave/anaconda3/lib/python3.5/site-packages/sklearn/utils/validation.py:386: DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and willraise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample.
DeprecationWarning)
Traceback (most recent call last):
File "002----Chapter2-B.py", line 11, in <module>
print ("A 12-inch pizza should cost: $%.2f") % model.predict([12])[0]
TypeError: unsupported operand type(s) for %: 'NoneType' and 'float'
当应给我这个时:
A 12" pizza should cost: $13.68
有没有解决这个问题?
答案 0 :(得分:1)
尝试以下方法:
print ("A 12-inch pizza should cost: $%.2f" % model.predict(np.array([12]).reshape(1, -1)[0]))
我使用reshape(1,-1)
将2d数组传递给predict
函数。
答案 1 :(得分:0)
以下是代码:
print('A ' + diameter + ' inch pizza should cost: $%.2f' % model.predict([d] [0]))
documentation pages提供了有关predict
方法的更多详细信息:
sklearn.svm.libsvm.predict()
参数:
X : array-like, dtype=float, size=[n_samples, n_features]