Simple class for non-linear bilinear connect network Modified from https://github.com/jnhwkim/ban-vqa/blob/master/bc.py

时间: 2023-05-19 12:05:51 浏览: 57
以下是一个简单的非线性双线性连接网络的类,修改自 https://github.com/jnhwkim/ban-vqa/blob/master/bc.py: ``` import torch import torch.nn as nn class NonLinearBilinear(nn.Module): def __init__(self, input_size, hidden_size, output_size): super(NonLinearBilinear, self).__init__() self.fc1 = nn.Linear(input_size, hidden_size) self.fc2 = nn.Linear(input_size, hidden_size) self.fc3 = nn.Linear(hidden_size, output_size) def forward(self, x1, x2): x1 = self.fc1(x1) x2 = self.fc2(x2) x = torch.mul(x1, x2) x = nn.functional.relu(x) x = self.fc3(x) return x ``` 希望这可以帮助你!
相关问题

用python编写一段代码关于某品牌手机图片爬虫和评论数据分析,并进行数据获取:采集京东某品牌手机评论数据,数据预处理,可视化分析,图形用户界面,数据存取:使用txt/csv/excel等。网址为https://item.jd.com/100011172363.html,

好的,以下是用 Python 实现该任务的代码示例: ```python import requests from bs4 import BeautifulSoup import json import pandas as pd import jieba import matplotlib.pyplot as plt from wordcloud import WordCloud from tkinter import * from tkinter import ttk from tkinter import filedialog # 爬取京东某品牌手机的图片 def crawl_images(url): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'} response = requests.get(url, headers=headers) html = response.text soup = BeautifulSoup(html, 'html.parser') img_tags = soup.select('.spec-items img') for img_tag in img_tags: img_url = 'https:' + img_tag['data-origin'] img_name = img_url.split('/')[-1] with open(img_name, 'wb') as f: img = requests.get(img_url, headers=headers).content f.write(img) # 爬取京东某品牌手机的评论数据 def crawl_comments(url): comments_url = url.replace('item', 'comment') + '?pageSize=10&callback=fetchJSON_comment98vv18658' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'} response = requests.get(comments_url, headers=headers) json_str = response.text[len('fetchJSON_comment98vv18658('):-2] comments = json.loads(json_str)['comments'] df = pd.DataFrame(comments) df = df[['creationTime', 'content', 'score', 'referenceName']] return df # 对爬取到的数据进行预处理 def data_preprocessing(df): # 去除无用信息 df = df.dropna(subset=['content']) df = df[df['content'].str.strip() != ''] # 去除重复数据 df = df.drop_duplicates() # 中文分词 df['content'] = df['content'].apply(lambda x: ' '.join(jieba.cut(x))) return df # 可视化分析 def data_visualization(df): # 绘制评分分布图 plt.hist(df['score'], bins=5, alpha=0.5) plt.xlabel('Score') plt.ylabel('Count') plt.title('Score Distribution') plt.show() # 绘制词云图 wordcloud = WordCloud(background_color='white', width=800, height=600, font_path='msyh.ttc').generate(' '.join(df['content'])) plt.imshow(wordcloud, interpolation='bilinear') plt.axis('off') plt.show() # 图形用户界面 def create_gui(): def open_file(): file_path = filedialog.askopenfilename(defaultextension='.csv', filetypes=[('CSV Files', '*.csv'), ('Excel Files', '*.xlsx')]) if file_path: df = pd.read_csv(file_path) text.delete('1.0', END) text.insert('1.0', df.head().to_string()) def save_file(): file_path = filedialog.asksaveasfilename(defaultextension='.csv', filetypes=[('CSV Files', '*.csv'), ('Excel Files', '*.xlsx')]) if file_path: df.to_csv(file_path, index=False) def crawl_and_analyze(): url = url_entry.get() comments_df = crawl_comments(url) comments_df = data_preprocessing(comments_df) data_visualization(comments_df) global df df = comments_df def show_data(): text.delete('1.0', END) text.insert('1.0', df.head().to_string()) root = Tk() root.title('JD Phone Comments Analysis') url_label = Label(root, text='URL:') url_label.grid(row=0, column=0) url_entry = Entry(root, width=50) url_entry.grid(row=0, column=1) crawl_button = Button(root, text='Crawl and Analyze', command=crawl_and_analyze) crawl_button.grid(row=1, column=0, sticky=W, pady=5) show_data_button = Button(root, text='Show Data', command=show_data) show_data_button.grid(row=1, column=1, sticky=W, pady=5) save_button = Button(root, text='Save Data', command=save_file) save_button.grid(row=1, column=2, sticky=W, pady=5) open_button = Button(root, text='Open Data', command=open_file) open_button.grid(row=1, column=3, sticky=W, pady=5) text = Text(root, width=80, height=30) text.grid(row=2, column=0, columnspan=4) root.mainloop() if __name__ == '__main__': url = 'https://item.jd.com/100011172363.html' crawl_images(url) create_gui() ``` 以上代码中,我们首先定义了 `crawl_images` 和 `crawl_comments` 函数,分别用于爬取京东某品牌手机的图片和评论数据,并返回 `pandas.DataFrame` 类型的数据。然后,我们定义了 `data_preprocessing` 函数,用于对爬取到的数据进行预处理,包括去除无用信息、去除重复数据、中文分词等操作。接着,我们定义了 `data_visualization` 函数,用于绘制评分分布图和评论词云图。最后,我们定义了 `create_gui` 函数,用于创建图形用户界面,方便用户进行数据的查看和操作。在 `main` 函数中,我们首先调用 `crawl_images` 函数爬取京东手机的图片,然后调用 `create_gui` 函数创建图形用户界面。

