跳至主要内容

面向数据科学项目的 Google Bard

学习如何利用 Google Bard 进行项目规划、数据预处理、探索性数据分析、特征工程、模型选择、超参数调优、模型验证,以及网页应用的构建与部署。
Abid Ali Awan
Abid Ali Awan

创建您的免费账户

实践并学习路径你的进步。

使用 Google 继续继续即表示您接受我们的 使用条款,我们的 隐私政策 ,并且您的数据存储在美国。

由 PaLM 2 模型驱动的最新版本 Bard,在推理、编码与多语言能力方面都有所提升。与 ChatGPT 不同,用户需要针对 Bard 调整输入,才能获得高质量的回答。

本文介绍如何利用新版 Bard 搭建端到端的数据科学项目。您将学习如何编写高效的提示词,为实验与开发生成创意与代码。

阅读我们的 《Bard 与 ChatGPT 在数据科学中的比较》一文,了解 Google Bard 与 ChatGPT 的详细对比;还可参考我们的通用文章 《ChatGPT vs Google Bard》,以及教程 《面向数据科学项目的 ChatGPT》,获取另一种方案。

项目规划

规划阶段是每个项目的关键步骤,它为成功奠定基础。在此阶段,我们会仔细分析可用资源与目标,并制定项目计划,明确达成目标所需的步骤。

要创建项目大纲,我们将为 Bard 编写一条包含所有相关信息的详细提示词,内容涵盖我们的假新闻检测应用的开发。它将包含关键细节,例如我们将使用的数据集,即来自 WELFake 论文的 Fake News Classification 数据集,以及指导团队在整个开发过程中的项目指令。

提示词:“请作为数据科学经理,制定一个端到端的假新闻检测项目计划。我们已经有 FakeNewsDetection 数据集,包含 72,134 行、4 列:[Unnamed: 0、title、text 和 ;abel(0 = 假,1 = 真)]。”

Image from Google Bard

虽然通用项目大纲提供了坚实的基础,但仍缺少一些关键步骤。我们可以通过撰写后续提示词来补充必要的步骤。

后续提示词:“请补充 EDA、模型选择、超参数优化、Streamlit 网页应用与 Streamlit Cloud 部署等步骤,并提供合并后的项目计划。”

Image from Google Bard

看起来 Bard 没有理解我们已经有数据集,因此不需要数据收集部分。您可以写一条后续提示词来删去多余部分。

后续提示词:“我们已经有数据,请从项目计划中移除数据收集步骤。”

以下是假新闻检测项目的大纲:

  1. 数据预处理
  2. 探索性数据分析(EDA)
  3. 特征提取
  4. 模型选择
  5. 超参数优化
  6. 模型训练与评估
  7. Streamlit 网页应用
  8. Streamlit Cloud 部署

项目计划详细解释了构建假新闻检测应用所涉及的每个步骤,并给出了可用于优化结果的推荐方法。此外,我们的计划还提供了按周安排的关键任务与里程碑。

如果您在编写提示词时感到吃力或不知所措,也无需担心。下载我们的提示词工程速查表,其中收录了 60 多条针对各类数据科学任务精心打造的提示词。

Bard 用于数据预处理

在这一步,我们将对数据集进行加载、清洗并开展特征工程。

数据加载

现在,您需要将角色从数据经理切换为数据科学家,编写用于加载数据的提示词。

提示词:“请以专业数据科学家的身份,编写 Python 代码,从上述数据集中随机加载五千条样本。”

注意:我们在下采样数据,以更快地训练与优化模型。

Image from Google Bard

import pandas as pd

# Load the dataset
df = pd.read_csv("fake-news-classification/WELFake_Dataset.csv")

# Get 5 thousand random samples
df = df.sample(n=5000, random_state=42)

# Print the first 5 rows of the data
df.head()

数据清洗

为确保我们的数据集得到妥善清洗并可用于分析,我们将向 Bard 提供关于所需数据清洗函数的具体指令。

