律速があると嬉しい

博士課程に在籍していたころは、ありとあらゆるものが研究活動の律速になっていた。作物の生育、圃場作業、自分の知識量や思考力、論文の読解力や執筆力、コーディング力など。ありとあらゆる律速によって、様々な工夫をして足りないものを補ったり、人を頼ったり、頑張って少しずつでも自分を高めていったりする機会が自然に生み出されていた。今振り返ると無駄だったように思えるものも多くあるが、有意義で味の濃い時間も多かった。そして、別の環境で、また違った味の濃い時間を過ごしている人たちがいて、その話を聞くことも日常の味の濃さを増してくれていた。

今はというと、自分の能力に関する律速が自分自身の能力の向上や性質に依ることなく取り除かれつつある。特に、Claude codeやCodexに代表されるAIエージェントは、あまりにも優秀な代理人過ぎて、元々、自分の成長や特性の発揮の機会だったものを奪ってしまっている。彼らは、会話を通して自己改良を続ける。こちらとしては、人間の成長をも代理してほしいとは思っていない。このような状況は、別に昨今の生成AIに限った話ではないと思う。かつて、電卓やパーソナルコンピュータ、インターネットが普及した際にも同様の感情を抱いた人々も多くいたはずだ。これらは、人間の計算能力や知識を代替する存在だったはずだ。

今のAIは人間の能力の一部の上位互換というよりも、ほぼ人間そのものの上位互換だ。かつての技術はあくまで人間が使う道具だった。今のAIは道具というよりパートナーに近い。パートナーの方が優秀であり、物事をよく分かっていて、よく働く場合、大抵の人はパートナーにどうしても頼り切りになってしまう。仮に自分が成長していないな、なんて思ったとしても、その気持ちを凌駕するほどに彼らは従順でよく働く。仕事をする上では、彼らに頼り切りになるのは自然だ。学生から大学の先生になった今、AIに頼ってしまうのは自然なことだと思う。優先順位が違う。学生の頃は学ぶことが1番だが、今は成果を出すことが1番だ。成果を出すためにAIの存在はありがたすぎる。実際にAIのお陰で成果が出ていると感じる。

と同時に、成果を出したい人の集団がいたとして、その集団の成果を出すスピードが一様に加速した時、その集団は意外と辛いのでは?と思った。今の学術界は既にそうなっている分野も多いと思う。先行研究を調べる、ドライな解析をする、論文を書く、英語に訳す、という人間の能力で律速されていた部分が実質的に取り除かれてしまっている。これによって、成果は沢山でた。しかし、相対的にみると、別に大した成果は出ていないような気がする。周りも大概そうだからだ。例えば、少し前までメタ解析をきっちりやった論文を読むと、おお、となっていたが、今はそのような論文が多すぎて特に何も感じなくなりつつある。そして、各々の成果の味が薄くなった。誰しもが同じ「代理人」に頼れば、当然、個々人の特徴は平均化される。各々に律速があった状況は、各々が独自性を発揮せざるを得ない状況だったのかもしれない。この論文のアイデア・着眼点、イイね、みたいなのが最近なかなかない。同じ苦労、あるいは達成感を味わった人にたまったま会って盛り上がる瞬間も減った気がする。

そんなようなことを踏まえると、これからは、自ら律速を作り出す、ということが極めて重要な気がする。それもそれが自然にあるような状況だったり、それがあってならではの状況を作り出すのが良い気がする。自分だけでできることもたくさんありそう。例えば、海外の研究機関に行って人と話す。もう英語のメールなんぞはAIが書いてくれるし、オンライン会議では自動でスクリプトを付けてくれるソフトもあるが、まだ直接人と対面で会話中に同時通訳をしてくれるアプリはそこまで多くない。英語を話している時は日本語を話している時と脳の動きが全く違う。緊張感がある。これを感じられるだけで嬉しい。あとは、文字を書く。自らの手でペンを持って書く文章は、ひとたび紙にのってしまっては消せない。後戻りできない。これまた、しっかり考えて書かねばならないという緊張感がある。そして、その筆跡は自分独自のものだ。手紙にすれば、渡す相手にそれならではの温かみと気持ちが伝わる。やっぱりもらうと嬉しい。自分のホームページのタイトルの文字は友人にお願いして気合を入れて書いてもらったものだ。味があってなんかとてもいい。

今後、フィジカルAIも急速に普及するはずだ。律速の嬉しさを忘れてしまう前に、自ら律速を生み出せるようにしたい。それも、ただデジタル断ちをするとかではなく、今の時代に合っていて、何かしら意味のある良い感じの律速がいい。そして、その味わい深さを忘れないようにしたい。

Vibe Coding Your Way to Python Data Analysis: Build a Reproducible Research Environment with Google Drive × Google Colab × LLM

Introduction

Hey there, it's Guchyos.

Lately, when doing data analysis for research, I've been using a technique called "vibe coding." Vibe coding is an approach where you write code while having a dialogue with an LLM (Large Language Model). "Vibe" refers to the mood or feel of the process — you tell the LLM what you want to do and have it write the code for you. Even if you're a programming beginner, you can consult with an LLM as you work through your analysis, which significantly lowers the barrier to entry.

In this post, I'll explain how to do vibe coding in Python using Google Colab and an LLM. The method I'll introduce stores all your data, code, and results in Google Drive, which has the added benefit of making your work easy to reproduce.

What is Google Colab?

Google Colaboratory (Google Colab) is a free, cloud-based Python execution environment provided by Google. It runs entirely in your browser and has the following features:

  • No environment setup required: Python and libraries are already installed
  • Free GPU/TPU access: Capable of heavy computation like machine learning
  • Google Drive integration: Save data and code to the cloud
  • Collaborative editing: Multiple people can edit simultaneously, like Google Docs
  • Jupyter Notebook format: Code, execution results, and explanations are all bundled in one file

The biggest advantage is that you can start Python programming immediately with just a browser, without installing anything on your computer.

What is an LLM (Large Language Model)?

An LLM (Large Language Model) is an artificial intelligence trained on enormous amounts of text data. It can converse naturally like a human, answer questions, write text, and generate program code.

Representative LLM services:

  • ChatGPT (OpenAI): The most well-known
  • Claude (Anthropic): Gives impressively accurate answers even to vaguely worded questions
  • Gemini (Google): Strong integration with Google services

These services are accessible via a web browser and allow you to interact in a chat format. Even without programming knowledge, if you ask "please write code to do this," the LLM will generate Python code for you.

Note: Code generated by LLMs is not always perfect. Errors can occur, but if you show the error message to the LLM, it will suggest fixes — working through this dialogue is the real joy of vibe coding.

What is Python?

Python is a programming language that appeared in 1991, known for its readable and writable syntax. Today it is used across a wide range of fields including data science, machine learning, web development, and automation scripting.

Features of Python:

  • Simple syntax: Natural, English-like notation that is beginner-friendly
  • Rich libraries: Extensive purpose-built libraries for statistics, machine learning, image processing, and more
  • Large community: Plenty of information available, so you can quickly find solutions when stuck
  • Open source: Free to use

In research, it has become one of the mainstream languages for data analysis alongside R.

What is Google Drive?

Google Drive is a cloud storage service provided by Google that lets you store, share, and edit files online. It can be accessed from any device — computer or smartphone — and is widely used in research and business settings.

Features of Google Drive:

  • 15 GB free storage: Ready to use immediately with a Google account
  • Real-time collaborative editing: Multiple people can simultaneously edit documents and spreadsheets
  • Powerful search: Can even recognize and search text within images
  • Automatic sync: Access the latest files from all your devices
  • Flexible sharing settings: Finely adjust permissions such as view-only, comment, or edit

In research, it has become an indispensable tool for sharing data and presentation materials, and for collaborative writing.

Why Vibe Coding × Google Drive?

