My Little World

一些实操的步骤

文生视频

  1. 找到相似图片,通过文心一言生成图片提示词
  2. 将提示词替换下面代码, 在jupyter notebook中运行可以得到5张图片
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import json
import os
import dashscope
from dashscope import MultiModalConversation

# 以下为北京地域url,若使用新加坡地域的模型,需将url替换为:https://dashscope-intl.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope.aliyuncs.com/api/v1'

messages = [
{
"role": "user",
"content": [
{"text": "一张充满秋日氛围的摄影图,画面中心是一片金黄的枫叶,叶脉清晰、边缘略带枯黄斑点,阳光从画面右侧洒下,形成耀眼的光斑与柔和的光线;背景是暖色调的树木(树叶呈橙红渐变),远处有朦胧的建筑轮廓;整体风格自然写实,光线明亮且带暖调,营造出宁静又诗意的秋日氛围,细节上突出枫叶的质感与光影层次。"}
]
}
]

# 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx"
# 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
api_key = "xxxxx"
for i in range(0,5):
response = MultiModalConversation.call(
api_key=api_key,
model="qwen-image-plus",
messages=messages,
result_format='message',
stream=False,
watermark=True,
prompt_extend=True,
negative_prompt='',
size='1328*1328'
)

if response.status_code == 200:
print(json.dumps(response, ensure_ascii=False))
import requests
url = json.dumps(response, ensure_ascii=False)
reponse = requests.get(url=response.output.choices[0].message.content[0]['image'])
with open('./ad50000'+str(i)+'.png','wb') as f:
f.write(reponse.content)
else:
print(f"HTTP返回码:{response.status_code}")
print(f"错误码:{response.code}")
print(f"错误信息:{response.message}")
print("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code")
  1. 将图片上传到度加-视频生成,生成依据图片生成的视频

商品评论分析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# Python3.8以上
pip install pydantic==2.5.3 -i https://mirrors.aliyun.com/pypi/simple/
pip install langchain-core==0.1.45 -i https://mirrors.aliyun.com/pypi/simple/
pip install langchain==0.1.16 -i https://mirrors.aliyun.com/pypi/simple/
pip install dashscope==1.24.7 -i https://mirrors.aliyun.com/pypi/simple/

#导入库
import os
import pandas as pd
from typing import List, Optional
from langchain_core.pydantic_v1 import BaseModel, Field
from langchain_core.utils.function_calling import convert_to_openai_tool
from dashscope import Generation
import dashscope
from langchain.tools.render import render_text_description
import warnings
warnings.filterwarnings('ignore')

# 1.初始化大模型环境

# 使用大模型类型
os.environ["DASHSCOPE_API_KEY"] = "https://dashscope.aliyuncs.com/compatible-mode/v1"

dashscope.api_key = "xxx" // 阿里云百炼 https://bailian.console.aliyun.com/?tab=model#/api-key

from typing import Optional

from langchain_core.pydantic_v1 import BaseModel, Field


class Person(BaseModel):
"""Information about a person."""
name: Optional[str] = Field(default=None, description="The name of the person")
hair_color: Optional[str] = Field(default=None, description="The color of the peron's hair if known")
height_in_meters: Optional[str] = Field(default=None, description="Height measured in meters")

2.读取数据

df=pd.read_excel(r"./原始数据.xlsx")

df.head(2)
df[df["Rating"]<2].groupby("Clothing_ID").size().sort_values().tail(10) # 评分低于2的最多的10条数据

3.筛选数据
re_862=df[(df["Rating"]<2)&(df["Clothing_ID"]==862)].Review_Text.dropna(axis=0,how=any).tolist() // 去掉Review_Text 缺省的数据

4.大模型处理

# 定义问题类别
class clothing(BaseModel):
Fabric_problems: Optional[str] = Field(default=None, description="Fabric problems: noticeable holes, loose threads, pilling, or abnormal color fading and shrinkage")
Workmanship_defects: Optional[str] = Field(default=None, description="Workmanship defects: poor stitching, excessive loose threads, easily detachable buttons, etc")
Size_discrepancies : Optional[str] = Field(default=None, description="Size discrepancies: the actual product size differs from the described dimensions, leading to ill-fitting garments.")
Uncomfortable_wear : Optional[str] = Field(default=None, description="non-breathable fabrics, irritation against the skin, or discomfort during wear.")
Fit_design: Optional[str] = Field(default=None, description="Fit and design: unsuitable cut, not conforming to ergonomics, or unflattering when worn")
Appearance_Discrepancies: Optional[str] = Field(default=None, description="Mismatch between the product received and online images in terms of style or color.")
After_Sales: Optional[str] = Field(default=None, description="Unsatisfactory customer service attitude or response efficiency.")
Value_Money: Optional[str] = Field(default=None, description="Consumers feel that the price does not align with the actual quality or value of the product, perceiving it as overpriced.")

class Data_yun(BaseModel):
"""提取负面信息"""
comment: List[clothing]