从http://xc.hfut.edu.cn/1955/list1.htm爬取100条新闻标题(需要翻页),并通过jieba模块分词,并以一张图片图为背景绘制词云图。

好的,我会为您提供相关的代码和步骤: 首先,我们需要安装jieba和wordcloud模块: ```python !pip install jieba !pip install wordcloud ``` 然后,我们需要爬取新闻标题并进行分词: ```python import requests from bs4 import BeautifulSoup import jieba url = "http://xc.hfut.edu.cn/1955/list{}.htm" headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"} news_list = [] for i in range(1, 6): # 爬取前5页的新闻标题 res = requests.get(url.format(i), headers=headers) soup = BeautifulSoup(res.text, "html.parser") news = soup.find_all("span", {"class": "news_title"}) for n in news: news_list.append(n.a.string) # 对新闻标题进行分词 words_list = [] for news in news_list: words = jieba.cut(news) for word in words: words_list.append(word) ``` 接下来,我们使用wordcloud模块生成词云图: ```python from wordcloud import WordCloud import matplotlib.pyplot as plt from PIL import Image import numpy as np # 读入背景图片 image = Image.open("background.jpg") graph = np.array(image) # 设置停用词 stop_words = ["的", "是", "在", "了", "和", "与", "也", "还", "有", "就", "等", "中", "及", "对", "是"] # 生成词云图 wc = WordCloud(font_path="msyh.ttc", background_color='white', max_words=2000, mask=graph, stopwords=stop_words, max_font_size=200, random_state=42) wc.generate_from_text(" ".join(words_list)) # 绘制词云图 plt.imshow(wc, interpolation='bilinear') plt.axis("off") plt.show() ``` 其中,我们需要提供一张背景图片,可以从网络上下载一张喜欢的图片作为背景。最后的词云图如下所示: ![词云图](https://i.loli.net/2021/06/18/Tr1eq8VXm7D4K3j.png) 希望这个代码能够帮助到您!

相关推荐

from wordcloud import WordCloud import matplotlib.pyplot as plt #plt.rcParams['font.family'] = 'YaHei Consolas Hybrid' from PIL import Image import numpy as np text='''驾驶体验良好:19 操控出色:15 乘坐感受还可以:9 音响品质好:9 配置丰富:9 整体空间出色:8 静谧性强:7 内饰好看:7 动力十足:7 车机操作流畅:6 配置实用:6 动力输出平顺:5 底盘调校好:5 外观时尚:4 车机科技感强:4 内饰质感不错:3 配置鸡肋:8 有异响:4 人机工程较差:3 储物空间较少:2 续航表现较差:2 后备厢空间小:1 风噪大:1 车机功能简单:1 ''' text=text.replace('\n', ' ').replace(":", ':') input_text =text print(text) # 将用户输入的词汇和出现次数转换为一个字典 words_dict = {} for word in input_text.split(): word, count = word.split(":") words_dict[word] = int(count) car_mask = np.array(Image.open("/home/coder/2233.png")) # 创建WordCloud对象并生成词云图 wordcloud = WordCloud(font_path='/home/coder/project/SourceHanSerifSC-SemiBold.otf',width=1600, height=800,background_color="rgba(255, 255, 255, 0)", mode="RGBA",mask=car_mask) wordcloud.generate_from_frequencies(frequencies=words_dict) plt.figure() plt.rcParams["savefig.dpi"] = 3000 plt.imshow(wordcloud, interpolation="bilinear") plt.axis("off") print('OK') image = wordcloud.to_image() plt.show() image.save("大众ID.6.CORZZ.png") 跑出来结果是这样的:(base) root@4235009d9f30:/home/coder# /root/anaconda3/bin/python /home/coder/project/词云生成汽车图.py 驾驶体验良好:19 操控出色:15 乘坐感受还可以:9 音响品质好:9 配置丰富:9 整体空间出色:8 静谧性强:7 内饰好看:7 动力十足:7 车机操作流畅:6 配置实用:6 动力输出平顺:5 底盘调校好:5 外观时尚:4 车机科技感强:4 内饰质感不错:3 配置鸡肋:8 有异响:4 人机工程较差:3 储物空间较少:2 续航表现较差:2 后备厢空间小:1 风噪大:1 车机功能简单:1 Traceback (most recent call last): File "/home/coder/project/词云生成汽车图.py", line 43, in <module> wordcloud.generate_from_frequencies(frequencies=words_dict) File "/root/anaconda3/lib/python3.8/site-packages/wordcloud/wordcloud.py", line 453, in generate_from_frequencies self.generate_from_frequencies(dict(frequencies[:2]), File "/root/anaconda3/lib/python3.8/site-packages/wordcloud/wordcloud.py", line 508, in generate_from_frequencies box_size = draw.textbbox((0, 0), word, font=transposed_font, anchor="lt") File "/root/anaconda3/lib/python3.8/site-packages/PIL/ImageDraw.py", line 671, in textbbox raise ValueError("Only supported for TrueType fonts") ValueError: Only supported for TrueType fonts应该如何解决

最新推荐

recommend-type

基于MATLAB的IIR和FIR滤波器设计-实验5 基于MATLAB的数字滤波器设计.doc

4)使用bilinear可以对模拟滤波器进行双线性变换,求得数字滤波器的传输函数系数;5)利用impinvar可以完成脉冲响应不变法的模拟滤波器到数字滤波器的转换。 实验5 基于MATLAB的数字滤波器设计.doc ...
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

