{"id":198,"date":"2026-09-03T10:53:59","date_gmt":"2026-09-03T10:53:59","guid":{"rendered":"https:\/\/alpeshconnect.in\/blog\/?p=198"},"modified":"2026-09-03T10:53:59","modified_gmt":"2026-09-03T10:53:59","slug":"mobile-store-price-prediction-linear-regression","status":"publish","type":"post","link":"https:\/\/alpeshconnect.in\/blog\/2026\/09\/03\/mobile-store-price-prediction-linear-regression\/","title":{"rendered":"Mobile Store Price Prediction &#8211; Linear Regression"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>from sklearn.model_selection import train_test_split<br>from sklearn.linear_model import LinearRegression<br>from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error<br><br># ============================================<br># Part 1: Load and Prepare Dataset<br># ============================================<br><br># Given dataset<br>data = {<br>    \"Storage\": [32, 32, 64, 64, 128, 128, 128, 256, 256, 256, 512, 512, 512, 512, 512],<br>    \"Price\": [10, 12, 15, 18, 22, 25, 30, 35, 38, 42, 50, 55, 60, 65, 70]<br>}<br><br># Convert to DataFrame<br>df_phones = pd.DataFrame(data)<br><br>print(\"=\"*60)<br>print(\"Q2: Smartphone Price Prediction - Linear Regression\")<br>print(\"=\"*60)<br><br>print(\"\\n Dataset Overview:\")<br>print(df_phones.head(10))<br>print(f\"\\n Dataset Shape: {df_phones.shape}\")<br>print(f\" Storage Range: {df_phones['Storage'].min()}GB - {df_phones['Storage'].max()}GB\")<br>print(f\" Price Range: \u20b9{df_phones['Price'].min()}K - \u20b9{df_phones['Price'].max()}K\")<br><br># Check for any missing values<br>print(f\"\\n Missing Values:\\n{df_phones.isnull().sum()}\")<br><br># ============================================<br># Part 2: Split Features and Target<br># ============================================<br><br># Independent variable (X) - Storage<br>X = df_phones[['Storage']]  # 2D array (required by sklearn)<br><br># Dependent variable (y) - Price<br>y = df_phones['Price']      # 1D array<br><br>print(\"\\n Feature (Independent Variable): Storage\")<br>print(f\"Shape: {X.shape}\")<br><br>print(\"\\n Target (Dependent Variable): Price\")<br>print(f\"Shape: {y.shape}\")<br><br># ============================================<br># Part 3: Split into Training and Testing Sets<br># ============================================<br><br># Split data: 80% training, 20% testing<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)<br><br>print(f\"\\n Training Set Size: {len(X_train)} samples\")<br>print(f\" Testing Set Size: {len(X_test)} samples\")<br><br># ============================================<br># Part 4: Build and Train Linear Regression Model<br># ============================================<br><br># Create and train the model<br>model = LinearRegression()<br>model.fit(X_train, y_train)<br><br># Get model coefficients<br>print(f\"\\n Model Coefficients:\")<br>print(f\"Intercept (\u03b20): {model.intercept_:.4f}\")<br>print(f\"Coefficient (\u03b21): {model.coef_[0]:.4f}\")<br>print(f\"\\n Equation: Price = {model.intercept_:.2f} + {model.coef_[0]:.2f} * Storage\")<br><br># ============================================<br># Part 5: Predict Prices<br># ============================================<br><br># Predict on training and test data<br>y_train_pred = model.predict(X_train)<br>y_test_pred = model.predict(X_test)<br><br># Predict for new storage values (Indian market scenario)<br>new_storage = np.array([[64], [128], [256], [512], [1024]])<br>predicted_prices = model.predict(new_storage)<br><br>print(\"\\n Predictions for New Storage Options:\")<br>predictions_df = pd.DataFrame({<br>    'Storage (GB)': new_storage.flatten(),<br>    'Predicted Price (\u20b9K)': np.round(predicted_prices, 2)<br>})<br>print(predictions_df)<br><br># ============================================<br># Part 6: Visualize Regression Line on Scatter Plot<br># ============================================<br><br>plt.figure(figsize=(12, 6))<br><br># Scatter plot of actual data<br>plt.scatter(X, y, color='blue', s=100, alpha=0.6, label='Actual Data', edgecolors='black')<br><br># Regression line<br>x_range = np.linspace(X.min(), X.max(), 100).reshape(-1, 1)<br>y_range = model.predict(x_range)<br>plt.plot(x_range, y_range, color='red', linewidth=3, label='Regression Line')<br><br># Highlight training and test points<br>plt.scatter(X_train, y_train, color='green', s=80, alpha=0.5, marker='o', label='Training Data')<br>plt.scatter(X_test, y_test, color='orange', s=120, alpha=0.7, marker='s', label='Test Data')<br><br># Plot predictions<br>plt.scatter(new_storage, predicted_prices, color='purple', s=200, marker='D', <br>            label='Predicted for New Storage', edgecolors='black', zorder=5)<br><br># Add value labels for predictions<br>for i, (storage, price) in enumerate(zip(new_storage.flatten(), predicted_prices)):<br>    plt.annotate(f'{storage}GB: \u20b9{price:.1f}K', <br>                 (storage, price), <br>                 xytext=(10, 10), <br>                 textcoords='offset points',<br>                 fontsize=9,<br>                 bbox=dict(boxstyle='round,pad=0.3', facecolor='yellow', alpha=0.7))<br><br># Customize plot<br>plt.xlabel('Storage (GB)', fontsize=12)<br>plt.ylabel('Price (\u20b9K)', fontsize=12)<br>plt.title('Smartphone Price Prediction\\nStorage vs Price (Linear Regression)', fontsize=14, fontweight='bold')<br>plt.legend(loc='upper left', fontsize=10)<br>plt.grid(True, alpha=0.3)<br>plt.xlim(0, 1100)<br>plt.ylim(0, 120)<br><br># Add annotation for model equation<br>plt.text(550, 20, f'Price = {model.intercept_:.2f} + {model.coef_[0]:.2f} * Storage', <br>         fontsize=11, bbox=dict(boxstyle='round,pad=0.5', facecolor='lightgray', alpha=0.8))<br><br>plt.show()<br><br># ============================================<br># Part 7: Evaluate Model Performance<br># ============================================<br><br>print(\"\\n\" + \"=\"*60)<br>print(\"PART 5: Model Evaluation\")<br>print(\"=\"*60)<br><br># R\u00b2 Score<br>r2_train = r2_score(y_train, y_train_pred)<br>r2_test = r2_score(y_test, y_test_pred)<br><br>print(f\"\\n R\u00b2 Score (Training): {r2_train:.4f}\")<br>print(f\" R\u00b2 Score (Testing): {r2_test:.4f}\")<br><br># Other metrics<br>mse_train = mean_squared_error(y_train, y_train_pred)<br>mse_test = mean_squared_error(y_test, y_test_pred)<br>rmse_train = np.sqrt(mse_train)<br>rmse_test = np.sqrt(mse_test)<br>mae_train = mean_absolute_error(y_train, y_train_pred)<br>mae_test = mean_absolute_error(y_test, y_test_pred)<br><br>print(f\"\\n Training Metrics:\")<br>print(f\"   MSE: {mse_train:.4f}\")<br>print(f\"   RMSE: {rmse_train:.4f}\")<br>print(f\"   MAE: {mae_train:.4f}\")<br><br>print(f\"\\n Testing Metrics:\")<br>print(f\"   MSE: {mse_test:.4f}\")<br>print(f\"   RMSE: {rmse_test:.4f}\")<br>print(f\"   MAE: {mae_test:.4f}\")<br><br># ============================================<br># Part 8: Residual Analysis<br># ============================================<br><br># Calculate residuals<br>residuals = y_test - y_test_pred<br><br># Plot residuals<br>plt.figure(figsize=(12, 5))<br><br>plt.subplot(1, 2, 1)<br>plt.scatter(y_test_pred, residuals, color='purple', alpha=0.7, s=80)<br>plt.axhline(y=0, color='red', linestyle='--', linewidth=2)<br>plt.xlabel('Predicted Price (\u20b9K)', fontsize=12)<br>plt.ylabel('Residuals', fontsize=12)<br>plt.title('Residual Plot', fontsize=12)<br>plt.grid(True, alpha=0.3)<br><br>plt.subplot(1, 2, 2)<br>plt.hist(residuals, bins=8, color='lightgreen', edgecolor='black', alpha=0.7)<br>plt.xlabel('Residuals', fontsize=12)<br>plt.ylabel('Frequency', fontsize=12)<br>plt.title('Distribution of Residuals', fontsize=12)<br>plt.axvline(x=0, color='red', linestyle='--', linewidth=2)<br>plt.grid(True, alpha=0.3)<br><br>plt.tight_layout()<br>plt.show()<br><br># ============================================<br># Part 9: Real-world Indian Market Insights<br># ============================================<br><br>print(\"\\n\" + \"=\"*60)<br>print(\"Real-World Indian Market Insights\")<br>print(\"=\"*60)<br><br># Predict prices for popular Indian smartphone configurations<br>indian_configs = np.array([[64], [128], [256], [512]])<br>indian_prices = model.predict(indian_configs)<br><br>print(\"\\n Predicted Prices for Indian Smartphone Configurations:\")<br>config_data = pd.DataFrame({<br>    'Storage': indian_configs.flatten(),<br>    'Predicted Price (\u20b9K)': np.round(indian_prices, 2),<br>    'Predicted Price (\u20b9)': np.round(indian_prices * 1000, 0)<br>})<br>print(config_data)<br><br>print(\"\\n Price Comparison:\")<br>print(\"64GB: \u20b915,000 - \u20b918,000 (Budget segment)\")<br>print(\"128GB: \u20b922,000 - \u20b930,000 (Mid-range)\")<br>print(\"256GB: \u20b935,000 - \u20b942,000 (Premium)\")<br>print(\"512GB: \u20b950,000 - \u20b970,000 (Flagship)\")<br><br>print(\"\\n Model Training and Evaluation Complete!\")<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LinearRegressionfrom sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error# ============================================# Part 1: Load and Prepare Dataset# ============================================# Given datasetdata = { &#8220;Storage&#8221;: [32, 32, 64, 64, 128, 128, 128, 256, 256, 256, 512, 512, 512, 512, 512], &#8220;Price&#8221;: [10, 12, 15, 18, 22, [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":188,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,55],"tags":[25,26,59,58,45],"class_list":["post-198","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-bca","category-ml","tag-bca","tag-bca-paper-solution","tag-machine-learning","tag-ml","tag-python"],"_links":{"self":[{"href":"https:\/\/alpeshconnect.in\/blog\/wp-json\/wp\/v2\/posts\/198","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/alpeshconnect.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/alpeshconnect.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/alpeshconnect.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/alpeshconnect.in\/blog\/wp-json\/wp\/v2\/comments?post=198"}],"version-history":[{"count":1,"href":"https:\/\/alpeshconnect.in\/blog\/wp-json\/wp\/v2\/posts\/198\/revisions"}],"predecessor-version":[{"id":199,"href":"https:\/\/alpeshconnect.in\/blog\/wp-json\/wp\/v2\/posts\/198\/revisions\/199"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/alpeshconnect.in\/blog\/wp-json\/wp\/v2\/media\/188"}],"wp:attachment":[{"href":"https:\/\/alpeshconnect.in\/blog\/wp-json\/wp\/v2\/media?parent=198"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/alpeshconnect.in\/blog\/wp-json\/wp\/v2\/categories?post=198"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/alpeshconnect.in\/blog\/wp-json\/wp\/v2\/tags?post=198"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}