提示词:“现在,请编写一个用于清洗数据集的 Python 函数。该函数应删除缺失值、删除 "Unnamed: 0" 列、清洗文本并移除停用词。”

为解决代码中的任何缺陷或错误,我们将请 Bard 处理停用词错误。它会理解问题并生成改进版代码。

更新提示词:“修复与停用词相关的错误”

import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords

def clean_dataset(df):

  # Drop missing values
  df = df.dropna()
    
  # Drop Unnamed column
  df = df.drop(["Unnamed: 0"], axis=1)

  # Clean text
  df['text'] = df['text'].str.lower()
  df["Text"] = df["Text"].str.replace("[^a-zA-Z]", " ")

  # Remove stopwords
  stopword = set(stopwords.words('english'))
  df['text'] = df['text'].apply(lambda x: ' '.join([word for word in x.split() if word not in stopword]))

  return df

df = clean_dataset(df)
df.head()

我们得到了一个相当干净的数据集。

image6.png

特征工程

为确保 Bard 生成最优代码,提供具体指令比提出笼统问题更重要。比如,如果我们要求 Bard 执行某个特定功能,如“合并两个文本列的长度”,它就能生成更契合项目需求的高质量代码。

提示词:“现在,请编写一个用于执行特征工程的 Python 函数。将 title 列转换为小写并合并 text 与 title,合并两个文本列的长度,统计唯一词数量,等等。”

def feature_engineering(df):

  # Lower the title column
  df['title'] = df['title'].str.lower()

  # Combine text and title
  df['combined'] = df['title'] + ' ' + df['text']

  # Length of the combined text
  df['combined_length'] = df['combined'].str.len()

  # Count unique words
  df['unique_words'] = df['text'].apply(lambda x: len(set(x.split())))

  return df

# Perform feature engineering
df = feature_engineering(df)

# Print the first few rows of the DataFrame with the new features
df.head()

我们创建了三个新特征,将用于数据分析。

image8.png

Bard 用于探索性数据分析(EDA)

在 EDA 部分,我们将请 Bard 创建对数据探索很重要的可视化图表。

提示词:“编写用于执行上述项目 EDA 的 Python 代码。包括用于比较合并文本长度的直方图(假 vs 真)、标签分布与词云。”

我们将再写一条后续提示词以添加分箱边界。

后续提示词:“使用 `np.linspace` 将 EDA 代码更新为创建从 0 到 200、宽度为 40 的分箱边界。”

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

bins = np.linspace(0, 200, 40)
# Histogram of the length of fake vs real news articles
plt.hist(df['combined_length'].where(df['label'] == 1),bins, alpha=0.5, label='Real')
plt.hist(df['combined_length'].where(df['label'] == 0),bins, alpha=0.5, label='Fake')
plt.xlabel('Combined Text Length')
plt.ylabel('Number of Articles')
plt.legend()
plt.show()

看起来假新闻的文本长度比真实新闻更长。

image4.png

# Label distribution
plt.pie(df['label'].value_counts(), labels=['Fake', 'Real'], autopct='%1.1f%%')
plt.show()

标签分布相当均衡,我们无需进行类别平衡处理。

image14.png

from wordcloud import WordCloud

wc = WordCloud(max_words=100, background_color='white')
wc.generate(' '.join(df[df['label'] == 0]['combined']))
plt.imshow(wc)
plt.axis('off')
plt.title('Word cloud of fake news articles')
plt.show()

image11.png

wc = WordCloud(max_words=100, background_color='white')
wc.generate(' '.join(df[df['label'] == 1]['combined']))
plt.imshow(wc)
plt.axis('off')
plt.title('Word cloud of real news articles')
plt.show()

image10.png

与假新闻相比,真实新闻中 “trump” 与 “said” 等词更为突出。

使用 Bard 进行特征提取

在本部分,我们将编写提示词,将“text”列转换为向量,并将数据集拆分为训练集与测试集。

提示词:“将文本列转换为向量,并将数据集拆分为训练集和测试集。”

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split

