def predictKnn(data, priceToPredict):
corelationCoefficiantDictionary = {}
corelationCoefficiantArray = []
openingPriceTrain, openingPriceTest, closingPriceTrain, closingPriceTest = \
data["openingPriceTrain"], data["openingPriceTest"], data["closingPriceTrain"], data["closingPriceTest"]
for k in range( 1 , 100 , 1):
neigh = KNeighborsRegressor(n_neighbors=k)
#n = 7 best fits
neigh.fit(openingPriceTrain, closingPriceTrain)
closingPriceTestArray = np.reshape(closingPriceTest,-1)
knnpr = neigh.predict(openingPriceTest)
predictedArray = np.reshape(knnpr,-1)
corelationCoefficient = pearsonr(closingPriceTestArray,predictedArray)
corelationCoefficiantDictionary[k] = corelationCoefficient[0]
corelationCoefficiantArray.append(corelationCoefficient[0])
plotter.plot(corelationCoefficiantArray)
# plotter.show()
bestK = max(corelationCoefficiantDictionary, key=corelationCoefficiantDictionary.get)
neighBest = KNeighborsRegressor(n_neighbors=bestK)
neighBest.fit(openingPriceTrain, closingPriceTrain)
openingPriceToPredict = np.array([priceToPredict])
print("K = ")
print(bestK)
print(neighBest.predict(openingPriceToPredict))
评论列表
文章目录