LoginSignup
4
4
お題は不問!Qiita Engineer Festa 2023で記事投稿!

ChatGPT Code Interpreterでコードを一切書かずにテレビゲームの売上分析をしてみた

Last updated at Posted at 2023-07-14

はじめに

(注)2023年8月に「Code Interpreter」は「Advanced Data Analytics」に名称変更されました

2023年7月10日。ChatGPT Plusユーザー向けに、Code Interpreterプラグインの利用が開放されました。
このプラグインは任意のファイルをアップロードして、そのファイルに対してPythonのコードを実行することができます。
例えば、CSVファイルやExcelファイルを元にグラフを作成するなど、日本語で指示するだけでそれなりのものが出来上がります。凄すぎです。

数年前、東大の松尾研究室が主催しているデータサイエンティスト育成講座というものに参加しました。
そのときはPandas、Numpy、MatplotlibなどPythonのライブラリを使ってデータを可視化したり、回帰モデル・分類モデルを作成したりしました。

詳しくは別記事にしているので興味があれば参照ください。

今回は当時やったことをコードを一切書かずに、ChatGPTに日本語で指示するだけで実施してみます。

ChatGPT Code Interpreterを使う

データセット自体は Kaggle にからCSVファイルをダウンロードして利用します。
このデータセットは、 1980年から2016年に全世界で発売されたテレビゲーム16,598タイトルが売上順 に並んでいます。

まずCSVファイルをアップロードして、これが何のデータセットなのかを聞いてみます。

1.jpg

雑に聞いただけでどんなカラムがあるかを答えてくれました。
ちなみにこのときChatGPTではコードが実行されており、show workのところをクリックすると中身が確認できます。

  • 実行コード
import pandas as pd

# Load the data
data = pd.read_csv('/mnt/data/vgsales.csv')

# Display the first few rows of the data
data.head()
  • 結果
   Rank                      Name Platform    Year         Genre Publisher  \
0     1                Wii Sports      Wii  2006.0        Sports  Nintendo   
1     2         Super Mario Bros.      NES  1985.0      Platform  Nintendo   
2     3            Mario Kart Wii      Wii  2008.0        Racing  Nintendo   
3     4         Wii Sports Resort      Wii  2009.0        Sports  Nintendo   
4     5  Pokemon Red/Pokemon Blue       GB  1996.0  Role-Playing  Nintendo   

   NA_Sales  EU_Sales  JP_Sales  Other_Sales  Global_Sales  
0     41.49     29.02      3.77         8.46         82.74  
1     29.08      3.58      6.81         0.77         40.24  
2     15.85     12.88      3.79         3.31         35.82  
3     15.75     11.01      3.28         2.96         33.00  
4     11.27      8.89     10.22         1.00         31.37  

グラフ化してみる

まずは世界の売上TOP20をグラフ化してみます。

3.jpg

グラフ化だけでなく、結果をみて売上の傾向などの見解までつけてくれます。
グラフ化のコードを確認すると、どう書けばよいかの勉強にもなりますね

# Get the top 20 games by global sales
top_20_games = data.sort_values(by='Global_Sales', ascending=False).head(20)

# Set the figure size
plt.figure(figsize=(10, 10))

# Create the bar plot
plt.barh(top_20_games['Name'], top_20_games['Global_Sales'], color='skyblue')

# Invert the y-axis so that the game with the highest sales is on top
plt.gca().invert_yaxis()

# Set the title and labels
plt.title('Top 20 Video Games by Global Sales')
plt.xlabel('Global Sales (in millions)')
plt.ylabel('Game')

# Display the plot
plt.show()

ここで、出力されたグラフをみて気づいたのは、

  • どのハードで発売されたソフトか区別できない
  • GTA5(Grand Theft Auto V)って複数ハードで出てなかったっけ?

といった点です。
そこでもう少し深掘りしたグラフを書いてみます。

4.jpg

きれいなグラフが作れました。
そして、ハード合算するとGTA5が第2位になることがわかりました。

# Group the data by game name, sum the sales, and sort by global sales
grouped_data = data.groupby('Name').sum().sort_values(by='Global_Sales', ascending=False).head(20)

# Create a new dataframe with platforms as columns and fill NaN with 0
platform_data = data.pivot_table(index='Name', columns='Platform', values='Global_Sales', fill_value=0)

# Keep only the top 20 games in platform_data
platform_data = platform_data.loc[grouped_data.index]

# Create the stacked bar plot
plt.figure(figsize=(10, 10))
platform_data.plot(kind='barh', stacked=True, colormap='tab20', figsize=(10, 10))

# Invert the y-axis so that the game with the highest sales is on top
plt.gca().invert_yaxis()

# Set the title and labels
plt.title('Top 20 Video Games by Global Sales (Stacked by Platform)')
plt.xlabel('Global Sales (in millions)')
plt.ylabel('Game')

# Display the plot
plt.show()

回帰モデルを作成する

今度は、海外販売本数、メーカー、ジャンルなどの説明変数から、「日本における販売本数」を予測するモデルを作成します。

以前に自力でモデル作成した際は、データセットをOne-hotエンコーディングして、説明変数の中で相関高いものに絞って、テスト分割サイズをいじって、モデル作成に決定木・リッジ回帰・重回帰使って、などなどいろいろやりました。
が、今回は難しいことは何も考えずChatGPT Code Interpreterに任せます。

11.jpg

# Preprocessing

# Check for missing values
missing_values = data.isnull().sum()

missing_values

12.jpg

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import OneHotEncoder
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.metrics import mean_squared_error, r2_score

# Drop rows with missing 'Year' values
data = data.dropna(subset=['Year'])

# Define features and target
features = ['Year', 'NA_Sales', 'EU_Sales', 'Other_Sales', 'Genre', 'Platform']
target = ['JP_Sales']

# Separate features and target
X = data[features]
y = data[target]

# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Define numerical and categorical features
num_features = ['Year', 'NA_Sales', 'EU_Sales', 'Other_Sales']
cat_features = ['Genre', 'Platform']

# Create transformers for numerical and categorical features
num_transformer = SimpleImputer(strategy='median')
cat_transformer = Pipeline(steps=[
    ('imputer', SimpleImputer(strategy='constant', fill_value='missing')),
    ('onehot', OneHotEncoder(handle_unknown='ignore'))])

# Combine transformers
preprocessor = ColumnTransformer(
    transformers=[
        ('num', num_transformer, num_features),
        ('cat', cat_transformer, cat_features)])

# Create a pipeline with preprocessing and model training steps
model = Pipeline(steps=[
    ('preprocessor', preprocessor),
    ('regressor', LinearRegression())])

# Train the model
model.fit(X_train, y_train)

# Make predictions on the testing set
y_pred = model.predict(X_test)

# Calculate the root mean squared error (RMSE)
rmse = mean_squared_error(y_test, y_pred, squared=False)

# Calculate the coefficient of determination (R^2)
r2 = r2_score(y_test, y_pred)

rmse, r2

13.jpg

精度を上げるにはもう少し前処理で工夫しないといけなさそうですが、とりあえず回帰モデルを作成することはできました。
どういうアプローチをすればアイディアもくれますし、具体的なコードも示してくれるのでかなり有用です。

さいごに

ちょっとCode Interpreterを触ってみたら、あまりに凄すぎて久々にQiita記事を書きたくなってしまいました。
扱えるデータはCSVやExcelファイルに限らず、画像・音声・動画なんかも扱えるようなので、他にもいろいろと活用できるシーンを考えてみたいと思います。

参考

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4