# Convert the text column into vectors
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(df['text'])

# Split the dataset into training and testing datasets
X_train, X_test, y_train, y_test = train_test_split(X, df['label'], test_size=0.25)

Bard 用于模型选择

在提供必要的背景信息后,您现在可以直接提出问题。

提示词:“执行模型选择。”

from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score

# Train the models
models = [LogisticRegression(), SVC(), DecisionTreeClassifier(), RandomForestClassifier()]
for model in models:
    model.fit(X_train, y_train)

# Evaluate the models
predictions = []
for model in models:
    predictions.append(model.predict(X_test))

# Calculate the accuracy of the models
accuracies = []
for predictions in predictions:
    accuracies.append(accuracy_score(y_test, predictions))

# Print the accuracy of the models
print("Accuracy of LogisticRegression:", accuracies[0])
print("Accuracy of SVC:", accuracies[1])
print("Accuracy of DecisionTreeClassifier:", accuracies[2])
print("Accuracy of RandomForestClassifier:", accuracies[3])
Accuracy of LogisticRegression: 0.9024979854955681
Accuracy of SVC: 0.91941982272361
Accuracy of DecisionTreeClassifier: 0.8767123287671232
Accuracy of RandomForestClassifier: 0.8863819500402901

基于我们的分析,所有测试的模型表现都相对不错。不过,支持向量分类器(SVC)在这些模型中取得了最高的准确率。

使用 Bard 进行超参数调优

我们请 Bard 编写超参数调优代码,并将最佳模型与向量对象保存,以便部署。

提示词:”编写用于 SVC 超参数优化的 Python 代码。同时使用 Joblib 保存最佳模型与向量化器。”

from sklearn.svm import SVC
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import accuracy_score,f1_score, classification_report, confusion_matrix

import joblib

# Create a RandomForestClassifier model
svm = SVC()

# Create the hyperparameter grid
param_grid = {'C': [1, 10, 100], 'gamma': [0.01, 0.1, 1]}

# Create the GridSearchCV object
grid = GridSearchCV(SVC(), param_grid, cv=5)


# Fit the GridSearchCV object to the training data
grid.fit(X_train, y_train)

# Print the best parameters
print(grid.best_params_)
{'C': 10, 'gamma': 0.1}
# Predict the labels of the testing data using the best model
y_pred = grid.predict(X_test)

# Calculate the accuracy of the best model
accuracy = accuracy_score(y_test, y_pred)

# Print the accuracy of the best model
print("Accuracy of the best model:", accuracy)

准确率略有提升。

Accuracy of the best model: 0.9298952457695407

保存的模型与向量器将用于推理。

# Save the best model
joblib.dump(grid.best_estimator_, 'best_model.pkl')
# Save the TfidfVectorizer
joblib.dump(vectorizer, 'tfidf_vectorizer.pkl')

Bard 用于模型评估

对于分类模型来说,仅有准确率还不够。我们还需要在 f1 分数、召回率、精确率以及混淆矩阵上进行测试。

提示词:”编写用于模型评估的 Python 代码。包括分类报告、混淆矩阵与 f1 分数。”

print(classification_report(y_test, y_pred))

从报告来看,我们的模型在测试数据集上表现较为稳定。

              precision    recall  f1-score   support

           0       0.94      0.92      0.93       620
           1       0.92      0.94      0.93       621

    accuracy                           0.93      1241
   macro avg       0.93      0.93      0.93      1241
weighted avg       0.93      0.93      0.93      1241
# Plot the confusion matrix
print(confusion_matrix(y_test, y_pred))
[[572  65]
 [ 37 567]]
# Calculate the F1 score
f1_score = f1_score(y_test, y_pred, average='weighted')

# Print the F1 score
print("F1 score:", f1_score)
F1 score: 0.9298892365447746

使用 Bard 构建 Streamlit 网页应用

在对结果满意之后,我们将开发一个应用:它会将输入文本转换为向量,传入模型,并展示结果。