# 封装请求数据
def prompt_yun(ct):
system_prompt="您是提取算法专家。仅从文本中提取相关信息。如果您不知道要求提取的属性值,则为属性值返回 null。首先抽取出用户评价中的抱怨点,然后对这些点进行分类,然后调用工具输出"
prompt=[{"content":system_prompt,"role":"system"},\
{"role":"user","content":"The material is cheap"},\
{'role': 'assistant', 'content': '', 'tool_calls_ids': [{'function': {'name': 'Data_yun', 'arguments':
'{"comment": [{"Fabric_problems": "The material is cheap","Size_discrepancies": "is made for women with long torso and shorter shoulders"}]}'}}]}]
prompt.append({"role":"user","content":ct})
return prompt

# 向大模型提问
def get_response_1t(mess):
response = Generation.call(
model='qwen-plus',
messages=mess,
tools=[convert_to_openai_tool(Data_yun)],
result_format='message', # 将输出设置为message形式
)
return response

5.处理单个评论,进行模型能力测试

text = re_862[1]
p_y = prompt_yun(text)
res = get_response_1t(p_y)

res.output.choices[0].message["tool_calls"][0]['function']['arguments']


6.循环处理所有数据

import time
import numpy as np
for i in re_862:
time.sleep(0)
text = i
if text is np.nan:
print("数据为空值")
else:
p_y=prompt_yun(text)
res=get_response_1t(p_y)
print(res.output.choices[0].message["tool_calls"][0]['function']['arguments'])
print('-'*20)

推荐算法1

算法(模型): 建模就是在使用某个算法。

关联算法: 可以实现商品的推荐。

电商: 购买了手机就推荐手机壳。

美团(小象超市): 土豆、黄瓜、鸡蛋、面包、椰子水。—>你历史的购物数据进行关联分析来推荐。

关联算法的阈值:

项集: 每个事物就是一个项集。(土豆、黄瓜、鸡蛋、面包、椰子水)

支持度: 满足最小支持度阈值时就认为数据(项集)之间存在关联规则。可以是多项集之间存在关联规则。0.2 3/5=0.6 牛奶和面包出现的次数/总记录数

001:(牛奶、面包、啤酒、鸡蛋)
002:(方便面、面包、火腿肠)
003:(牛奶、面包、火腿肠)
004:(牛奶、面包、啤酒)
005:(矿泉水、面包、啤酒)

手机和手机壳之间有关联系,还是手机壳和手机之间有关联系呢

置信度: 确定事物之间的关联关系的。0.8
面包和牛奶之间的置信度: 面包和牛奶同时出现的次数/面包出现的次数, 3/5=0.6
牛奶和面包之间的置信度: 牛奶和面包同时出现的次数/牛奶出现的次数 3/3=1

apriori算法
如果事物不满足频繁一项集那么也就一定不满足频繁二项集,以此类推

牛奶、面包、啤酒、鸡蛋、火腿肠、矿泉水、方便面

牛奶: 0.6 面包: 1 啤酒: 0.6 鸡蛋0.2 火腿肠: 0.4 矿泉水: 0.2 方便面: 0.2

牛奶: 面包: 0.6 牛奶: 啤酒: 0.4 牛奶: 鸡蛋: 0.2 面包: 啤酒: 0.6 面包: 鸡蛋: 0.2 啤酒: 鸡蛋: 0.2

fp-tree: 将事物的关联规则加载成一个树形结构

面包: 5

牛奶: 3 啤酒: 3 火腿肠: 1

火腿肠: 1


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import pandas as pd
import warnings
warnings.filterwarnings("ignore")

1.读取数据

df = pd.read_csv('./fruit_purchases1.csv',sep=';')
df.head()

2.数据预处理

df_mtix = df['购买水果'].map(lambda line:line.replace(' ','').split(','))
或者
list_all_f = []
for x in df['购买水果']:
list_all_f.append(x.split(','))

from mlxtend.preprocessing import TransactionEncoder

model_te = TransactionEncoder() # 设置参数
df_te = model_te.fit_transform(df_mtix) # 应用到数据上
df_te = pd.DataFrame(data=df_te,columns=model_te.columns_) # 转型

3.关联规则建模
from mlxtend.frequent_patterns import fpmax,fpgrowth,apriori // 不同的计算置信度的算法

model_apriori = apriori(df=df_te,min_support=0.2,use_colnames=True)
# model_fpmax = fpmax(df=df_te,min_support=0.1,use_colnames=True)
# model_fpgrowth = fpgrowth(df=df_te,min_support=0.1,use_colnames=True)

4.association_rules 函数来找出关联规则
from mlxtend.frequent_patterns import association_rules

rules = association_rules(df=model_apriori,metric='confidence',min_threshold=0.8)
rules

5. 推荐---当用户购买了某个水果后应推荐什么其他的水果

buyfruit = input('现已经买了什么水果')

lists = rules[rules['antecedents'] == {buyfruit}]['consequents'].values
print('用户购买了'+ buyfruit + '推荐', lists)

