Spaces:
Build error
Build error
Upload 5 files
Browse filesFiles changed (4)
- ChatAssessmentAnalysis.pyAdded+58
- EmbeddingExtraction.pyAdded+41
- FeatureExtraction.pyAdded+37
- ObtainChatData.pyAdded+25
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758# ChatAssessmentAnalysis.py# Purpose: Script for analyzing chat data using machine learning models, including training, validation, and testing.
import pandas as pdimport numpy as npimport pickleimport xgboost as xgbfrom sklearn.multioutput import MultiOutputRegressorfrom sklearn.model_selection import train_test_splitfrom sklearn.metrics import mean_squared_error, mean_absolute_error
# Read your data filedatafile_path = "data/chat_transcripts_with_features.csv" # Update this path as necessarydf = pd.read_csv(datafile_path)
# Convert embeddings to numpy arraysdf['embedding'] = df['embedding'].apply(lambda x: np.array([float(num) for num in x.strip('[]').split(',')]))
# Define features (X) and labels (y) - Adjust column names as per your datasetX = np.array(df['embedding'].tolist())y = df[['score1', 'score2', 'score3']].values # Replace with your actual score columns
# Split data into training, validation, and testing setsX_train, X_val_test, y_train, y_val_test = train_test_split(X, y, test_size=0.3, random_state=42)X_val, X_test, y_val, y_test = train_test_split(X_val_test, y_val_test, test_size=0.5, random_state=42)
# Train the regression model# Note: You can replace XGBRegressor with any other regression model as per your requirement.# For instance, you might use RandomForestRegressor or a neural network model from Keras.xg_reg = xgb.XGBRegressor(objective='reg:squarederror', colsample_bytree=0.3, learning_rate=0.05, max_depth=4, alpha=0, lam=0.5, n_estimators=200)multioutput_reg = MultiOutputRegressor(xg_reg)multioutput_reg.fit(X_train, y_train)
# Save the trained modelmodel_filename = 'trained_model.pkl'with open(model_filename, 'wb') as file: pickle.dump(multioutput_reg, file)print(f"Model trained and saved as {model_filename}")
# Validate the model# Note: You can use other metrics for validation based on your specific needs.# For instance, you might consider using precision, recall, F1-score, or ROC-AUC for classification tasks.val_preds = multioutput_reg.predict(X_val)val_mse = mean_squared_error(y_val, val_preds)val_mae = mean_absolute_error(y_val, val_preds)print(f"Validation MSE: {val_mse:.2f}, Validation MAE: {val_mae:.2f}")
# Test the modeltest_preds = multioutput_reg.predict(X_test)test_mse = mean_squared_error(y_test, test_preds)test_mae = mean_absolute_error(y_test, test_preds)print(f"Test MSE: {test_mse:.2f}, Test MAE: {test_mae:.2f}")
# Note to Users:# - Make sure to adjust the data paths and column names to match your dataset.# - Feel free to experiment with different machine learning models and parameters to find the best fit for your data.# - The trained model can be used to make predictions on new chat transcript data.# - Consider re-training the model periodically with new data to keep it updated and improve its accuracy.1234567891011121314151617181920212223242526272829303132333435363738394041import pandas as pdimport openaiimport tiktokenimport osimport configfrom openai import OpenAIfrom dotenv import load_dotenvload_dotenv(override=True)
client = OpenAI( api_key=os.getenv("OPENAI_API_KEY"))# Set your OpenAI API key
# Embedding model parametersembedding_model = "text-embedding-ada-002"embedding_encoding = "cl100k_base"max_tokens = 8000
# Function to get embeddingsdef get_embedding(text, model="text-embedding-3-small"): text = text.replace("\n", " ") return client.embeddings.create(input = [text], model=model).data[0].embedding
# Load preprocessed chat transcript datainput_datapath = "../data/processed_chat_data.csv"output_datapath = "../data/chat_transcripts_with_embeddings.csv"df = pd.read_csv(input_datapath)
# Ensure your chat transcripts are within the token limit for embeddingencoding = tiktoken.get_encoding(embedding_encoding)df["n_tokens"] = df["transcript"].apply(lambda x: len(encoding.encode(x)))df = df[df["n_tokens"] <= max_tokens]
# Extract embeddings for each chat transcriptprint("Extracting embeddings...")df["embedding"] = df["transcript"].apply(lambda x: get_embedding(x, embedding_model))
# Save the data with embeddingsdf.to_csv(output_datapath, index=False)print(f"Data with embeddings saved to {output_datapath}")12345678910111213141516171819202122232425262728293031323334353637# FeatureExtraction.py# Purpose: Script to extract additional features from chat transcripts for psychological assessments.
# Importsimport pandas as pdimport numpy as npfrom textblob import TextBlob
# Function to calculate sentiment polaritydef get_sentiment_polarity(text): return TextBlob(text).sentiment.polarity
# Function to calculate sentiment subjectivitydef get_sentiment_subjectivity(text): return TextBlob(text).sentiment.subjectivity
# Load data with embeddingsinput_datapath = "data/chat_transcripts_with_embeddings.csv"output_datapath = "data/chat_transcripts_with_features.csv"df = pd.read_csv(input_datapath)
# Feature Extraction# Example: Extracting sentiment polarity and subjectivitydf['sentiment_polarity'] = df['chathistory'].apply(get_sentiment_polarity)df['sentiment_subjectivity'] = df['chathistory'].apply(get_sentiment_subjectivity)
# TODO: Add any additional feature extraction relevant to your study here.# Example: df['feature_name'] = df['column'].apply(your_custom_function)
# Save the data with additional featuresdf.to_csv(output_datapath, index=False)print(f"Data with additional features saved to {output_datapath}")
# Note to Users:# - Ensure that 'input_datapath' points to your data file with embeddings.# - This script uses TextBlob for sentiment analysis. Install it using 'pip install textblob' if not already installed.# - You can add more feature extraction functions as needed for your specific research requirements.12345678910111213141516171819202122232425# ObtainChatData.pyimport pandas as pd
# Load & inspect datasetinput_datapath = "../data/chatbotdata.csv"output_datapath = "../data/processed_chat_data.csv"df = pd.read_csv(input_datapath)print("Initial Data Loaded. Here's a preview:")print(df.head(2))
# Data Preprocessingdf = df.dropna()print(f"Data after cleaning: {len(df)} entries")
# Combine all transcripts from the same user into a single transcriptdf_combined = df.groupby('user_id')['transcript'].apply(' '.join).reset_index()
# Save the processed datadf_combined.to_csv(output_datapath, index=False)print(f"Processed data saved to {output_datapath}")
# Note to Users:# - Ensure that your data file path is correctly specified in 'input_datapath'.# - The script currently includes a basic data cleaning step (dropping missing values). Depending on your data, you may need to add more preprocessing steps.# - The processed data is saved in CSV format. Make sure to use this processed file in subsequent analysis scripts.ChatAssessmentAnalysis.pyAdded+58
EmbeddingExtraction.pyAdded+41
FeatureExtraction.pyAdded+37
ObtainChatData.pyAdded+25