在此之前,我们需要创建一个 GitHub 仓库。

Image from Github

克隆该仓库,并保存应用的所有关键组件。这一步不仅确保其安全保存,也便于对应用与模型进行有效的版本管理。

git clone https://github.com/kingabzpro/Fake-News-DataCamp-Project.git

编写一条通用提示词,用于开发一个判断新闻真假的应用。

提示词:“单独编写一个 Python 文件,使用 Streamlit 创建网页应用,用于预测新闻是否为(0 = 假或 1 = 真)。只需包含 Streamlit 应用部分。”

接下来,我们创建一个 app.py 文件,并将 Bard 生成的代码拷贝到此文件。完成后,您可以使用命令 streamlit run app.py 运行应用。

注意:请确保您已安装运行 Streamlit 应用所需的全部 Python 包。

看起来 Bard 未能正确加载向量化器。我们可以写一个后续提示词来修复这个问题。

后续提示词:“在应用文件中使用 joblib 加载向量化器与模型。”

应用运行不太正常,因此我们需要添加一个运行按钮来修复该问题。

后续提示词:“另外,添加一个用于运行推理的按钮。”

import streamlit as st
import joblib

# Load the vectorizer
vectorizer = joblib.load("tfidf_vectorizer.pkl")

# Load the model
model = joblib.load("best_model.pkl")

# Create a title
st.title("Predict Fake News")

# Input text
text = st.text_input("Enter the news article:")

# Button to run inference
if st.button("Predict"):

    # Convert the text to a vector
    vector = vectorizer.transform([text])

    # Predict the label
    label = model.predict(vector)[0]

    # Display the label
    if label == 0:
        st.write("The news article is fake.")
    else:
        st.write("The news article is real.")

我们已成功构建一个 Streamlit 应用,它接收文本输入,并对新闻文章的真实性给出预测。

Gif from Streamlit app - Fake News Classifier

使用 Bard 进行 Streamlit Cloud 部署

要将应用部署到云端,我们可以请 Bard 提供帮助。结果表明,我们只需将代码推送到 GitHub 仓库,并与 Streamlit 服务器连接即可。

提示词:“请帮我将应用部署到 Streamlit Community Cloud。”

1. 创建 requirements.txt 文件,添加所有必需的 Python 包,如 “scikit-learn”。

2. 使用 Git 添加文件、提交,并推送到远程服务器。确保已添加模型、向量器、app.py 与 requirements.txt。

Image from Repository Directory

3. 前往 share.streamlit.io,点击 “New app”,选择 GitHub 仓库,并填写应用所需的信息。

Image from Streamlit

就是这样。我们的应用已部署,并可在 Streamlit(fake-news-detector.streamlit.app) 公开访问。

Image from fake news detector app

总结

ChatGPT、Bard 与 Claude 等 AI 工具让我们在日常数据科学工作中如虎添翼。借助这些工具的能力,我们提升了效率与熟练度,能够更加从容地应对复杂的数据挑战。

本文探讨了新版 Bard 在开发完整端到端数据科学项目方面的强大能力。您也可以查看我们的指南 《在数据科学项目中使用 ChatGPT》,或学习一门系统的 ChatGPT 课程:《ChatGPT 入门》,了解编写提示词的最佳实践。

Abid Ali Awan

作者

Abid Ali Awan

作为一名持证的数据科学家,我热衷于利用前沿技术打造创新的机器学习应用。凭借在语音识别、数据分析与报告、MLOps、对话式人工智能以及自然语言处理方面的扎实背景,我不断打磨构建智能系统的能力,力求带来切实影响。除技术专长外,我也擅长沟通,能够将复杂概念提炼为清晰、简明的表述。因此,我成为数据科学领域备受关注的博主,与不断壮大的数据专业人士社区分享洞见与实践经验。目前,我专注于内容创作与编辑,借助大语言模型打造有力且吸引人的内容,帮助企业与个人更好地发挥数据价值。

主题