Traceback (most recent call last): File "C:\Users\superman\Desktop\双色球.py", line 36, in <module> next_number = predict_next_lottery_number() File "C:\Users\superman\Desktop\双色球.py", line 25, in predict_next_lottery_number model.fit(X, y) File "C:\Python39\lib\site-packages\sklearn\linear_model\_base.py", line 662, in fit X, y = self._validate_data( File "C:\Python39\lib\site-packages\sklearn\base.py", line 581, in _validate_data X, y = check_X_y(X, y, **check_params) File "C:\Python39\lib\site-packages\sklearn\utils\validation.py", line 964, in check_X_y X = check_array( File "C:\Python39\lib\site-packages\sklearn\utils\validation.py", line 769, in check_array raise ValueError( ValueError: Expected 2D array, got 1D array instead: array=[]. Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.
时间: 2023-08-18 10:10:58 浏览: 152
这个错误通常是因为在使用 `LinearRegression` 模型进行训练时,输入的特征数据 `X` 的维度不正确。根据错误消息,它期望接收一个二维数组,但实际上传递了一个一维数组。
为了解决这个问题,我们可以使用 `reshape` 方法来将一维数组转换为二维数组。具体来说,我们可以使用 `X.reshape(-1, 1)` 将 `X` 转换为一个列向量,其中 `-1` 表示自动推断数组的长度。以下是更新后的代码:
```python
import requests
from bs4 import BeautifulSoup
import numpy as np
from sklearn.linear_model import LinearRegression
def get_lottery_numbers():
url = 'http://kaijiang.zhcw.com/zhcw/html/ssq/list.html'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36'
}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
rows = soup.find_all('tr', {'class': 'red'})
lottery_numbers = []
for row in rows:
numbers = row.find_all('em')
lottery_numbers.append([int(number.text) for number in numbers])
return lottery_numbers
def predict_next_lottery_number():
lottery_numbers = get_lottery_numbers()
X = np.array([[i] for i in range(1, len(lottery_numbers) + 1)])
y = np.array([numbers[0] for numbers in lottery_numbers])
model = LinearRegression()
model.fit(X, y)
next_number = model.predict(np.array([[len(lottery_numbers) + 1]]))
return int(next_number)
# 测试代码
print("历史双色球开奖号码:")
lottery_numbers = get_lottery_numbers()
for numbers in lottery_numbers:
print(numbers)
print("\n预测下期双色球开奖号码:")
next_number = predict_next_lottery_number()
print(next_number)
```
请注意,这只是一个示例代码,用于说明如何使用线性回归模型进行预测。实际上,双色球的开奖结果是随机的,没有明显的规律可循。这段代码只是提供一个简单的示例,不保证预测结果的准确性。在实际应用中,我们可能需要更复杂的模型和更多的特征来提高预测准确性。
阅读全文