<jupyter_start><jupyter_text><jupyter_code>!pip install optuna gspread pandas
# Google スプレッドシートの承認

from google.colab import auth
from oauth2client.client import GoogleCredentials
import gspread

auth.authenticate_user()
gc = gspread.authorize(GoogleCredentials.get_application_default())
# スプレッドシートからデータを取ってくる
import pandas as pd

ss_name = "shu65コーヒーデータ"
workbook = gc.open(ss_name)
worksheet = workbook.get_worksheet(1)
df = pd.DataFrame(worksheet.get_all_records())
df = df.set_index('淹れた日')
df

# 探索空間の定義

import optuna

search_space={
    "豆の量(g)": optuna.distributions.IntUniformDistribution(8, 12),
    "ミルの時間 (sec)": optuna.distributions.IntUniformDistribution(3, 15),
    "トータルの時間 (sec)": optuna.distributions.IntUniformDistribution(180, 300),
    "蒸らし時間 (sec)": optuna.distributions.IntUniformDistribution(20, 40),
    }
score_column = 'スコア'
# 現在までのデータをstudyに登録

import optuna

sampler = optuna.samplers.TPESampler(multivariate=True)
study = optuna.create_study(direction='maximize', sampler=sampler)

for record_i, record in df.iterrows():
  print(record.to_dict())
  params = {}
  for key in search_space.keys():
    params[key] = record[key]
  trial = optuna.trial.create_trial(
    params=params,
    distributions=search_space,
    value=record[score_column])
  study.add_trial(trial)
# 次のパラメータの出力
trial = study._ask()

new_params = {}
for key, space in search_space.items():
  new_params[key] = trial._suggest(key, space)

for key in  ["豆の量(g)", "ミルの時間 (sec)",  "トータルの時間 (sec)",  "蒸らし時間 (sec)"]:
  print(key, new_params[key])<jupyter_output>豆の量(g) 9
ミルの時間 (sec) 13
トータルの時間 (sec) 199
蒸らし時間 (sec) 33
{'fraction_non_alphanumeric': 0.12379807692307693, 'fraction_numerical': 0.016826923076923076, 'mean_word_length': 4.842105263157895, 'pattern_counts': {'":': 4, '<': 4, '<?xml version=': 0, '>': 4, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '496347', 'license': 'BSD-2-Clause', 'n_tokens_mistral': 747, 'n_tokens_neox': 694, 'n_words': 118, 'path': 'coffee_tuning_blog用.ipynb', 'repo_name': 'shu65/coffee-tuning', 'size': '1664'}