There are probably quite a few people who want to try programming but feel the first step is too high a hurdle.

  • "I don't understand Python syntax"
  • "I don't know what error messages mean"
  • "I have no idea how to write the code"
  • "I know the statistical method, but I don't know how to implement it"

With vibe coding, you can analyze data even as a programming beginner by writing code in dialogue with an LLM. Tell it what you want in your native language, and the LLM will write the code. If an error occurs, consult the LLM and it will teach you the solution.

Furthermore, with the method introduced here, everything is centralized in Google Drive, which brings these benefits:

  • Data, code, and analysis results are managed in one place
  • That means everything related to the analysis is recorded together
  • So it's easy to share with collaborators, supervisors, and lab members
  • Reproducibility is also easy to ensure

How to Do It!

Basic Flow

In the vibe coding I'll explain here, you go back and forth between dialogue with the LLM and code execution in Google Colab.

Basic cycle:

  1. Ask the LLM to "please write code to do this"
  2. Copy the code generated by the LLM
  3. Paste it into Google Colab and run it
  4. Check the results (if it works, move on; if there's an error, report it to the LLM)

Repeat this cycle to advance your analysis.

Preparation: Organizing Your Data and Setting Up Folders and Files in Google Drive

1. Create the Ultimate Excel Sheet

First, consolidate all the data needed for analysis into a single Excel sheet (or CSV file). "Ultimate" means the information needed for analysis is complete and well-organized. Each row must be uniquely identified by a combination of values across multiple columns.

For example, for rice yield data:

Year | Variety | Treatment | Replicate | Yield (kg/10a) | Plant Height (cm)
-----|---------|-----------|-----------|----------------|------------------
2024 | A       | 0N        | 1         | 520            | 85
2024 | A       | 0N        | 2         | 535            | 87
2024 | A       | 6N        | 1         | 580            | 92
2024 | B       | 3N        | 1         | 498            | 78
...

In this example, each row is uniquely determined by the combination of "Year," "Variety," "Treatment," and "Replicate." With this structure, each measurement value is clearly linked to its condition, so you won't run into trouble during analysis.

If your data is spread across multiple sheets (e.g., a variety info sheet and a measurement data sheet), consolidating them into one is easier in the long run.

2. Create a Folder Structure in Google Drive

Go to Google Drive (https://drive.google.com/). Log in with your Gmail account. This way, your files will be saved linked to your account. Now, let's create a folder structure like this:

Example folder structure:

📁 Research Project Name/
  📁 data/          ← Store data files here
  📁 code/          ← Save Google Colab notebooks here
  📁 results/       ← Save figures and tables of analysis results here

Specific steps:

  1. Open Google Drive
  2. Click the "New" button in the upper left → "New folder" to create a folder named "Research Project Name"
  3. Inside that folder, create three folders: "data," "code," and "results"
  4. Upload the Excel file you created to the "data" folder

3. Create a Google Colab Notebook

You can create a Google Colab notebook directly from Google Drive.

Method 1: Create from Google Drive (Recommended)

  1. Open the "code" folder in Google Drive
  2. Click "New" → "More" → "Google Colaboratory"
  3. Once the notebook opens, rename the file to something like "analysis_notebook"

If "Google Colaboratory" is not displayed, search for "Colaboratory" under "Connect more apps" and install it.

Method 2: Create directly from Google Colab

  1. Go to https://colab.research.google.com/
  2. "File" → "New notebook"
  3. After creating it, go to "File" → "Save a copy in Drive" and specify the "code" folder as the save destination

Reference links:

Practice: Advancing the Analysis in Dialogue with the LLM

This is the heart of vibe coding. Let's go back and forth between the LLM and Google Colab to do our coding and analysis.

Step 1: Ask the LLM for the First Code (LLM side)

First, open your LLM (ChatGPT, Claude, Gemini, etc.) and ask it something like this.

At this point, if you're worried about data leakage, use the temporary chat feature!

💬 Example prompt to LLM:

Please write Python code for Google Colab that mounts Google Drive and
reads an Excel file at the following path:
/content/drive/MyDrive/Research Project Name/data/analysis_data.xlsx

The LLM should generate code something like this:

from google.colab import drive
import pandas as pd

# Mount Google Drive
drive.mount('/content/drive')

# Read the Excel file
df = pd.read_excel('/content/drive/MyDrive/Research Project Name/data/analysis_data.xlsx')

# Check the data
print(df.head())

Step 2: Run the Generated Code in Google Colab (Colab side)

Basic Google Colab operations:

  • Add a code cell (the rectangular box where you write code): click the "+ Code" button at the top of the notebook (red circle in the figure)
  • Run code: click the play button (▶) on the left side of the cell, or press "Shift + Enter"
  • Delete a cell: click the trash can icon in the upper right of the cell (blue circle in the figure)

  1. Copy the code generated by the LLM
  2. Paste it into the Google Colab notebook
  3. Click the play button (▶) on the left side of the code cell to run it
  4. On the first run, you'll be asked for permission to access Google Drive — follow the instructions to grant access

Now you can access folders in your Google Drive, read Excel files from there, and save analysis results back to it.

Step 3: Output Basic Information about the Data (LLM → Colab)

Next, to get an overview of the data, ask the LLM to write code that outputs basic information.

💬 Example prompt to LLM:

Please write Python code that outputs the following basic information
about the Excel file I just loaded:

- Number of rows and columns
- List of column names
- Data type of each column
- Presence and count of missing values
- Basic statistics for numerical data (mean, standard deviation, min, max, etc.)
- First 5 rows of data

Workflow:

  1. 💬 Have the LLM generate the code
  2. 📋 Copy the code
  3. 🔬 Paste it into Google Colab and run it
  4. 👀 Check the output (it will appear below the code cell)

Step 4: Show the Basic Information to the LLM and Have It Write the Analysis Code (Colab → LLM → Colab)

Copy the basic information displayed below the code cell and show it to the LLM. This step is important.

At this point, if you're worried about data leakage, use the temporary chat feature!

💬 Example prompt to LLM:

I am working with the following data:

[Paste the basic information output from Google Colab here]

Using this data, I would like to perform the following analysis:

1. Calculate the mean yield for each variety
2. Conduct a t-test between varieties
3. Visualize the results with a box plot
4. Save the figure and t-test results to /content/drive/MyDrive/Research Project Name/results/

Please write the Python code.

This way, the LLM understands the data structure before generating the code. Note that you are only showing the LLM a summary of the data, so there is no risk of the LLM absorbing your raw data. You could send the raw data directly to the LLM, but it's not recommended from a data security standpoint.

Again, the workflow:

  1. 💬 Have the LLM generate the code
  2. 📋 Copy the code
  3. 🔬 Paste it into Google Colab and run it
  4. 👀 Check the results (if it worked, you're done; if there's an error, move to the next step)

Step 5: Report Errors to the LLM (Colab → LLM → Colab)

Errors are part of programming. Just copy the error message displayed in Google Colab and paste it to the LLM.

💬 Example prompt to LLM:

I got the following error. Please tell me the cause and how to fix it.

[Paste the error message from Google Colab here]

Example:
KeyError: 'variety'

The LLM will explain the cause — something like "the column name is 'Variety' not 'variety'" — and suggest a corrected version of the code.

Common errors and how to handle them:

  • ModuleNotFoundError: A required library is not installed

    • 💬 Ask the LLM "please tell me the code to install ○○"
    • 🔬 Run the generated code in Colab
  • KeyError: Incorrect column name specified

    • 💬 Show the LLM the basic info to confirm the correct column name
    • 🔬 Run the corrected code in Colab
  • ValueError: Data type mismatch

    • 💬 Ask the LLM "please give me code to convert the data type"
    • 🔬 Run the generated code in Colab

Error resolution cycle:

🔬 Colab: Error occurs
     ↓ Copy the error message
💬 LLM: Analyzes cause + generates corrected code
     ↓ Copy the corrected code
🔬 Colab: Run the corrected code
     ↓ Success! Or another error (if so, repeat)

Step 6: Understand What the Code Does (LLM side)

Rather than just using the generated code, it's also important to understand what it does. Ask the LLM to annotate it line by line in English.

💬 Example prompt to LLM:

Please add a comment to every line of the code you wrote earlier.
Explain in detail what each line does so that even a programming beginner can understand.

By doing this:

  • You'll understand how the code works
  • You can apply it the next time you do a similar analysis
  • The content of the Methods section in your paper will become clear

If you paste the annotated code into Google Colab, it will also be easy to understand when you revisit it later.

Notes and Recommendations!

Save Output Figures and Tables to Google Drive

Save analysis result figures and tables to Google Drive as well. You can also have the LLM write the code for this.

💬 Example prompt to LLM:

Please add code to save the created figure to
/content/drive/MyDrive/Research Project Name/results/
as "figure_yield_comparison.png" at high resolution (300 dpi).

This way, all figures and tables are also retained in your Google Drive folder.

Ensure Code Reproducibility (Python and Library Version Management)!

Even with the same code, behavior can change or errors can occur if the versions of Python or libraries (the things that appear as "import something" in the code) are different. To ensure reproducibility in research, it is important to record these versions. You can't change the Python version itself, but you should at least record the version in use when you ran the analysis.

How to Check Versions

💬 Example prompt to LLM:

Please write code to check the current versions of Python and
pandas, numpy, matplotlib, scipy, seaborn (the libraries included in my code)
in Google Colab.

You'll likely get a response like this:

To check the current environment in Google Colab, run the following code:

import sys
print(f"Python version: {sys.version}")

# Check major library versions
import pandas as pd
import numpy as np
import matplotlib
import scipy
import seaborn as sns

print(f"pandas: {pd.__version__}")
print(f"numpy: {np.__version__}")
print(f"matplotlib: {matplotlib.__version__}")
print(f"scipy: {scipy.__version__}")
print(f"seaborn: {sns.__version__}")

Run this in Google Colab to display the versions of Python and the libraries.

How to Record Versions

You can add a text cell and leave notes in it, as shown below. Note that in text cells, code cannot be executed. They are for notes only.

Add a text cell at the very beginning of your Google Colab notebook and paste in the output from the code above.

# Environment information (execution date: 2024-01-15)
# Python 3.10.12
# pandas==2.0.3
# numpy==1.25.2
# matplotlib==3.7.1
# scipy==1.11.4
# seaborn==0.12.2

This records the Python and library versions used for the analysis.

How to Pin Library Versions

If you want to install the listed library versions, run the following code at the beginning of your notebook:

!pip install pandas==2.0.3 numpy==1.25.2 matplotlib==3.7.1 (list library==version for each)

From this point on, libraries imported in subsequent code will be the versions specified here.

If you want to manage all libraries at once, you can save and load a list of libraries as a text file. Try asking the LLM like this:

💬 Example prompt to LLM:

Please write code to save the versions of all currently installed libraries
in Google Colab as a requirements.txt file to Google Drive.
Save it to /content/drive/MyDrive/Research Project Name/code/

You should get code like this:

# Export all libraries in the current environment
!pip freeze > /content/drive/MyDrive/Research Project Name/code/requirements.txt

Running this in Google Colab will save a requirements.txt file containing the list of libraries to your Google Drive folder.

To reproduce the same environment later, just run the following at the very beginning of the notebook:

# Install all at once from requirements.txt
!pip install -r /content/drive/MyDrive/Research Project Name/code/requirements.txt

If You're Worried About Data Leakage, Use the Temporary Chat Feature!

Even if you're not directly uploading data to the LLM, you might be concerned about discussing unpublished data with an LLM. Most LLM services have a "temporary chat" or "incognito mode," and using this means your input data won't be used for model training, so you can feel at ease.

Temporary chat features in major LLM services:

  • ChatGPT:

  • Claude:

    • When starting a new chat, select "Use Incognito" in the upper right of the screen
  • Gemini:

    • Click the "Temporary chat" icon displayed to the right of "New chat"

Notes when using temporary chat:

  • Chat history is not saved, so make sure to save important code in Google Colab. Also save the chat contents somewhere as appropriate.

Make Sure to Back Up!

Make sure to save and back up your Google Colab notebooks regularly.

How to save:

  • Auto-save: Google Colab automatically saves to Google Drive
  • Manual save: "File" → "Save" or "Ctrl + S" (Mac: Cmd + S)

Best practices for version management:

  1. Before making major changes, copy the notebook

    • "File" → "Save a copy in Drive"
    • Add a date or version number to the filename (e.g., analysis_notebook_v2_20240115.ipynb)
  2. Check the change history

    • "File" → "Revision history" to view and restore past versions
  3. Once an important analysis result is obtained, copy and save the notebook at that point

Tips for Effective Vibe Coding

Tip 1: Be Specific with Your Prompts

Make your instructions to the LLM as specific as possible.

❌ Bad example: "Make a graph" ⭕ Good example: "Please compare the yield by variety using a box plot, with the y-axis label 'Yield (kg/10a)', the title 'Yield Comparison Between Varieties', figure size 12 cm wide × 8 cm tall, and font size 12pt"

Tip 2: Proceed Step by Step

Rather than asking for complex analyses all at once, proceed in stages.

  1. Load data → 🔬 Run in Colab and check
  2. Check basic statistics → 🔬 Run in Colab and check
  3. Simple visualization → 🔬 Run in Colab and check
  4. Statistical testing → 🔬 Run in Colab and check
  5. Create the final figure → 🔬 Run in Colab and check

By checking results at each step as you go, it's easier to identify the cause when an error occurs.

Tip 3: Don't Fear Errors

There's no need to panic when an error occurs. If you show the error message to the LLM, it will usually tell you the solution. In fact, facing errors often deepens your understanding.

Mindset for handling errors:

  • Errors are opportunities to learn
  • Error messages are hints to solving the problem
  • Through dialogue with the LLM, your understanding of the code gradually deepens

Tip 4: Templatize Frequently Used Code

If you repeat similar analyses, it's convenient to create a template notebook in advance.

Contents to include in a template:

  1. Code to mount Google Drive
  2. Code to load data
  3. Code to output basic statistics
  4. Style settings for commonly used figures

Copy the template notebook to start a new analysis, and you can save the time of initial setup. Alternatively, have the LLM write new code based on the template code.

About Folder Sharing

The greatest advantage of this method is that everything related to the analysis is saved in a Google Drive folder:

Things saved in your Google Drive folder:

  1. Original data (data/analysis_data.xlsx)
  2. Analysis code (code/analysis_notebook.ipynb)
    • Google Colab notebooks also save execution results
  3. Analysis result figures (results/figure_yield_comparison.png)
  4. Analysis result tables (results/statistics_results.csv)

When someone asks "please explain the details of your analysis method" or "please reproduce the results," sharing the Google Drive folder allows anyone to re-run the analysis in the same environment. For example, you could have your supervisor check whether the analysis is correct.

How to share a Google Drive folder:

  1. Right-click the folder and click "Share"
  2. Enter the email address of the person you want to share with
  3. Set the permission to "Viewer" (they can't edit files in the folder) or "Editor"
  4. Click "Send"

Reference link:

Note that Google Colab notebooks are saved together with execution results, so the record of "this is what happened when this code was run" is also preserved.

Want to Try It Right Now? Here's a Ready-Made Example!

If you'd like to jump straight into vibe coding with a real dataset, here's a sample notebook you can use as practice material.

It uses open-source biochar data to walk through the full workflow: building a Random Forest machine learning model and interpreting the results with SHAP analysis — exactly the kind of thing you'd do in actual research.

👉 RandomForestSHAP/BiocharRandomForestSHAP.ipynb at main · Gucchyon/RandomForestSHAP

How to use it as a vibe coding exercise:

  1. Open the notebook from the link above
  2. Save a copy to your own Google Drive ("File" → "Save a copy in Drive")
  3. Try running each cell — and whenever you're unsure what the code does, just paste it into your LLM and ask!

It's a great way to get hands-on experience with the Google Drive × Google Colab × LLM workflow described in this post.

Summary

Vibe coding is a method that leverages the power of LLMs to allow even programming beginners to perform data analysis. By repeating the cycle of generating code with the LLM → running it in Google Colab → reporting results back to the LLM, you can advance your analysis.

By centralizing everything in Google Drive, you can build a highly reproducible research environment. You'll never find yourself wondering "how did I do this analysis again?" And you can easily share everything with collaborators, supervisors, and lab members.

Recap of key points:

  • 💬 LLM = Code generator and consultation partner
  • 🔬 Google Colab = Place to run code and check results
  • 💾 Google Drive = Save everything and ensure reproducibility
  • 🔄 Repeat the LLM ↔ Colab cycle to complete the analysis

Let's all give it a try.


Reference links: - Google Colab official site - How to use Google Colab (official tutorial) - ChatGPT - Claude - Gemini - Google Drive Help Center

バイブコーディングでPythonを使ったデータ解析を始めよう!Google Drive × Google Colab × LLMで再現性の高い解析環境を構築する方法

はじめに

どうも,Guchyosです.

最近,研究でデータ解析をする際に「バイブコーディング」という手法を使うようになりました.バイブコーディングとは,LLM(大規模言語モデル)と対話しながらコードを書いていく手法のことです.「vibe」は「雰囲気」とか「ノリ」という意味で,やりたいことをLLMに伝えてコードを書いてもらうスタイルを指します.プログラミング初心者でも,やりたい解析をLLMに相談しながら進められるので,かなりハードルが下がります.

今回は,Google ColabLLMを使ったPythonのバイブコーディングのやり方を解説します. これから紹介する方法では,Google Driveにすべてのデータとコードと結果が残るので,再現性が担保しやすいというメリットもあります.

Google Colabとは?

Google Colaboratory(通称:Google Colab)は,Googleが提供する無料のクラウドベースのPython実行環境です.ブラウザだけで動作し,以下のような特徴があります:

  • 環境構築不要:Pythonやライブラリがすでにインストールされている
  • 無料でGPU/TPUが使える:機械学習などの重い計算も可能
  • Google Driveと連携:データやコードをクラウドに保存
  • 共同編集可能:Google Docsのように複数人で同時編集できる
  • Jupyter Notebook形式:コードと実行結果,説明文を1つのファイルにまとめられる

自分のパソコンに何もインストールせずに,ブラウザさえあればすぐにPythonプログラミングを始められるのが最大のメリットです.

LLM(大規模言語モデル)とは?

LLM(Large Language Model,大規模言語モデル)とは,膨大なテキストデータで学習された人工知能のことです.人間のように自然な会話ができ,質問に答えたり,文章を書いたり,プログラムコードを生成したりすることができます.

代表的なLLMサービス:

  • ChatGPT(OpenAI社):最も有名
  • Claude(Anthropic社):大雑把な聞き方でもかなり的確に答えてくれる印象
  • Gemini(Google社):Google関連のサービスとの連携が強い

これらのサービスは,ウェブブラウザからアクセスして,チャット形式で対話できます.プログラミングの知識がなくても,「こういうコードを書いてほしい」とお願いすれば,LLMがPythonコードを生成してくれます.

注意点: LLMが生成したコードは,必ずしも完璧ではないです.エラーが出ることもありますが,そのエラーメッセージをLLMに見せれば修正してくれるので,対話しながら進めていくのがバイブコーディングの醍醐味です.

Pythonとは?

Pythonは,1991年に登場したプログラミング言語で,読みやすく書きやすい文法が特徴です.現在,データサイエンス,機械学習,Web開発,自動化スクリプトなど,幅広い分野で使われています.

Pythonの特徴:

  • シンプルな文法:英語に近い自然な記述で初心者にも優しい
  • 豊富なライブラリ:統計,機械学習,画像処理など,目的別のライブラリが充実
  • 大きなコミュニティ:情報が豊富で,困ったときにすぐ解決策が見つかる
  • オープンソース:無料で使える

研究分野では,R言語と並んでデータ解析の主流の言語となっています.

Google Driveとは?

Google Driveは,Googleが提供するクラウドストレージサービスで,ファイルの保存・共有・編集をオンライン上で行うことができます.パソコンやスマートフォンなど,どのデバイスからでもアクセスでき,研究やビジネスの現場で広く利用されています.

Google Driveの特徴:

  • 15GBの無料ストレージ:Googleアカウントがあればすぐに使える
  • リアルタイム共同編集:複数人で同時にドキュメントやスプレッドシートを編集可能
  • 強力な検索機能:画像内のテキストも認識して検索できる
  • 自動同期:すべてのデバイスで最新のファイルにアクセスできる
  • 柔軟な共有設定:閲覧のみ,コメント,編集など権限を細かく設定可能

研究分野では,データやプレゼンテーション資料の共有,共同執筆などに欠かせないツールとなっています.

なぜバイブコーディング × Google Driveなのか?

プログラミングやりたいけど,一歩目のハードルが高いって感じる人がおそらく結構いると思います.

  • 「Pythonの文法がわからん」
  • 「エラーメッセージの意味がわからん」
  • 「どうコードを書けばいいのか見当もつかん」
  • 「統計手法は知ってるけど,実装方法がわからん」

バイブコーディングなら,LLMと対話しながらコードを書いていけるので,プログラミング初心者でもデータの解析ができます.やりたいことを日本語で伝えれば,LLMがコードを書いてくれるし,エラーが出てもLLMに相談すれば解決策を教えてくれます.

さらに,今回紹介する方法では,Google Driveにすべてを集約するので,こんなメリットがあります:

  • データ・コード・解析結果が一元管理される
  • つまり、解析に関することがすべてまとまって記録として残る
  • なので、共同研究者や先生、先輩後輩との共有が楽
  • 再現性も担保しやすい

やりかた!

基本的な流れ

今回解説するバイブコーディングでは,LLMとの対話Google Colabでのコード実行を行ったり来たりします.

基本的なサイクル:

  1. LLMに「こういうコードを書いてほしい」とお願いする
  2. LLMが生成したコードをコピーする
  3. Google Colabに貼り付けて実行する
  4. 結果を確認(うまくいけば次へ,エラー出たらLLMに報告)

このサイクルを繰り返しながら,解析を進めていきます.

準備編:データの整備とGoogle Driveでのフォルダとファイルの作成

1. 最強のエクセルシートを作る

まず,解析に必要なデータを全部1つのExcelシート(またはCSVファイル)にまとめます.「最強」というのは,解析に必要な情報が抜けなく整理されてる状態のことです.そして,各行のデータが複数の列に入ってる要素を組み合わせれば1つに決まるような構造になっていなければならないです.

例えば,イネの収量データなら:

年度 | 品種 | 処理区 | 反復 | 収量(kg/10a) | 草丈(cm)
-----|------|--------|------|--------------|----------
2024 | A    | 0N   | 1    | 520          | 85
2024 | A    | 0N   | 2    | 535          | 87
2024 | A    | 6N   | 1    | 580          | 92
2024 | B    | 3N   | 1    | 498          | 78
...

この例では,「年度」「品種」「処理区」「反復」の組み合わせで各行が一意に決まるようになっています.こうしておけば,どの測定値がどの条件のものか分けられているため,解析で困ることはないです.

複数のシートに分かれてるデータ(例:品種情報シート,測定データシートとか)も,できれば1つにまとめておくと楽です.

2. Google Driveにフォルダ構成を作る

Google Drive(https://drive.google.com/)にアクセスしてください. 自分のgmailのアカウントでログインしてください.これで,自分のアカウントに紐づいた形で,Google Driveにファイルが保存されていくことになります. それでは,こんな感じでフォルダを作ってみましょう.

フォルダ構成の例:

📁 研究プロジェクト名/
  📁 data/          ← データファイルを格納
  📁 code/          ← Google Colabノートブックを保存
  📁 results/       ← 解析結果の図や表を保存

具体的な手順:

  1. Google Driveを開く
  2. 左上の「新規」ボタン → 「新しいフォルダ」で「研究プロジェクト名」フォルダ作成
  3. そのフォルダ内に「data」「code」「results」の3つのフォルダ作成
  4. 作ったExcelファイルを「data」フォルダにアップロード

3. Google Colabノートブックを作成する

Google Colabのノートブックは,Google Driveから直接作れます.

方法1:Google Driveから作成(推奨)

  1. Google Driveで「code」フォルダ開く
  2. 「新規」ボタン → 「その他」→「Google Colaboratory」選ぶ
  3. ノートブック開いたら,ファイル名を「analysis_notebook」とかに変更

もし「Google Colaboratory」が表示されない場合は,「アプリを追加」から「Colaboratory」と検索してインストールしてください.

方法2:Google Colabから直接作成

  1. https://colab.research.google.com/にアクセス
  2. 「ファイル」→「ノートブックを新規作成」
  3. 作成後,「ファイル」→「ドライブにコピーを保存」で保存先を「code」フォルダに指定

参考リンク:

実践編:LLMと対話しながら解析を進める

ここからがバイブコーディングの本番.LLMとGoogle Colab行き来しながらコーディングと解析を進めていきましょう.

ステップ1:LLMに最初のコードをお願いする(LLM側)

まず,LLM(ChatGPTClaudeGeminiとか)を開いて,こんな感じで話しかけましょう.

この際,データの流出が心配なら一時チャット機能を使いましょう!

💬 LLMへのプロンプト例:

Google ColabでGoogle Driveをマウントして,
/content/drive/MyDrive/研究プロジェクト名/data/analysis_data.xlsx
というパスのExcelファイルを読み込むコードを書いてください.

LLMがこんな感じのコードを生成してくれるはずです:

from google.colab import drive
import pandas as pd

# Google Driveをマウント
drive.mount('/content/drive')

# Excelファイルを読み込み
df = pd.read_excel('/content/drive/MyDrive/研究プロジェクト名/data/analysis_data.xlsx')

# データの確認
print(df.head())

ステップ2:生成されたコードをGoogle Colabで実行(Colab側)

Google Colabの基本操作:

  • コードセル(コードを書く四角い枠のことです)追加:ノートブック上部の「+ コード」ボタン(図の赤丸)
  • コード実行:セルの左側の再生ボタン(▶)か「Shift + Enter」
  • セル削除:セルの右上のゴミ箱アイコン(図の青丸)

  1. LLMが生成したコードをコピーする
  2. Google Colabのノートブックに貼り付け
  3. コードセルの左側にある「再生」ボタン(▶)クリックして実行
  4. 初回実行時は,Google Driveへのアクセス許可を求められるので,指示に従って許可する

これで,自分のGoogle Driveのフォルダにアクセスして,そこのエクセルファイルを読み取って解析したり,解析結果を保存したりできるようになります.

ステップ3:データの基本情報を出力(LLM → Colab)

次に,データの全体像を把握するために,基本情報を出力するコードをLLMに書いてもらいます.

💬 LLMへのプロンプト例:

読み込んだExcelファイルについて,
以下の基本情報を出力するPythonコードを書いてください:

- データの行数と列数
- 列名の一覧
- 各列のデータ型
- 欠損値の有無と数
- 数値データの基本統計量(平均,標準偏差,最小値,最大値など)
- 最初の5行のデータ

作業の流れ:

  1. 💬 LLMでコードを生成してもらう
  2. 📋 コードをコピー
  3. 🔬 Google Colabに貼り付けて実行
  4. 👀 出力結果を確認(コードセルの下に表示されます)

ステップ4:基本情報をLLMに見せて解析コードを書いてもらう(Colab → LLM → Colab)

コードセルの下に出力された基本情報をコピーして,LLMに見せます.これが重要です.

この際,データの流出が心配なら一時チャット機能を使いましょう!

💬 LLMへのプロンプト例:

以下のデータで作業しています:

[ここにGoogle Colabで出力された基本情報を貼り付け]

このデータを使って,以下の解析をしたいです:

1. 品種ごとの収量の平均値を計算
2. 品種間でt検定を実施
3. 結果を箱ひげ図で可視化
4. 図とt検定の結果を/content/drive/MyDrive/研究プロジェクト名/results/に保存

Pythonコードを書いてください.

これで,LLMがデータの構造を理解した上でコード生成してくれます. LLMに見せているのはデータの要約だけなので,LLMにデータを吸い取られるリスクがないのがポイントです. 直接LLMに元データを投げても良いのですが,データセキュリティ上怖いのでお勧めしません.

再び作業の流れ:

  1. 💬 LLMでコードを生成してもらう
  2. 📋 コードをコピー
  3. 🔬 Google Colabに貼り付けて実行
  4. 👀 結果を確認(うまくいったら完了,エラーが出たら次のステップへ)

ステップ5:エラーが出た場合はLLMに報告(Colab → LLM → Colab)

プログラミングにエラーはつきもの.Google Colabで表示されたエラーメッセージをそのままコピーしてLLMに貼り付けちゃいましょう.

💬 LLMへのプロンプト例:

以下のエラーが出ました.原因と修正方法を教えてください.

[ここにGoogle Colabのエラーメッセージを貼り付け]

例:
KeyError: 'variety'

LLMが「列名が'variety'じゃなくて'品種'になってるのが原因」のような感じで,原因を説明して修正版のコードを提案してくれます.

よくあるエラーとその対処:

  • ModuleNotFoundError: 必要なライブラリがインストールされてない

    • 💬 LLMに「〇〇をインストールするコード教えて」と聞く
    • 🔬 生成されたコードをColabで実行
  • KeyError: 列名の指定ミス

    • 💬 LLMに基本情報見せて正しい列名確認
    • 🔬 修正されたコードをColabで実行
  • ValueError: データ型の不一致

    • 💬 LLMに「データ型を変換するコード教えて」って聞く
    • 🔬 生成されたコードをColabで実行

エラー解決のサイクル:

🔬 Colab: エラー発生
     ↓ エラーメッセージをコピー
💬 LLM: 原因分析 + 修正コード生成
     ↓ 修正コードをコピー
🔬 Colab: 修正コードを実行
     ↓ 成功!または再度エラー(その場合は繰り返し)

ステップ6:コードの内容を理解する(LLM側)

生成されたコードはそのまま使うだけではなく,内容を理解することも大事です.LLMに1行ずつ日本語の注釈をつけてもらいましょう.

💬 LLMへのプロンプト例:

さっき書いてもらったコードに1行ずつ日本語でコメントをつけてください.
プログラミング初心者でも理解できるように各行で何をしているのか詳しく説明してください.

こうすることで:

  • コードの動作原理が理解できる
  • 次に似たような解析をするときに応用できる
  • 論文の方法に書く内容が明確になる

注釈付きのコードをGoogle Colabに貼り付けておけば,後で見返したときにも理解しやすいです.

注意点やおすすめしたいこと!

出力する図や表はGoogle Driveに保存しよう

解析結果の図や表も,Google Driveに保存しましょう.そのコードもLLMに書いてもらえます.

💬 LLMへのプロンプト例:

作成した図を
/content/drive/MyDrive/研究プロジェクト名/results/
に「figure_yield_comparison.png」という名前で
高解像度(300 dpi)で保存するコードを追加してください.

こうすることで,図や表も全部Google Driveのフォルダに残ります.

コードの再現性を担保せよ(Pythonとライブラリのバージョン管理)!

同じコードでも,Pythonやライブラリ(コード内で「import 何とか」で表示されているものたち)のバージョンが違うと動作が変わったり,エラーが出たりすることがあります. 研究の再現性を担保するには,これらのバージョンを記録することが重要です. Pythonのバージョンの変更についてはできないのですが,実行した際のバージョンの記録はしておきましょう.

バージョンの確認方法

💬 LLMへのプロンプト例:

Google Colabで現在のPythonとpandas, numpy, matplotlib, scipy, seaborn(自分のコードに含まれているライブラリたち)の
バージョンを確認するコードを書いてください.

おそらく,以下のような回答が返ってきます.

Google Colabで現在の環境を確認するには,以下のコードを実行します:

import sys
print(f"Python version: {sys.version}")

# 主要ライブラリのバージョン確認
import pandas as pd
import numpy as np
import matplotlib
import scipy
import seaborn as sns

print(f"pandas: {pd.__version__}")
print(f"numpy: {np.__version__}")
print(f"matplotlib: {matplotlib.__version__}")
print(f"scipy: {scipy.__version__}")
print(f"seaborn: {sns.__version__}")

Google Colabで実行して,Pythonとライブラリのバージョンを表示してもらいましょう.

バージョンの記録方法

以下のように,テキストのセルを追加して,その中にメモを残せます. ちなみに,テキストのセルでは,コードは実行できません.メモ用です.

Google colabのノートブックの最初にテキストのセルを追加して,先ほどのコードの実行結果をコピペしておきましょう.

# 環境情報の記録(実行日:2024-01-15)
# Python 3.10.12
# pandas==2.0.3
# numpy==1.25.2
# matplotlib==3.7.1
# scipy==1.11.4
# seaborn==0.12.2

これで,解析を行った際のPythonとライブラリのバージョンが記録できました.

ライブラリのバージョンを固定する方法

記載されているバージョンのライブラリをインストールしたい場合は,以下のようなコードをノートブックの最初に実行します.

!pip install pandas==2.0.3 numpy==1.25.2 matplotlib==3.7.1 (ライブラリ名==バージョンを列挙)

これで,これ以降のコードでインポートされるライブラリは,ここで指定したバージョンのものになります.

おすすめのやり方:requirements.txtの作成と読込

すべてのライブラリを一括で管理したい場合は,ライブラリのリストをテキストファイルとして保存したり,読み込んだりすることもできます. 以下のようにLLMにお願いしてみましょう.

💬 LLMへのプロンプト例:

Google Colabで現在インストールされている全ライブラリのバージョンを
requirements.txtファイルとしてGoogle Driveに保存するコードを書いてください.
保存先は/content/drive/MyDrive/研究プロジェクト名/code/です.

以下のようなコードが返されるはずです.

# 現在の環境の全ライブラリをエクスポート
!pip freeze > /content/drive/MyDrive/研究プロジェクト名/code/requirements.txt

これをGoogle colabで実行すると,ライブラリのリストが含まれたrequirements.txtのファイルがGoogle Driveのフォルダに保存されているはずです.

後日,同じ環境を再現する場合には,ノートブックの一番最初に以下を実行すればOKです.

# requirements.txtから一括インストール
!pip install -r /content/drive/MyDrive/研究プロジェクト名/code/requirements.txt

データの流出が心配なら一時チャット機能を使う!

LLMにデータを直接アップロードしているわけではないとしても,未公開のデータに関する話をLLMとするのは心配かもしれない.多くのLLMサービスには「一時チャット」とか「Incogniteモード」があって,これ使えば入力したデータがモデルの学習に使われないので安心.

主要なLLMサービスの一時チャット機能:

  • ChatGPT:

  • Claude:

    • 新しいチャットを開始する際に画面右上の「Use incognite」を選択
  • Gemini:

    • 「New chat」の右に表示されている「Temporary chat」のアイコンをクリック

一時チャット使用時の注意点:

  • チャットの履歴が残らないので,重要なコードはGoogle Colabに保存しておく.チャットの内容も適宜どこかに保存しておく.

バックアップはとっておこう!

Google Colabのノートブックは,定期的に保存&バックアップを取っておきましょう.

保存方法:

  • 自動保存:Google Colabは自動的にGoogle Driveに保存されます
  • 手動保存:「ファイル」→「保存」か「Ctrl + S」(Mac: Cmd + S)

バージョン管理のベストプラクティス:

  1. 大きな変更加える前に,ノートブックをコピー

    • 「ファイル」→「ドライブにコピーを保存」
    • ファイル名に日付とかバージョン番号を追加(例:analysis_notebook_v2_20240115.ipynb
  2. 変更履歴を確認

    • 「ファイル」→「変更履歴」で過去のバージョン確認・復元できる
  3. 重要な解析結果が出たら,その時点のノートブックをコピーして保存しておく

バイブコーディングをうまくやるコツ

コツ1:プロンプトは具体的に

LLMへの指示は,できるだけ具体的にしましょう.

❌ 悪い例:「グラフ作って」 ⭕ 良い例:「品種ごとの収量を箱ひげ図で比較して,y軸のラベルは『収量(kg/10a)』,タイトルは『品種間の収量比較』,図のサイズは横12cm×縦8cm,フォントサイズは12ptにしてください」

コツ2:段階的に進める

いきなり複雑な解析を頼むのではなく,段階的に進めましょう.

  1. データ読み込み → 🔬 Colabで実行・確認
  2. 基本統計量の確認 → 🔬 Colabで実行・確認
  3. 簡単な可視化 → 🔬 Colabで実行・確認
  4. 統計検定 → 🔬 Colabで実行・確認
  5. 最終的な図の作成 → 🔬 Colabで実行・確認

各ステップで結果確認しながら進めることで,エラーが出ても原因を特定しやすい.

コツ3:エラーを恐れない

エラーが出ても焦る必要はない.エラーメッセージをLLMに見せれば,たいてい解決策を教えてくれます.むしろ,エラーと向き合うことで理解が深まることが多い.

エラー対処の心構え:

  • エラーは学習のチャンス
  • エラーメッセージは問題解決のヒント
  • LLMとの対話を通じて,徐々にコードの理解が深まる

コツ4:よく使うコードはテンプレート化

同じような解析繰り返す場合は,テンプレートとなるノートブック作っておくと便利.

テンプレートに含めると良い内容:

  1. Google Driveマウントのコード
  2. データ読み込みのコード
  3. 基本統計量を出力するコード
  4. よく使う図のスタイル設定

テンプレートのノートブックをコピーして,新しい解析始めれば,初期設定の手間を省ける. あるいは,テンプレートのコードをベースにLLMに新たなコードを書いてもらうのも良い.

フォルダの共有について

この方法の最大のメリットは,解析に関する全てがGoogle Driveのフォルダに保存されるということである:

Google Driveのフォルダに保存されるもの:

  1. 元データ(data/analysis_data.xlsx)
  2. 解析コード(code/analysis_notebook.ipynb)
    • Google Colabのノートブックには実行結果も保存されます
  3. 解析結果の図(results/figure_yield_comparison.png)
  4. 解析結果の表(results/statistics_results.csv)

誰かから「解析手法の詳細教えてほしい」とか「結果を再現してほしい」と言われた時に,Google Driveのフォルダを共有すれば誰でも同じ環境で解析を再実行できます.例えば,指導教員に解析が合ってるかチェックしてもらったりとかもできます.

Google Driveのフォルダの共有方法:

  1. フォルダを右クリックし,「共有」をクリック
  2. 共有したい相手のメールアドレスを入力
  3. 権限を「閲覧者」(フォルダ内のファイルの編集はできない)か「編集者」に設定
  4. 「送信」をクリック

参考リンク:

  • Google Colabでのファイル共有方法 ちなみに,Google Colabのノートブックには実行結果も一緒に保存されるので,「このコードを実行したらこういう結果になった」という記録も残る.

まずはここから試してみよう!

実際にバイブコーディングを体験してみたい人のために,すぐに使えるサンプルノートブックを用意しました.

オープンソースのバイオチャーデータを使って,Random Forestによる機械学習モデリングとSHAPを使った結果の解釈をひとつながりで体験できます.まさに実際の研究でやるような解析の流れそのものです.

👉 RandomForestSHAP/BiocharRandomForestSHAP.ipynb at main · Gucchyon/RandomForestSHAP

バイブコーディングの練習素材として使う方法:

  1. 上のリンクからノートブックを開く
  2. 自分のGoogle Driveにコピーを保存する(「ファイル」→「ドライブにコピーを保存」)
  3. 各セルを実行してみる――コードの意味がわからなければ,LLMに貼り付けて聞いてみよう!

この記事で紹介したGoogle Drive × Google Colab × LLMの流れを,実際のデータで試すのにぴったりの素材です.

まとめ

バイブコーディングは,LLMの力を借りて,プログラミング初心者でもデータ解析ができる手法である.LLMでコード生成 → Google Colabで実行 → 結果をLLMに報告というサイクルを繰り返すことで,解析を進められる.

Google Driveに全部を集約することで,再現性の高い研究環境を構築できる.「ここどうやって解析したんだっけ?」となることもない.共同研究者や先生,先輩後輩とも簡単に共有できる.

重要なポイントのおさらい:

  • 💬 LLM = コード生成と相談相手
  • 🔬 Google Colab = コード実行と結果確認の場
  • 💾 Google Drive = 全部を保存して再現性を担保
  • 🔄 LLM ↔ Colabのサイクルを繰り返して解析を完遂する

みんなやろう.


参考リンク: - Google Colab公式サイト - Google Colabの使い方(公式チュートリアル) - ChatGPT - Claude - Gemini - Google Driveヘルプセンター

PythonでCompact Letter Display (CLD) アルゴリズムをクリークベースで実装した

Compact Letter Display (CLD) アルゴリズム

Tukey HSD多重比較の結果を文字で見やすく表示する方法


はじめに

PythonでのCompact Letter Display (CLD) アルゴリズムのクリークベースの実装にちょい苦労したので、備忘録として記録しておきます。 Rのmultcompパッケージやemmeansパッケージでは簡単にCLDが生成できるんですが、Pythonで同じことをやろうとすると意外と大変でした。最終的にはクリーク(完全グラフ)ベースのアプローチで実装しました。 Claude Sonnet 4.5さんと相談しながら、、、もし間違いや改善点があれば、ぜひ教えてください。

参考:


概要

Compact Letter Display (CLD)は、Tukey HSD多重比較の結果を文字(a, b, c...)で視覚的に表示する手法です。同じ文字を共有するグループ間には統計的に有意な差がないことを示します。 統計解析の結果を論文やレポートで示すとき、「どのグループとどのグループに有意差があるのか」を一目で分かるようにしてくれる便利な手法です。


基本原理

「同じ文字を共有するグループ間には有意差がない」

例えば、こんな感じです:

  • グループA: a ← 最高値グループ

  • グループB: ab ← AともCとも有意差なし

  • グループC: bc ← BともDとも有意差なし

  • グループD: c ← 最低値グループ

この例だと、AとBは文字'a'を共有しているので有意差なし、BとCは文字'b'を共有しているので有意差なし、といった具合に読み取れます。


アルゴリズム:クリークベース方式

このアルゴリズムは、グラフ理論の「クリーク(完全グラフ)」という概念を使って、有意差のないグループの集合を見つけます。

Step 1: 有意差のないペアを記録

まず、Tukey HSD検定の結果から、有意差のない(p > α)ペアを集めます。

no_sig_pairs = set()
for _, row in tukey_df.iterrows():
    if row['reject'] == False:  # 有意差なし
        g1, g2 = row['group1'], row['group2']
        no_sig_pairs.add(frozenset([g1, g2]))

Step 2: クリークを見つける

クリーク = 全メンバーが互いに有意差なしのグループ集合(完全グラフ)

重要なのは、単にペアワイズで有意差がないだけじゃなくて、グループ内の全ペアが有意差なしである必要があるってことです。

from itertools import combinations

cliques = []

# 大きいサイズから順にチェック
for size in range(len(groups), 1, -1):
    for combo in combinations(groups, size):
        # 全ペアが有意差なしかチェック
        is_clique = True
        for i, g1 in enumerate(combo):
            for g2 in combo[i+1:]:
                if frozenset([g1, g2]) not in no_sig_pairs:
                    is_clique = False
                    break
        if is_clique:
            cliques.append(set(combo))

単独グループの処理

どのクリークにも属さないグループ(全てのグループと有意差あり)は、単独クリークとして扱います。

# 単独グループを追加
for group in groups:
    in_any_clique = any(group in clique for clique in cliques)
    if not in_any_clique:
        cliques.append({group})

Step 3: クリークをソート

最大平均値の大きい順にソートすることで、最高値グループを含むクリークが文字'a'を取得するようにします。

def get_max_mean(clique):
    return max(group_means[g] for g in clique)

cliques.sort(key=get_max_mean, reverse=True)

Step 4: 文字を割り当て

各クリークに順番に文字(a, b, c...)を割り当てて、各グループは属する全てのクリークの文字を持つようにします。

available_letters = 'abcdefghijklmnopqrstuvwxyz'
group_letters = {group: [] for group in groups}

for idx, clique in enumerate(cliques):
    letter = available_letters[idx]
    for group in clique:
        group_letters[group].append(letter)

# 各グループの文字をソートして結合
labels = {}
for group in groups:
    letters_list = sorted(group_letters[group])
    labels[group] = ''.join(letters_list)

完全なコード例

以下は、Tukey HSD結果からCLDを生成する完全な関数です。コピペしてそのまま使えます。

def compact_letter_display(groups, group_means, tukey_df):
    """
    Compact Letter Display (CLD) を生成
    
    Parameters:
    -----------
    groups : list
        グループ名のリスト(降順ソート済み推奨)
    group_means : dict
        {group: mean_value} の辞書
    tukey_df : DataFrame
        Tukey HSD結果 (columns: group1, group2, reject)
    
    Returns:
    --------
    labels : dict
        {group: 'a', 'ab', 'bc', ...} の辞書
    """
    from itertools import combinations
    
    # Step 1: 有意差のないペアを記録
    no_sig_pairs = set()
    for _, row in tukey_df.iterrows():
        if row['reject'] == False:
            g1, g2 = row['group1'], row['group2']
            no_sig_pairs.add(frozenset([g1, g2]))
    
    # Step 2: クリークを見つける
    cliques = []
    for size in range(len(groups), 1, -1):
        for combo in combinations(groups, size):
            is_clique = True
            for i, g1 in enumerate(combo):
                for g2 in combo[i+1:]:
                    if frozenset([g1, g2]) not in no_sig_pairs:
                        is_clique = False
                        break
                if not is_clique:
                    break
            if is_clique:
                clique_set = set(combo)
                is_new = True
                for existing in cliques:
                    if clique_set.issubset(existing):
                        is_new = False
                        break
                if is_new:
                    cliques.append(clique_set)
    
    # 単独グループを追加
    for group in groups:
        in_any = any(group in c for c in cliques)
        if not in_any:
            cliques.append({group})
    
    # Step 3: クリークをソート
    cliques.sort(
        key=lambda c: max(group_means[g] for g in c),
        reverse=True
    )
    
    # Step 4: 文字を割り当て
    letters = 'abcdefghijklmnopqrstuvwxyz'
    group_letters = {g: [] for g in groups}
    
    for idx, clique in enumerate(cliques):
        letter = letters[idx]
        for group in clique:
            group_letters[group].append(letter)
    
    # 結果
    labels = {}
    for group in groups:
        letters_list = sorted(group_letters[group])
        labels[group] = ''.join(letters_list)
    
    return labels

重要なポイント

1. クリークは完全グラフであること

全メンバーが互いに有意差なしである必要があります。

単にペアワイズで有意差がないだけじゃダメで、クリーク内の全ペアが有意差なしである必要があります。ここを間違えると、結果がおかしくなるので注意です。

2. 単独グループの処理を忘れずに

どのクリークにも属さないグループは単独クリークとして扱います。

全てのグループと有意差がある場合、そのグループは独自の文字を持ちます。この処理を忘れると、一部のグループにラベルが付かなくなってしまいます。

3. ソート順に注意

平均値の大きいグループを含むクリークから a, b, c... を割り当てます。

これによって、最高値グループが'a'を、最低値グループが最後の文字を取得します。ソート順を間違えると、逆になってしまうので気をつけましょう。

4. 複数の文字を持つことがある

グループは複数のクリークに属することがあり、その場合は ab, bc のように複数文字を持ちます。

これは、そのグループが複数の異なるグループ集合と有意差がないことを示しています。これがCLDの重要な特徴です。

Mouse Dictionaryの使い始め How to use ”Mouse Dictionary”

Mouse Dictionaryで英単語学習のハードルを下げる

製作者様のQiita記事
Chrome拡張の高速な英語辞書ツールをつくりました(Mouse Dictionary) #JavaScript - Qiita

Mouse Dictionaryは、ウェブページ上の英単語にマウスカーソルを合わせるだけで、その意味をその場で表示してくれる辞書ツールです。
Chrome、Microsofe EdgeおよびFirefox対応の拡張機能です。
DeepLやChatGPTで訳していると、英単語の対応まで見なくて英語力が付きづらかったりとか、毎回コピペするのがちょい面倒だったりするので、結構おすすめです。

Mouse Dictionaryのインストール方法

  1. Chromeウェブストアから拡張機能を追加:

  2. 拡張機能のオプション設定:

    • インストール後、ブラウザの右上に表示されるMouse Dictionaryのアイコンを右クリックし、「オプション」を選択します。
    • 初回起動時に、フリーの辞書データを自動的に登録するか聞かれるので、OKをクリックして登録すると、辞書機能が使えるようになります。加えて、自分で作ったカスタム辞書データを追加することも可能です。

カスタム辞書データの作成と読み込み

以下の手順で自作のカスタム辞書を準備し、読み込めます。

  1. 辞書データの作成:

    • テキストエディタで、以下のような形式で単語とその意味をタブ区切りで入力します。

      canopy 群落
      plant height   草高
      plant length   草丈
      green manure   緑肥
      
    • 作成したファイルを.tsv形式で保存します。

  2. 辞書データの読み込み:

    • Mouse Dictionaryのオプション画面で、以下の設定にして、、、
    • 作成した.tsvファイルを選択し、「LOAD」ボタンをクリックして辞書データを読み込みます。
  3. 辞書データのリセット: カスタム辞書を修正して再度読み込みをし直したい場合は、リセットが必要です。

    • Mouse Dictionaryのオプション画面で、「設定を開く」をクリック。
    • 一番下の方にある、「デフォルト辞書データの再ロード」をクリック。 !
    • 再度2のように新たな辞書を読み込めばよい。

Mouse Dictionaryの使用方法

辞書データの読み込みが完了したら、ウェブページ上で英単語にマウスカーソルを合わせるだけで、ポップアップウィンドウにその意味が表示されるようになってます。

Site map(サイトマップ)

研究論文に関するTips Research Paper Tips

解析のやり方など Methods of Analysis

その他の関連ページ Related Websites

生成AIを使うときに考えること・LLMを使った論文の速読・精読 Things to think about when using generative AI/Skimming and intensive reading of papers using LLM

生成AIを使うときに考えること

生成AI:テキスト・画像・音声などを自動的に生成できるAI

  • AIの出力に対して最終的に責任を持つのは人間である。

  • 研究に関わる機密データをアップロードする際には、注意が必要。 同じ形式でダミーのデータを用意して、解析方法を提案してもらったり、コードを書いてもらう、というのが安心。

  • 出力してもらった結果は、中身の解析や引用がどうなっているかを理解したうえで使う。 Web検索機能を使うか、あるいは自分で見つけた文献をアップロードしてそれに基づいて回答してもらうのが良い。

  • 回答の精度は飛躍的に向上しているが、まだ、嘘の回答をすることがあるハルシネーション)ので注意。 最近はハルシネーションをしないでというと、ハルシネーションをしないらしい。

chatGPTに「ハルシネーションしないで」とお願いしたら効果がある? | SIOS Tech. Lab

LLMを使った論文の速読・精読

大規模言語モデル(LLMs):大量のテキストデータと深層学習によって構築された、文章作成や翻訳などの自然言語処理に活用される生成AI

最も有名なLLMの一つ ChatGPT

chatgpt.com

最近、PDFとか受け付けてくれるし、画像とかでも返してくれるし、媒体が多様化した(マルチモーダル化

速読(数分-数十分)

論文の重要なポイントや新規性を短時間で把握する

  • 概要の把握 ChatGPTに論文を「論文の読み方」に沿って解説してもらう。

guchyos.hatenablog.com

魔法の言葉「Step by stepで」 自分のお気に入りの読み方を見つけたらそれでも良い。
論文のPDFをアップロードし、指示を入力して回答してもらう。

  • 関連論文の把握 論文誌を指定して探してもらう。

    精読(30分-数時間)

論文で登場する技術や手法、図表を完全に理解し、論旨に関わらない議論の隅々まで把握した上で、自分の考えをまとめる

  • 図表の理解 スクショ(Shift + Windows + S)してコピペして解説してもらう
  • 技術や手法の理解 ググって出てきた資料やWebページをアップロードして解説してもらう Webサーチをonにして質問する→Webサイトもチェック

Things to think about when using generative AI

Generative AI: AI that can automatically generate text, images, audio, etc.

  • Humans have the last word in the use of AI

  • Be careful when uploading confidential data related to your research. It is safe to prepare dummy data in the same format and ask them to suggest a method of analysis or write the code for the analysis.

  • The results you get from the output should be used with an understanding of how the contents are analyzed and cited; use the web search function or upload the references you have found and have them respond based on that.

  • The accuracy of the answers has improved dramatically, but be aware that they still sometimes give false answers (hallucination). These days, if you ask them not to hallucinate, they don't hallucinate. chatGPTに「ハルシネーションしないで」とお願いしたら効果がある? | SIOS Tech. Lab

Skimming and intensive reading of papers using LLM

Large language models (LLMs): Generative AI used for natural language processing such as writing and translation, built using large amounts of text data and deep learning.

One of the most famous LLMs ChatGPT chatgpt.com

Recently, it accepts PDFs and returns images, and the media has become more diverse (multimodal)

Skimming (Several minutes - several tens of minutes)

Grasp the key points and novelty of the paper in a short time

  • Understanding the overview Ask ChatGPT to explain the paper according to "how to read papers"
    guchyos.hatenablog.com
    Magic words "Step by step"
    You can use your own favorite way of reading if you find one.
    Upload the paper's PDF and enter instructions to get answers.

  • Understanding related papers Ask it to search within specified journals

    Intensive reading (30 minutes - several hours)

Complete understanding of the techniques, methods, and figures that appear in the paper and a thorough grasp of the nooks and crannies of the argument that are not involved in the main point of the paper.