后续策略
去重
如果是一个任何关联都没有的水果,可以推荐support 最高的,购买次数最多的项集

推荐算法2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<!-- 想要向某个用户去推荐音乐:
计算处用户和哪些用户相似,在将和用户相似的用户听过的音乐,并且是用户没用听过的音乐,推荐给用户。
张三:李四、王五 音乐:1 2 3 4 5 6
李四:音乐:1 5 6 7 8
王五:音乐:2 4 7 9
向张三推荐:7 8 9
1.计算用户之间的相似度:
2.相似的用户听过的音乐;
3.相似用户听过的音乐哪些是用户没有听过的的;
4.推荐 -->

# 导入pandas和numpy库
import pandas as pd
import numpy as np
# 读取数据集
user_artists = pd.read_csv('./music/user_artists.dat', sep='\t') # 优用"t'分隔符读取user artists.dat文件
artists = pd.read_csv('./music/artists.dat', sep='\t', usecols=['id', 'name']) # 使用t分隔符读取artists.dat文件,仅读取id和name列
user_artists

# 去除不必要的列
# user_artists = user_artists.drop(['weight'], axis=1)# 删除user _artists中的weight列

artists.head()

artists['id'] =artists['id'].astype(np.int64)

6.将user_artists和artists两个DataFrame进行合并,以user_artists中的artistID和artists中的id为键值进行连接。
# 合并数据集
data = pd.merge(user_artists, artists, left_on='artistID', right_on='id') # 将user_artists 和 artists 合并
data = data.drop(['id', 'artistID'], axis=1) # 删除data 中的id 和artistID 列
data

7.去除评分次数少于50次的音乐和用户。
counts = data['userID'].value_counts() # 计算每个用户的评分次数
data = data[data['userID'].isin(counts[counts >= 50].index)] # 去除评分次数少于50 次的用户

counts = data['name'].value_counts() # 计算每个音乐的评分次数
data = data[data['name'].isin(counts[counts >= 50].index)] # 去除评分次数少于50 次的音乐

# 将音乐和用户ID 转换为数字
name_to_index = {} # 创建 name_to_index 字典
index_to_name = {} # 创建index_to_name 字典
for i, name in enumerate(data['name'].unique()): # 遍历 data 中的name 列
name_to_index[name] = i # 将name 映射到数字
index_to_name[i] = name # 将数字映射到name

user_id_to_index = {} # 创建user_id_to_index 字典
index_to_user_id = {} # 创建index_to_user_id 字典
for i, user_id in enumerate(data['userID'].unique()): # 遍历data 中的userID 列
user_id_to_index[user_id] = i # 将user_id 映射到数字
index_to_user_id[i] = user_id # 将数字映射到user_id
data['name_index'] = data['name'].apply(lambda x: name_to_index[x]) # 将data 中的 name 映射到数字
data['user_index'] = data['userID'].apply(lambda x: user_id_to_index[x]) # 将data 中的 user_id 映射到数字
# # 构建用户-音乐评分矩阵
n_users = len(user_id_to_index) # 获取用户数量
n_artists = len(name_to_index) # 获取音乐数量
ratings_matrix = np.zeros((n_users, n_artists)) # 创建用户-音乐评分矩阵
ratings_matrix

8.将data中的评分填入用户-音乐评分矩阵,使得ratingsmatrix的输出为。
for row in data.itertuples(): # 遍历data
ratings_matrix[row[5], row[4]] = row[2] # 将data 中的评分填入用户-音乐评分矩阵
print(row)
ratings_matrix
# print(row)
# 计算用户之间的相似度
from sklearn.metrics.pairwise import cosine_similarity # 导入sklearn 库中的余弦相似度计算函数
user_similarity = cosine_similarity(ratings_matrix) # 计算用户之间的相似度
# 为用户推荐音乐
user_index = 0 # 设置用户索引


9.获取与用户最相似的用户索引similar users(不包括自己),使得similar users的输出为:
similar_users = np.argsort(-user_similarity[user_index])[1:] # 获取与用户索引为0 的用户最相似的用户索引
similar_users
recommended_artists=[]# 创建推荐音乐列表

10.填补以下程序,获取相似用户评分的音乐索引artists_rated。

for i in similar_users: # 遍历相似用户索引
artists_rated = np.where(ratings_matrix[i] > 0)[0] # 获取相似用户评分的音乐索引
for j in artists_rated: # 遍历音乐索引
if ratings_matrix[user_index][j] == 0: #用户未评分
recommended_artists.append((j, ratings_matrix[i][j])) # 将音乐加入推荐音乐列表
recommended_artists = sorted(recommended_artists, key=lambda x: x[1], reverse=True)[:10] # 筛选出推荐音乐中的前10 首
for artist in recommended_artists: # 遍历推荐音乐
# print(artists[artists['name'] == index_to_name[artist[0]]]['name'].values[0]) # 打印推荐音乐
print(index_to_name.get(artist[0]))
# print(artist)

artists[artists['name'] == index_to_name[artist[0]]]['name'].values[0]

实验