大模型系列:OpenAI使用技巧_使用OpenAI进行K-means聚类

文章目录

      • 1. 使用K-means算法找到聚类
      • 2. 聚类中的文本样本和聚类的命名让我们展示每个聚类中的随机样本。

我们使用一个简单的k-means算法来演示如何进行聚类。聚类可以帮助发现数据中有价值的隐藏分组。数据集是在 Get_embeddings_from_dataset Notebook中创建的。

# 导入必要的库
import numpy as np
import pandas as pd
from ast import literal_eval

# 数据文件路径
datafile_path = "./data/fine_food_reviews_with_embeddings_1k.csv"

# 读取csv文件为DataFrame格式
df = pd.read_csv(datafile_path)

# 将embedding列中的字符串转换为numpy数组
df["embedding"] = df.embedding.apply(literal_eval).apply(np.array)

# 将所有的embedding数组按行堆叠成一个矩阵
matrix = np.vstack(df.embedding.values)

# 输出矩阵的形状
matrix.shape
(1000, 1536)

1. 使用K-means算法找到聚类

我们展示了K-means的最简单用法。您可以选择最适合您用例的聚类数量。

# 导入KMeans聚类算法
from sklearn.cluster import KMeans

# 设置聚类数目
n_clusters = 4

# 初始化KMeans算法,设置聚类数目、初始化方法和随机种子
kmeans = KMeans(n_clusters=n_clusters, init="k-means++", random_state=42)

# 使用KMeans算法对数据进行聚类
kmeans.fit(matrix)

# 获取聚类标签
labels = kmeans.labels_

# 将聚类标签添加到数据框中
df["Cluster"] = labels

