我正在尝试通过机器学习在Python中实现斐波那契数列。我希望我的程序预测给定输入后的下5位数字。例如,如果我通过[0,1,1]
,它将预测并返回[2,3,5,8,13]
。但是,我找不到解决方法。我的程序目前只能预测下一位数字。是的,我可以对其进行硬编码,使用新的输出来更新数组,但是我不想这样做。
我的代码:
#! /usr/bin/python3
from sklearn import svm
from sklearn.linear_model import LinearRegression
features = [
[0,1,1],
[2,3,5],
[8,13,21],
[34,55,89],
]
labels = [2,8,34,144]
clf = LinearRegression()
clf.fit(features, labels)
test = [[144, 233, 377]]
print(clf.predict(test))
有帮助吗?
答案 0 :(得分:2)
这可能会帮助您;参见代码中的注释
from sklearn.linear_model import LinearRegression
#define your inputs
features = [ [0,1,1],
[2,3,5],
[8,13,21],
[34,55,89] ]
labels = [2,8,34,144]
# create your linear regression extrapolator
clf = LinearRegression()
clf.fit(features, labels)
# create a simple function to find the next number in the fibonacci sequence
def find_next(feat_list):
# feat_list is your input list of numbers
result = clf.predict(feat_list)
result = result.tolist()
result = [int(x) for x in result]
return result
# create one more function to iterate and add as many numbers to the sequence as you want
def find_next_numbers(feat_list, how_many):
# feat_list is your input list of numbers
# how_many is the number of numbers you want to append
result = []
for i in range(how_many):
nextnum = find_next(feat_list)
result = result + nextnum
# remove the smallest number and add the number you just found
# before you iterate again using this new list as input
feat_list[0] = feat_list[0][1:] + nextnum
return result
# test it
test = [[144, 233, 377]]
print(find_next_numbers(test, 5))
答案 1 :(得分:2)
如果要从模型中获得多个输出,则必须以这种方式进行训练。然后,这成为一个多输出问题,您需要提供3个特征并希望预测5个输出。
有关my answer here的一些说明。
当前,您正在训练它以预测单个值。因此,模型将始终预测单个值。通过在输出中输入多个值来训练模型。
类似这样的东西:
# Three features per row
features = [[0, 1, 1],
[2, 3, 5],
[8, 13, 21],
[34, 55, 89]]
# This changed.
# Now a single label consists of a list of output values to be predicted
# 5 outputs per row
labels = [[2, 3, 5, 8, 13],
[8, 13, 21, 34, 55],
[34, 55, 89, 144, 233],
[144, 233, 377, 610, 987]]
clf = LinearRegression()
clf.fit(features, labels)
test = [[144, 233, 377]]
print(clf.predict(test))
# Output
# array([[ 610., 987., 1597., 2584., 4181.]])
但是请注意,正如我在链接的答案中提到的那样,所有scikit-learn估计器都无法预测多个输出。