if __name__ == '__main__': # 通过pandas读入数据 data = pd.read_excel('../1data.xls', encoding='utf-8', header=None) data.columns = ['class_label', 'text', 'tokens'] label = data['class_label'] categories = [] for i in label: if i in categories: pass else: categories.append(i) print(categories) le = preprocessing.LabelEncoder().fit_transform(data['class_label']) data["class_label"] = le # 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(data["tokens"], data["class_label"], test_size=0.2, random_state=1) # 文本特征提取 X_train_tfidf, tfidf_vectorizer = tfidf(X_train) X_test_tfidf = tfidf_vectorizer.transform(X_test) modelFile = "SVMModel.m" # 训练保存模型 SVMClassify() # 预测测试集结果 SVMTest()
时间: 2024-02-14 17:31:31 浏览: 45
这部分代码是在主函数中进行数据预处理、模型训练和测试的过程。首先,你使用pandas库读取了一个Excel文件,并将数据命名为data。然后,你为数据的列名进行了命名,分别是'class_label'、'text'和'tokens'。
接下来,你提取了标签(label)并将其存储在categories列表中。这个循环遍历了标签(label)列表,如果标签(label)已经在categories列表中,则跳过,否则将其添加到categories列表中。
之后,你使用LabelEncoder对data['class_label']进行了编码,并将编码后的结果存储在le变量中。然后,将data["class_label"]更新为编码后的结果。
接着,你使用train_test_split函数将数据集划分为训练集(X_train, y_train)和测试集(X_test, y_test),其中测试集占总数据集的20%。
然后,你使用tfidf函数对训练集进行了文本特征提取,得到了训练集的tfidf表示(X_train_tfidf)和tfidf向量化器(tfidf_vectorizer)。
接下来,你指定了模型文件的路径(modelFile)。
然后,你调用了SVMClassify函数进行模型训练,并保存了训练好的模型。
最后,你调用了SVMTest函数对测试集进行预测,并输出了一些评估指标。
相关问题
import urllib3 import pandas as pd import os def download_content(url): http = urllib3.PoolManager() response = http.request("GET", url) response_data = response.data html_content = response_data.decode() return html_content def save_excel(): html_content = download_content("http://fx.cmbchina.com/Hq/") cmb_table_list = pd.read_html(html_content) cmb_table_list[1].to_excel("Bit&Yanan.xlsx") def main(): save_excel() if __name__ == '__main__': main() os.startfile("Bit&Yanan.xlsx") import pandas as pd import matplotlib.pyplot as plt import numpy as np plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签 plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号 rapx = (114.4936096 - 112.6832583)/50 rapy = (23.87839806 - 22.49308313)/50 minx = 112.6832583+rapx*2 maxx = 114.4936096+rapx*2 miny = 22.49308313 maxy = 23.87839806 data = pd.read_excel("Bit&Yanan.xlsx") print(data.head()),继续完成用
pandas和matplotlib库分析和展示数据的任务。
首先,我们可以查看一下读入数据后的前几行,使用`.head()`函数,例如`print(data.head())`。
接下来,你可以使用pandas库进行数据的筛选和处理,例如选取特定列、按照某列进行排序、按照某列筛选数据等等。具体使用方法可以参考pandas的官方文档或者各种在线教程。
最后,你可以使用matplotlib库绘制各种图表,例如折线图、散点图、柱状图等等,来展示数据的规律和趋势。同样的,matplotlib库的使用方法可以参考官方文档或者各种在线教程。需要注意的是,matplotlib库的绘图需要一定的数学基础和美学素养,因此建议在实际操作中结合各种案例和实践经验,不断提高自己的绘图技能。
import numpy as np import pandas as pd def read_asc(filepath): asc_file = pd.read_csv(filepath, skiprows=4, encoding="gbk", engine='python', sep=' ', delimiter=None, index_col=False, header=None, skipinitialspace=True) file = np.array(asc_file) data = read_message(file) filter_step_size(data) def read_message(file): mask = file[:, 4] == "107" data = file[mask] return data def filter_step_size(data): diff = np.diff(data[:, 0]) mask = np.logical_and(0.090 < diff, diff < 0.110) success_sum = np.count_nonzero(mask) fail_sum = len(mask) - success_sum result = np.column_stack((data[:-1, 0], data[1:, 0], diff)) result = result[~mask] print("步长通过数: {}".format(success_sum)) print("步长未通过数: {}".format(fail_sum)) print("未通过前一项值:未通过后一项值:差值:") print(result) if __name__ == '__main__': read_asc("E:\package\databin 7-11-2023 9-12-31 am Messages File.asc") 这段代码在运行时报错”Unable to allocate 1.63 GiB for an array with shape (4475770, 49) and data type object“,怎么修改优化
这个错误是由于 NumPy 数组中存在大量的对象类型(`object`)数据导致的。对象类型的数据通常需要更多的内存空间来存储,因此可能会导致内存不足的错误。
为了解决这个问题,你可以尝试以下优化措施:
1. 检查数据类型:查看你的数据文件中是否有非数值类型的列。如果有,可以尝试将其转换为适当的数值类型(如整数、浮点数等)来减少内存使用。
2. 限制读取的列数:在 `read_asc` 函数中,你可以尝试只读取需要使用的列,而不是将整个文件都读入内存。这样可以减少内存占用。
3. 分块读取数据:如果数据文件太大,无法一次性读入内存,可以考虑使用 Pandas 的 `read_csv` 函数的 `chunksize` 参数来分块读取数据,并在每一块中进行处理。
下面是修改后的代码示例:
```python
import numpy as np
import pandas as pd
def read_asc(filepath):
usecols = [0, 4] # 仅读取第0列和第4列
chunksize = 100000 # 每次读取100000行数据
for chunk in pd.read_csv(filepath, skiprows=4, encoding="gbk", engine='python', sep=' ', delimiter=None,
index_col=False, header=None, skipinitialspace=True, usecols=usecols, chunksize=chunksize):
file = np.array(chunk)
data = read_message(file)
filter_step_size(data)
def read_message(file):
mask = file[:, 1] == "107"
data = file[mask]
return data
def filter_step_size(data):
diff = np.diff(data[:, 0].astype(float)) # 将第0列转换为浮点数类型
mask = np.logical_and(0.090 < diff, diff < 0.110)
success_sum = np.count_nonzero(mask)
fail_sum = len(mask) - success_sum
result = np.column_stack((data[:-1, 0], data[1:, 0], diff))
result = result[~mask]
print("步长通过数: {}".format(success_sum))
print("步长未通过数: {}".format(fail_sum))
print("未通过前一项值:未通过后一项值:差值:")
print(result)
if __name__ == '__main__':
read_asc("E:\package\databin 7-11-2023 9-12-31 am Messages File.asc")
```
通过以上优化,我们限制了读取的列数,使用了分块读取数据的方式,并将第0列转换为浮点数类型,以减少内存占用。希望这能够解决你遇到的问题。如果问题仍然存在,请提供更多关于数据文件的信息,以便我能够给出更准确的解决方案。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)