# 按照聚类标签对数据框进行分组,计算每个聚类的平均分数,并按照平均分数排序
df.groupby("Cluster").Score.mean().sort_values()
/Users/ted/.virtualenvs/openai/lib/python3.9/site-packages/sklearn/cluster/_kmeans.py:870: FutureWarning: The default value of `n_init` will change from 10 to 'auto' in 1.4. Set the value of `n_init` explicitly to suppress the warning
  warnings.warn(





Cluster
0    4.105691
1    4.191176
2    4.215613
3    4.306590
Name: Score, dtype: float64
# 导入必要的库
from sklearn.manifold import TSNE
import matplotlib
import matplotlib.pyplot as plt

# 初始化t-SNE模型,设置参数
tsne = TSNE(n_components=2, perplexity=15, random_state=42, init="random", learning_rate=200)

# 使用t-SNE模型对数据进行降维
vis_dims2 = tsne.fit_transform(matrix)

# 提取降维后的数据的x和y坐标
x = [x for x, y in vis_dims2]
y = [y for x, y in vis_dims2]

# 针对每个类别,绘制散点图,并标记类别的平均值
for category, color in enumerate(["purple", "green", "red", "blue"]):
    # 提取属于当前类别的数据的x和y坐标
    xs = np.array(x)[df.Cluster == category]
    ys = np.array(y)[df.Cluster == category]
    # 绘制散点图
    plt.scatter(xs, ys, color=color, alpha=0.3)
    # 计算当前类别的平均值
    avg_x = xs.mean()
    avg_y = ys.mean()
    # 标记平均值
    plt.scatter(avg_x, avg_y, marker="x", color=color, s=100)

# 设置图表标题
plt.title("Clusters identified visualized in language 2d using t-SNE")
Text(0.5, 1.0, 'Clusters identified visualized in language 2d using t-SNE')

在二维投影中对聚类进行可视化。在这次运行中,绿色聚类(#1)似乎与其他聚类非常不同。让我们看一下每个聚类的几个样本。

2. 聚类中的文本样本和聚类的命名让我们展示每个聚类中的随机样本。

我们将使用text-davinci-003来为聚类命名,基于从该聚类中随机抽取的5个评论样本。

# 导入openai模块

import openai

# 每个聚类组中的评论数量
rev_per_cluster = 5

# 遍历每个聚类组
for i in range(n_clusters):
    # 输出聚类组的主题
    print(f"Cluster {i} Theme:", end=" ")

    # 选取属于该聚类组的评论,并将它们合并成一个字符串
    reviews = "\n".join(
        df[df.Cluster == i]
        .combined.str.replace("Title: ", "")
        .str.replace("\n\nContent: ", ":  ")
        .sample(rev_per_cluster, random_state=42)
        .values
    )

    # 使用openai模块对选取的评论进行主题分析
    response = openai.Completion.create(
        engine="text-davinci-003",
        prompt=f'What do the following customer reviews have in common?\n\nCustomer reviews:\n"""\n{reviews}\n"""\n\nTheme:',
        temperature=0,
        max_tokens=64,
        top_p=1,
        frequency_penalty=0,
        presence_penalty=0,
    )

    # 输出主题分析结果
    print(response["choices"][0]["text"].replace("\n", ""))

    # 选取属于该聚类组的样本行,并输出它们的得分、摘要和文本内容
    sample_cluster_rows = df[df.Cluster == i].sample(rev_per_cluster, random_state=42)
    for j in range(rev_per_cluster):
        print(sample_cluster_rows.Score.values[j], end=", ")
        print(sample_cluster_rows.Summary.values[j], end=":   ")
        print(sample_cluster_rows.Text.str[:70].values[j])

    # 输出分隔符
    print("-" * 100)
Cluster 0 Theme:  All of the reviews are positive and the customers are satisfied with the product they purchased.
5, Loved these gluten free healthy bars, saved $$ ordering on Amazon:   These Kind Bars are so good and healthy & gluten free.  My daughter ca
1, Should advertise coconut as an ingredient more prominently:   First, these should be called Mac - Coconut bars, as Coconut is the #2
5, very good!!:   just like the runts<br />great flavor, def worth getting<br />I even o
5, Excellent product:   After scouring every store in town for orange peels and not finding an
5, delicious:   Gummi Frogs have been my favourite candy that I have ever tried. of co
----------------------------------------------------------------------------------------------------
Cluster 1 Theme:  All of the reviews are about pet food.
2, Messy and apparently undelicious:   My cat is not a huge fan. Sure, she'll lap up the gravy, but leaves th
4, The cats like it:   My 7 cats like this food but it is a little yucky for the human. Piece
5, cant get enough of it!!!:   Our lil shih tzu puppy cannot get enough of it. Everytime she sees the
1, Food Caused Illness:   I switched my cats over from the Blue Buffalo Wildnerness Food to this
5, My furbabies LOVE these!:   Shake the container and they come running. Even my boy cat, who isn't 
----------------------------------------------------------------------------------------------------
Cluster 2 Theme:  All of the reviews are positive and express satisfaction with the product.
5, Fog Chaser Coffee:   This coffee has a full body and a rich taste. The price is far below t
5, Excellent taste:   This is to me a great coffee, once you try it you will enjoy it, this 
4, Good, but not Wolfgang Puck good:   Honestly, I have to admit that I expected a little better. That's not 
5, Just My Kind of Coffee:   Coffee Masters Hazelnut coffee used to be carried in a local coffee/pa
5, Rodeo Drive is Crazy Good Coffee!:   Rodeo Drive is my absolute favorite and I'm ready to order more!  That
----------------------------------------------------------------------------------------------------
Cluster 3 Theme:  All of the reviews are about food or drink products.
5, Wonderful alternative to soda pop:   This is a wonderful alternative to soda pop.  It's carbonated for thos
5, So convenient, for so little!:   I needed two vanilla beans for the Love Goddess cake that my husbands 
2, bot very cheesy:   Got this about a month ago.first of all it smells horrible...it tastes
5, Delicious!:   I am not a huge beer lover.  I do enjoy an occasional Blue Moon (all o
3, Just ok:   I bought this brand because it was all they had at Ranch 99 near us. I
----------------------------------------------------------------------------------------------------

重要的是要注意,聚类不一定与您打算使用它们的目的完全匹配。更多的聚类将关注更具体的模式,而较少的聚类通常会关注数据中最大的差异。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/278989.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

共享单车之数据分析

文章目录 第1关&#xff1a;统计共享单车每天的平均使用时间第2关&#xff1a;统计共享单车在指定地点的每天平均次数第3关&#xff1a;统计共享单车指定车辆每次使用的空闲平均时间第4关&#xff1a;统计指定时间共享单车使用次数第5关&#xff1a;统计共享单车线路流量 第1关…

RO-NeRF论文笔记

RO-NeRF论文笔记 文章目录 RO-NeRF论文笔记论文概述Abstract1 Introduction2 Related Work3 Method3.1 RGB and depth inpainting network3.2 Background on NeRFs3.3 Confidence-based view selection3.4 Implementation details 4 Experiments4.1 DatasetsReal ObjectsSynthe…

kafka实现延迟消息

背景 我们知道消息中间件mq是支持延迟消息的发送功能的&#xff0c;但是kafka不支持这种直接的用法&#xff0c;所以我们需要独立实现这个功能&#xff0c;以下是在kafka中实现消息延时投递功能的一种方案 kafka实现延时消息 主要的思路是增加一个检测服务&#xff0c;这个检…

2011年AMC8数学竞赛中英文真题典型考题、考点分析和答案解析

今天是2023年12月30日&#xff0c;距离2024年元旦新年还有2天时间&#xff0c;先预祝所有的读者和小读者想今年工作、学习进步&#xff01;幸福平安&#xff01; 今天距离2024年1月19日的AMC8正式比赛只有20天的时间&#xff0c;我们继续来看AMC8竞赛的历年真题典型考题和解析…

Stable Diffusion WebUI安装合成面部说话插件SadTalker

SadTalker可以根据一张图片、一段音频&#xff0c;合成面部说这段语音的视频。图片需要真人或者接近真人。 安装ffmpeg 下载地址&#xff1a; https://www.gyan.dev/ffmpeg/builds/ 下载ffmpeg-git-full.7z 后解压&#xff0c;将解压后的目录\bin添加到环境变量的Path中。 在…

MR实战:统计总分与平均分

文章目录 一、实战概述二、提出任务三、完成任务&#xff08;一&#xff09;准备数据1、在虚拟机上创建文本文件2、上传文件到HDFS指定目录 &#xff08;二&#xff09;实现步骤1、创建Maven项目2、添加相关依赖3、创建日志属性文件4、创建成绩映射器类5、创建成绩驱动器类6、启…

计算每个月的天数

大家好呀&#xff0c;今天的每日一题来喽。准备好了吗亲。上车上车&#xff01;&#xff01;&#xff01; 文章目录 目录 文章目录 题目重现 输⼊y和m两个整数&#xff0c;y表⽰年份&#xff0c;m表⽰⽉份&#xff0c;计算y年m⽉有多少天&#xff0c;并输出天数。 一、解法思路…

LLM之RAG实战(十一)| 使用Mistral-7B和Langchain搭建基于PDF文件的聊天机器人

在本文中&#xff0c;使用LangChain、HuggingFaceEmbeddings和HuggingFace的Mistral-7B LLM创建一个简单的Python程序&#xff0c;可以从任何pdf文件中回答问题。 一、LangChain简介 LangChain是一个在语言模型之上开发上下文感知应用程序的框架。LangChain使用带prompt和few-…

Transformer(seq2seq、self-attention)学习笔记

在self-attention 基础上记录一篇Transformer学习笔记 Transformer的网络结构EncoderDecoder 模型训练与评估 Transformer的网络结构 Transformer是一种seq2seq 模型。输入一个序列&#xff0c;经过encoder、decoder输出结果也是一个序列&#xff0c;输出序列的长度由模型决定…

基于MINIST的手写数字体识别

一、算法简述 网络结构设计 通过创建MnistNet类&#xff0c;定义了包含两个卷积层和两个全连接层的深度神经网络。这个网络的设计灵感来自于经典的CNN结构&#xff0c;其中卷积层用于提取图像特征&#xff0c;而全连接层则用于将这些特征映射到最终的类别。 卷积与池化 卷…

在 Golang 应用程序中管理多个数据库

掌握在 Golang 项目中处理多个数据库的艺术 在当前软件开发领域中&#xff0c;处理单个应用程序内的多个数据库的需求越来越普遍。具有强大功能的 Golang 是处理此类任务的绝佳解决方案&#xff0c;无论您是与多个数据源合作还是仅为增强组织和可扩展性而分隔数据。在本文中&a…

网络安全应急响应工具之-流量安全取证NetworkMiner

在前面的一些文章中&#xff0c;用了很多的章节介绍流量分析和捕获工具wireshark。Wireshark是一款通用的网络协议分析工具&#xff0c;非常强大&#xff0c;关于wireshark的更多介绍&#xff0c;请关注专栏&#xff0c;wireshark从入门到精通。本文将介绍一个专注于网络流量取…

JavaEE - 网络编程之回显服务器

目录 一.什么是回显服务器&#xff1f; 二.UDP是什么&#xff1f; 1.TCP 是有链接的&#xff0c; UDP 是无连接的 2.TCP是可靠传输的,UDP是不可靠传输的 3.TCP是面向字节流的&#xff0c;UDP是面向数据报 4.TCP和UDP是全双工的 三.UDP的 socket api 四. 具体代码实现 …

NModbus-一个C#的Modbus协议库实现

NModbus-一个基于C#实现的Modbus通信协议库 最近在学习C#的时候&#xff0c;因为之前做过环保设备时使用C做过环保设备采集使用到了Modbus协议&#xff0c;当时看了一下基于C语言开发的libmodbus库。所以特意搜索看了一下C#下有什么Modbus协议库&#xff0c;在Github上面找了一…

Spring Boot学习随笔- 集成MyBatis-Plus,第一个MP程序(环境搭建、@TableName、@TableId、@TableField示例)

学习视频&#xff1a;【编程不良人】Mybatis-Plus整合SpringBoot实战教程,提高的你开发效率,后端人员必备! 引言 MyBatis-Plus是一个基于MyBatis的增强工具&#xff0c;旨在简化开发&#xff0c;提高效率。它扩展了MyBatis的功能&#xff0c;提供了许多实用的特性&#xff0c;…

数据缓存(Redis, Spring Cache)——后端

场景&#xff1a;给用户端展示的数据都是通过查询数据库所得&#xff0c;因此数据库访问压力会随着用户访问量增大而增加&#xff0c;从而导致系统响应慢、用户体验差。 方法&#xff1a;通过Redis缓存数据&#xff0c;减少查询数据库操作。&#xff08;Redis的数据是存储在内存…

vue中常见的指令

简单介绍一下常见的vue中用到的指令 v-on 指定当前的事件&#xff0c;语法糖为&#xff0c;如例子所示&#xff0c;指定按钮的事件为addCounter&#xff0c;点击会使变量counter 1 <!DOCTYPE html> <html><head><meta charset"utf-8" />…

【教学类-43-02】20231226 九宫格数独2.0(n=9)(ChatGPT AI对话大师生成 回溯算法)

作品展示&#xff1a; 背景需求&#xff1a; 大4班20号说&#xff1a;我不会做这种&#xff08;九宫格&#xff09;&#xff0c;我做的是小格子的&#xff0c; 他把手工纸翻过来&#xff0c;在反面自己画了矩阵格子。向我展示&#xff1a; “我会做这种&#xff01;” 原来他…

Android MVP 写法

前言 Model&#xff1a;负责数据逻辑 View&#xff1a;负责视图逻辑 Presenter&#xff1a;负责业务逻辑 持有关系&#xff1a; 1、View 持有 Presenter 2、Model 持有 Presenter 3、Presenter 持有 View 4、Presenter 持有 Model 辅助工具&#xff1a;ViewBinding 执行…
最新文章