使用卷积神经网络预测股票价格:解决'Close'列缺失问题
使用卷积神经网络预测股票价格是一个常见的机器学习任务。本文将介绍如何使用 Python 中的 Keras 库构建一个卷积神经网络模型,并使用股票价格数据进行训练和预测。/n/npython/nimport numpy as np/nimport pandas as pd/nfrom keras.models import Sequential/nfrom keras.layers import Dense, Dropout, Flatten, Conv1D, MaxPooling1D/n/n# 加载股票价格数据/ndata = pd.read_excel('E://pythonProject5//深度学习//新建 XLS 工作表.xls')/n/n# 数据预处理/nprices = data['Close'].values/nprices_diff = np.diff(prices)/nprices_diff = np.insert(prices_diff, 0, 0)/n/n# 构建卷积神经网络模型/nmodel = Sequential()/nmodel.add(Conv1D(filters=64, kernel_size=3, activation='relu', input_shape=(len(prices), 1)))/nmodel.add(Conv1D(filters=64, kernel_size=3, activation='relu'))/nmodel.add(MaxPooling1D(pool_size=2))/nmodel.add(Flatten())/nmodel.add(Dense(100, activation='relu'))/nmodel.add(Dropout(0.5))/nmodel.add(Dense(1, activation='linear'))/n/n# 编译模型/nmodel.compile(loss='mse', optimizer='adam')/n/n# 训练模型/nmodel.fit(prices_diff.reshape(-1, len(prices), 1), prices, epochs=50, batch_size=32)/n/n# 使用模型进行预测/npredicted_prices = model.predict(prices_diff.reshape(-1, len(prices), 1)) /n/n/n/n在运行代码时,你可能会遇到以下错误:/n/n/nC://Users//Administrator//anaconda3//python.exe E://pythonProject5//深度学习//vf.py /nTraceback (most recent call last):/n File /'C://Users//Administrator//anaconda3//lib//site-packages//pandas//core//indexes//base.py/', line 3080, in get_loc/n return self._engine.get_loc(casted_key)/n File /'pandas/_libs//index.pyx/', line 70, in pandas._libs.index.IndexEngine.get_loc/n File /'pandas/_libs//index.pyx/', line 101, in pandas._libs.index.IndexEngine.get_loc/n File /'pandas/_libs//hashtable_class_helper.pxi/', line 4554, in pandas._libs.hashtable.PyObjectHashTable.get_item/n File /'pandas/_libs//hashtable_class_helper.pxi/', line 4562, in pandas._libs.hashtable.PyObjectHashTable.get_item/nKeyError: 'Close'/n/nThe above exception was the direct cause of the following exception:/n/nTraceback (most recent call last):/n File /'E://pythonProject5//深度学习//vf.py/', line 10, in <module>/n prices = data['Close'].values/n File /'C://Users//Administrator//anaconda3//lib//site-packages//pandas//core//frame.py/', line 3024, in __getitem__/n indexer = self.columns.get_loc(key)/n File /'C://Users//Administrator//anaconda3//lib//site-packages//pandas//core//indexes//base.py/', line 3082, in get_loc/n raise KeyError(key) from err/nKeyError: 'Close'/n/n/n这个错误提示信息表明代码中的第10行出现了KeyError: 'Close'的错误,即找不到名为'Close'的列。这可能是因为:/n/n1. 数据文件中没有名为'Close'的列。/n2. 列名不完全一致,例如数据文件中列名为'close'或'Closing Price'等。/n/n为了解决这个问题,你需要检查数据文件中的列名是否正确,并进行相应的修改。例如,如果你发现数据文件中列名为'close',则需要将代码中的data['Close']改为data['close']。/n/n修改代码后,重新运行程序,应该就可以解决KeyError: 'Close'的问题,并成功地训练和预测股票价格了。/n/n注意:/n/n* 股票价格数据往往包含噪声和随机性,因此预测结果可能不完全准确。/n* 需要根据实际情况选择合适的模型参数和训练数据。/n* 仅供学习参考,不能作为投资建议。/n
原文地址: https://www.cveoy.top/t/topic/oY2y 著作权归作者所有。请勿转载和采集!