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n.model_selection import train_test_split
|
| 5 |
+
from sklearn.linear_model import LinearRegression, LogisticRegression
|
| 6 |
+
from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier
|
| 7 |
+
from xgboost import XGBRegressor, XGBClassifier
|
| 8 |
+
from sklearn.svm import SVC
|
| 9 |
+
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score, accuracy_score, precision_score, recall_score, f1_score, roc_auc_score
|
| 10 |
+
from statsmodels.tsa.arima.model import ARIMA
|
| 11 |
+
from tensorflow.keras.models import Sequential
|
| 12 |
+
from tensorflow.keras.layers import LSTM, Dense
|
| 13 |
+
from tensorflow.keras.callbacks import EarlyStopping
|
| 14 |
+
from sklearn.preprocessing import MinMaxScaler
|
| 15 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 16 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
| 17 |
+
from textblob import TextBlob # For sentiment analysis
|
| 18 |
+
import logging
|
| 19 |
+
|
| 20 |
+
# Set up logging
|
| 21 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 22 |
+
|
| 23 |
+
# Load Instagram data
|
| 24 |
+
logging.info("Loading Instagram data...")
|
| 25 |
+
data = pd.read_csv('processed_instagram_data.csv')
|
| 26 |
+
|
| 27 |
+
# Load Instagram secrets book
|
| 28 |
+
logging.info("Loading Instagram secrets book...")
|
| 29 |
+
with open('Instagram_secrets_full.json', 'r') as f:
|
| 30 |
+
instagram_secrets = json.load(f)
|
| 31 |
+
|
| 32 |
+
# Extract tips and tricks from the book
|
| 33 |
+
logging.info("Extracting tips and tricks from the book...")
|
| 34 |
+
tips = []
|
| 35 |
+
for section in instagram_secrets.values():
|
| 36 |
+
if isinstance(section, dict):
|
| 37 |
+
for key, value in section.items():
|
| 38 |
+
if isinstance(value, str):
|
| 39 |
+
tips.append(value)
|
| 40 |
+
elif isinstance(value, list):
|
| 41 |
+
tips.extend(value)
|
| 42 |
+
elif isinstance(section, list):
|
| 43 |
+
tips.extend(section)
|
| 44 |
+
|
| 45 |
+
# Preprocess tips (e.g., remove duplicates, clean text)
|
| 46 |
+
tips = list(set(tips)) # Remove duplicates
|
| 47 |
+
logging.info(f"Extracted {len(tips)} unique tips from the book.")
|
| 48 |
+
|
| 49 |
+
# Feature Engineering
|
| 50 |
+
logging.info("Performing feature engineering...")
|
| 51 |
+
data['posting_time_encoded'] = pd.to_datetime(data['posting_time']).astype(int) / 10**9
|
| 52 |
+
data['caption_length'] = data['caption'].apply(len)
|
| 53 |
+
data['hashtag_count'] = data['hashtags'].apply(lambda x: len(eval(x)))
|
| 54 |
+
data['viral'] = data['engagement_rate'].apply(lambda x: 1 if x > data['engagement_rate'].quantile(0.75) else 0)
|
| 55 |
+
data['sentiment'] = data['caption'].apply(lambda x: TextBlob(x).sentiment.polarity) # Sentiment analysis
|
| 56 |
+
|
| 57 |
+
# Define features and target variables
|
| 58 |
+
X = data[['posting_time_encoded', 'content_type_encoded', 'caption_length', 'hashtag_count', 'media_type_encoded', 'sentiment']]
|
| 59 |
+
y_engagement = data['engagement_rate']
|
| 60 |
+
y_viral = data['viral']
|
| 61 |
+
|
| 62 |
+
# Split data
|
| 63 |
+
X_train, X_test, y_train_engagement, y_test_engagement, y_train_viral, y_test_viral = train_test_split(
|
| 64 |
+
X, y_engagement, y_viral, test_size=0.2, random_state=42
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
# Regression Model: Engagement Rate Prediction
|
| 68 |
+
logging.info("Training engagement rate prediction model...")
|
| 69 |
+
engagement_model = XGBRegressor(random_state=42)
|
| 70 |
+
engagement_model.fit(X_train, y_train_engagement)
|
| 71 |
+
y_pred_engagement = engagement_model.predict(X_test)
|
| 72 |
+
mae = mean_absolute_error(y_test_engagement, y_pred_engagement)
|
| 73 |
+
mse = mean_squared_error(y_test_engagement, y_pred_engagement)
|
| 74 |
+
r2 = r2_score(y_test_engagement, y_pred_engagement)
|
| 75 |
+
logging.info(f"Engagement Rate Model: MAE: {mae:.4f}, MSE: {mse:.4f}, R²: {r2:.4f}")
|
| 76 |
+
|
| 77 |
+
# Classification Model: Viral Potential Prediction
|
| 78 |
+
logging.info("Training viral potential prediction model...")
|
| 79 |
+
viral_model = XGBClassifier(random_state=42)
|
| 80 |
+
viral_model.fit(X_train, y_train_viral)
|
| 81 |
+
y_pred_viral = viral_model.predict(X_test)
|
| 82 |
+
accuracy = accuracy_score(y_test_viral, y_pred_viral)
|
| 83 |
+
precision = precision_score(y_test_viral, y_pred_viral)
|
| 84 |
+
recall = recall_score(y_test_viral, y_pred_viral)
|
| 85 |
+
f1 = f1_score(y_test_viral, y_pred_viral)
|
| 86 |
+
roc_auc = roc_auc_score(y_test_viral, viral_model.predict_proba(X_test)[:, 1])
|
| 87 |
+
logging.info(f"Viral Potential Model: Accuracy: {accuracy:.4f}, Precision: {precision:.4f}, Recall: {recall:.4f}, F1-Score: {f1:.4f}, ROC-AUC: {roc_auc:.4f}")
|
| 88 |
+
|
| 89 |
+
# Time-Series Model: Optimal Posting Times
|
| 90 |
+
logging.info("Training time-series model for optimal posting times...")
|
| 91 |
+
time_series_data = data.groupby('posting_time')['engagement_rate'].mean().reset_index()
|
| 92 |
+
time_series_data.set_index('posting_time', inplace=True)
|
| 93 |
+
train_size = int(len(time_series_data) * 0.8)
|
| 94 |
+
train, test = time_series_data[:train_size], time_series_data[train_size:]
|
| 95 |
+
arima_model = ARIMA(train, order=(5, 1, 0))
|
| 96 |
+
arima_fit = arima_model.fit()
|
| 97 |
+
predictions = arima_fit.forecast(steps=len(test))
|
| 98 |
+
mape = mean_absolute_percentage_error(test, predictions)
|
| 99 |
+
logging.info(f"ARIMA Model: MAPE: {mape:.4f}")
|
| 100 |
+
|
| 101 |
+
# Recommendation System: Hashtag and Keyword Recommendations
|
| 102 |
+
logging.info("Training recommendation system for hashtags...")
|
| 103 |
+
hashtags = data['hashtags'].apply(lambda x: ' '.join(eval(x)))
|
| 104 |
+
vectorizer = TfidfVectorizer()
|
| 105 |
+
tfidf_matrix = vectorizer.fit_transform(hashtags)
|
| 106 |
+
cosine_sim = cosine_similarity(tfidf_matrix, tfidf_matrix)
|
| 107 |
+
|
| 108 |
+
def recommend_hashtags(post_index, top_n=5):
|
| 109 |
+
sim_scores = list(enumerate(cosine_sim[post_index]))
|
| 110 |
+
sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)
|
| 111 |
+
top_indices = [i[0] for i in sim_scores[1:top_n+1]]
|
| 112 |
+
return data.iloc[top_indices]['hashtags']
|
| 113 |
+
|
| 114 |
+
# Example: Recommend hashtags for the first post
|
| 115 |
+
logging.info("Example Hashtag Recommendations:")
|
| 116 |
+
print(recommend_hashtags(0))
|
| 117 |
+
|
| 118 |
+
# Sentiment Analysis: Audience Reactions
|
| 119 |
+
logging.info("Performing sentiment analysis on captions...")
|
| 120 |
+
data['sentiment_category'] = data['sentiment'].apply(lambda x: 'Positive' if x > 0 else 'Negative' if x < 0 else 'Neutral')
|
| 121 |
+
logging.info("Sentiment Analysis Results:")
|
| 122 |
+
print(data['sentiment_category'].value_counts())
|
| 123 |
+
|
| 124 |
+
# Niche Trend Analysis (if available)
|
| 125 |
+
logging.info("Analyzing niche trends...")
|
| 126 |
+
niche_trends = data.groupby('content_type')['engagement_rate'].mean().sort_values(ascending=False)
|
| 127 |
+
logging.info("Top Performing Content Types:")
|
| 128 |
+
print(niche_trends)
|
| 129 |
+
|
| 130 |
+
# Promotion Recommendations
|
| 131 |
+
logging.info("Generating promotion recommendations...")
|
| 132 |
+
promotion_data = data[data['promoted'] == 1]
|
| 133 |
+
promotion_effectiveness = promotion_data.groupby('content_type')['engagement_rate'].mean().sort_values(ascending=False)
|
| 134 |
+
logging.info("Most Effective Content Types for Promotion:")
|
| 135 |
+
print(promotion_effectiveness)
|
| 136 |
+
|
| 137 |
+
# Callbacks to Avoid Overfitting
|
| 138 |
+
early_stopping = EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True)
|
| 139 |
+
|
| 140 |
+
# Train Until 95% Accuracy (Example for Classification Model)
|
| 141 |
+
logging.info("Training viral potential model until 95% accuracy...")
|
| 142 |
+
accuracy = 0
|
| 143 |
+
while accuracy < 0.95:
|
| 144 |
+
viral_model.fit(X_train, y_train_viral, eval_set=[(X_test, y_test_viral)], early_stopping_rounds=10, verbose=False)
|
| 145 |
+
y_pred_viral = viral_model.predict(X_test)
|
| 146 |
+
accuracy = accuracy_score(y_test_viral, y_pred_viral)
|
| 147 |
+
logging.info(f"Current Accuracy: {accuracy:.4f}")
|
| 148 |
+
|
| 149 |
+
logging.info("Training complete!")
|