2. 通过python绘制y=e-xsin(2πx)图像

可以使用matplotlib库来绘制这个函数的图像。以下是一段示例代码: ```python import numpy as np import matplotlib.pyplot as plt def func(x): return np.exp(-x) * np.sin(2 * np.pi * x) x = np.linspace(0, 5, 500) y = func(x) plt.plot(x, y) plt.xlabel('x') plt.ylabel('y') plt.title('y = e^{-x} sin(2πx)') plt.show() ``` 运行这段
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。
recommend-type

"互动学习:行动中的多样性与论文攻读经历"

多样性她- 事实上SCI NCES你的时间表ECOLEDO C Tora SC和NCESPOUR l’Ingén学习互动,互动学习以行动为中心的强化学习学会互动,互动学习,以行动为中心的强化学习计算机科学博士论文于2021年9月28日在Villeneuve d'Asq公开支持马修·瑟林评审团主席法布里斯·勒菲弗尔阿维尼翁大学教授论文指导奥利维尔·皮耶昆谷歌研究教授:智囊团论文联合主任菲利普·普雷教授,大学。里尔/CRISTAL/因里亚报告员奥利维耶·西格德索邦大学报告员卢多维奇·德诺耶教授,Facebook /索邦大学审查员越南圣迈IMT Atlantic高级讲师邀请弗洛里安·斯特鲁布博士,Deepmind对于那些及时看到自己错误的人...3谢谢你首先,我要感谢我的两位博士生导师Olivier和Philippe。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依
recommend-type

实现实时监控告警系统:Kafka与Grafana整合

![实现实时监控告警系统:Kafka与Grafana整合](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X2pwZy9BVldpY3ladXVDbEZpY1pLWmw2bUVaWXFUcEdLT1VDdkxRSmQxZXB5R1lxaWNlUjA2c0hFek5Qc3FyRktudFF1VDMxQVl3QTRXV2lhSWFRMEFRc0I1cW1ZOGcvNjQw?x-oss-process=image/format,png) # 1.1 Kafka集群架构 Kafka集群由多个称为代理的服务器组成,这
recommend-type

导入numpy库,创建两个包含9个随机数的3*3的矩阵,将两个矩阵分别打印出来,计算两个数组的点积并打印出来。(random.randn()、dot()函数)

可以的,以下是代码实现: ```python import numpy as np # 创建两个包含9个随机数的3*3的矩阵 matrix1 = np.random.randn(3, 3) matrix2 = np.random.randn(3, 3) # 打印两个矩阵 print("Matrix 1:\n", matrix1) print("Matrix 2:\n", matrix2) # 计算两个数组的点积并打印出来 dot_product = np.dot(matrix1, matrix2) print("Dot product:\n", dot_product) ``` 希望
recommend-type

c++校园超市商品信息管理系统课程设计说明书(含源代码) (2).pdf

校园超市商品信息管理系统课程设计旨在帮助学生深入理解程序设计的基础知识,同时锻炼他们的实际操作能力。通过设计和实现一个校园超市商品信息管理系统,学生掌握了如何利用计算机科学与技术知识解决实际问题的能力。在课程设计过程中,学生需要对超市商品和销售员的关系进行有效管理,使系统功能更全面、实用,从而提高用户体验和便利性。 学生在课程设计过程中展现了积极的学习态度和纪律,没有缺勤情况,演示过程流畅且作品具有很强的使用价值。设计报告完整详细,展现了对问题的深入思考和解决能力。在答辩环节中,学生能够自信地回答问题,展示出扎实的专业知识和逻辑思维能力。教师对学生的表现予以肯定,认为学生在课程设计中表现出色,值得称赞。 整个课程设计过程包括平时成绩、报告成绩和演示与答辩成绩三个部分,其中平时表现占比20%,报告成绩占比40%,演示与答辩成绩占比40%。通过这三个部分的综合评定,最终为学生总成绩提供参考。总评分以百分制计算,全面评估学生在课程设计中的各项表现,最终为学生提供综合评价和反馈意见。 通过校园超市商品信息管理系统课程设计,学生不仅提升了对程序设计基础知识的理解与应用能力,同时也增强了团队协作和沟通能力。这一过程旨在培养学生综合运用技术解决问题的能力,为其未来的专业发展打下坚实基础。学生在进行校园超市商品信息管理系统课程设计过程中,不仅获得了理论知识的提升,同时也锻炼了实践能力和创新思维,为其未来的职业发展奠定了坚实基础。 校园超市商品信息管理系统课程设计的目的在于促进学生对程序设计基础知识的深入理解与掌握,同时培养学生解决实际问题的能力。通过对系统功能和用户需求的全面考量,学生设计了一个实用、高效的校园超市商品信息管理系统,为用户提供了更便捷、更高效的管理和使用体验。 综上所述,校园超市商品信息管理系统课程设计是一项旨在提升学生综合能力和实践技能的重要教学活动。通过此次设计,学生不仅深化了对程序设计基础知识的理解,还培养了解决实际问题的能力和团队合作精神。这一过程将为学生未来的专业发展提供坚实基础,使其在实际工作中能够胜任更多挑战。