Predicting Product Prices and Future Ratings through Images

Imagine your stuck at home during a terrible pandemic. There is chaos everywhere and you feel powerless to do anything to stop it. Then suddenly you get a brilliant idea! You are going to collect items you have no use for, sell them online, and donate the profits to a relief fund.

picture

You gather a bunch of stuff and realize there is only one problem: you have no idea how much to charge for the items online. Doing research takes a ton of time and its still hard to get a good idea of what price makes sense and how others may rate what your trying to sell. But what if you could get an estimate for a price by just using a picture of your stuff? What if you could use your first few reviews to get an estimate of your future rating? That would make your life much easier.

To do this you decide to build two models:

  1. A model that predicts price and ratings from the images of products
  2. A model that predicts ratings from the review text

Your not sure how effective these models will be in predicting price and reviews, but you decide its worth a shot to find out.


Predicting Prices from Images

The Dataset

It was surprisingly difficult to find a dataset of product images, prices, and reviews so we decided to create our own. We built a spider using scrapy that crawled Amazon to find over 400 images of dresses as well as the prices and the average review rating of each dress. The dresses we used to build this model can be found here. We chose to scrape dresses from here as all the dresses were a similar shape and behind them was a plain white background. This made it much easier to find important features and distinguish their meaning. (The scraper is included and is called fash.py)

From our scraper, we build a dataset of 10 csv files, each with the image url, price, and average review rating of 48 dresses to get a total dataset of 480 dresses.

Prepping the data

In [1]:
import pandas as pd
import numpy as np
In [2]:
dresses = pd.read_csv("dress_all.csv")
dresses2 = pd.read_csv("dress_all_2.csv")
dresses3 = pd.read_csv("dress_all_3.csv")
dresses4 = pd.read_csv("dress_all_4.csv")
dresses5 = pd.read_csv("dress_all_5.csv")
dresses6 = pd.read_csv("dress_all_6.csv")
dresses7 = pd.read_csv("dress_all_7.csv")
dresses8 = pd.read_csv("dress_all_8.csv")
dresses9 = pd.read_csv("dress_all_9.csv")
dresses10 = pd.read_csv("dress_all_10.csv")
In [3]:
dress = pd.concat([dresses, dresses2, dresses3, dresses4, dresses5, dresses6, dresses7, dresses8, dresses9, dresses10], axis=0)
dress = dress.reset_index()
dress.head()
Out[3]:
index first secondary review price url name img_url
0 0 Fair Lady Long Sleeves Sheer Black Lace Prom Dresses Bal... 5.0 out of 5 stars,1 $99.00 https://www.amazon.com/Fair-Lady-Sleeves-Dress... Fair Lady Long Sleeves Sheer Black Lace Prom D... https://images-na.ssl-images-amazon.com/images...
1 1 OUGES Women's Summer Short Sleeve V-Neck Floral Shor... 4.2 out of 5 stars,596 $28.99 https://www.amazon.com/OUGES-Womens-Pattern-Po... OUGES Women's Summer Short Sleeve V-Neck Flora... https://images-na.ssl-images-amazon.com/images...
2 2 KORSIS Women's Summer Floral Dresses T Shirt Dress Fl... 4.2 out of 5 stars,170 $22.83,$29.99 https://www.amazon.com/KORSIS-Womens-Summer-Fl... KORSIS Women's Summer Floral Dresses T Shirt D... https://images-na.ssl-images-amazon.com/images...
3 3 StayPretty V Neck Bridesmaid Dresses Long Chiffon Aline P... 3.8 out of 5 stars,12 $69.99 https://www.amazon.com/Bridesmaid-Dresses-Chif... V Neck Bridesmaid Dresses Long Chiffon Aline P... https://images-na.ssl-images-amazon.com/images...
4 4 Noras dress Women's Lace Appliques Mother of The Bride Dre... 4.9 out of 5 stars,10 $99.99,$189.99 https://www.amazon.com/Noras-dress-Appliques-S... Noras dress Women's Lace Appliques Mother of T... https://images-na.ssl-images-amazon.com/images...

Lets start by cleaning our price and review columns so we can see their distribution and use them as the response variables in our model.

In [4]:
prices = dress.price.str.split(",").tolist()
price_clean = []

for price in prices:
  try:
    first = price[0]
    num = float(first[1:])
    price_clean.append(num)
  except:
    price_clean.append(None)
  
price_clean = pd.Series(price_clean)
In [5]:
review_clean = dress.review.str[:3].astype(float)

Now that we cleaned our response variables, let's take a quick glance to see what distributions we are working with

In [6]:
price_clean.plot.hist()
Out[6]:
<matplotlib.axes._subplots.AxesSubplot at 0x1165b4090>
In [7]:
review_clean.plot.hist()
Out[7]:
<matplotlib.axes._subplots.AxesSubplot at 0x1171432d0>

Now we have to convert our image urls into something we can use to build our model. To do that we to take the image url, get the image, and covert it to a numpy array of the r, g, b value of every pixel

In [8]:
import urllib.request
from PIL import Image

def processImage(url):
    im = Image.open(urllib.request.urlopen(url))
    im = im.resize((50,137))
    pixels = list(im.getdata())
    return pixels
In [9]:
img_data = []
for url in dress.img_url:
    pixels = processImage(url)
    row = []
    
    for px in pixels:
        try:
            r,g,b = px
            row.append(r/255)
            row.append(g/255)
            row.append(b/255)
        except:
            l = 0
    
    img_data.append(row)

Finally we must remove NAs as well as add the cleaned response variables to the dataframe.

In [10]:
df = pd.DataFrame.from_records(img_data)
df["price"] = price_clean
df["reviews"] = review_clean
df["img_url"] = dress["url"]
clean_df = df.dropna()
clean_df
Out[10]:
0 1 2 3 4 5 6 7 8 9 ... 20543 20544 20545 20546 20547 20548 20549 price reviews img_url
0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 ... 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 99.00 5.0 https://www.amazon.com/Fair-Lady-Sleeves-Dress...
1 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 ... 0.317647 0.772549 0.478431 0.352941 0.949020 0.917647 0.909804 28.99 4.2 https://www.amazon.com/OUGES-Womens-Pattern-Po...
2 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 ... 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 22.83 4.2 https://www.amazon.com/KORSIS-Womens-Summer-Fl...
3 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 ... 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 69.99 3.8 https://www.amazon.com/Bridesmaid-Dresses-Chif...
4 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 ... 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 99.99 4.9 https://www.amazon.com/Noras-dress-Appliques-S...
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
475 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 ... 1.000000 0.996078 1.000000 1.000000 1.000000 1.000000 1.000000 82.99 4.6 https://www.amazon.com/Alicepub-Bridesmaid-Dre...
476 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 ... 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 83.99 4.2 https://www.amazon.com/Wedding-Bridesmaid-Dres...
477 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 ... 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 79.99 4.5 https://www.amazon.com/Alicepub-Pleated-Chiffo...
478 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 ... 0.996078 0.996078 0.996078 0.996078 0.996078 0.996078 0.996078 84.99 4.3 https://www.amazon.com/Lily-Wedding-Mermaid-Br...
479 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 ... 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 85.99 4.4 https://www.amazon.com/YSMei-Vintage-Evening-B...

434 rows × 20553 columns

Since we standardized all the images to a width of 50 pixels and a height of 137 pixels, our dataset includes data about 6850 pixels for every image. But for each pixel we have a r,g,b value and so in total our dataset has 20,550 columns for each of the 480 images. That plus the 3 columns including the response variables price, reviews, and the old image url

Regression

First we are going to train a regression model that predicts price and reviews from our cleaned dataset. Since we have far more columns than rows, we are going to run the lasso and ridge regression models.

Training the Models

In [11]:
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split

train_lin, test_lin = train_test_split(clean_df, test_size=0.25, random_state=3)
In [12]:
from sklearn.model_selection import cross_val_score

train_y_rev, train_y_price_val = train_lin['reviews'], train_lin['price']
test_y_rev, test_y_price_val = test_lin['reviews'], test_lin['price']
trainX_lin = train_lin.drop(['img_url', 'price', 'reviews'], axis=1)
testX_lin = test_lin.drop(['img_url', 'price', 'reviews'], axis=1)
In [13]:
from sklearn.linear_model import Ridge
from sklearn.linear_model import Lasso

review_model = Ridge()
price_model = Ridge()
review_lasso = Lasso()
price_lasso = Lasso()
In [14]:
# Train the Ridge Models
review_model.fit(trainX_lin, train_y_rev)
price_model.fit(trainX_lin, train_y_price_val)

# Train the Lasso Models
review_lasso.fit(trainX_lin, train_y_rev)
price_lasso.fit(trainX_lin, train_y_price_val)
Out[14]:
Lasso(alpha=1.0, copy_X=True, fit_intercept=True, max_iter=1000,
      normalize=False, positive=False, precompute=False, random_state=None,
      selection='cyclic', tol=0.0001, warm_start=False)

Finding the Prediction Risk

Now lets find the root mean squared error to see how well our model predicts price and reviews on test data it has never seen before.

In [15]:
from sklearn.metrics import mean_squared_error

review_model_preds = review_model.predict(testX_lin)
price_model_preds = price_model.predict(testX_lin)
review_lasso_preds = review_lasso.predict(testX_lin)
price_lasso_preds = price_lasso.predict(testX_lin)


print(mean_squared_error(test_y_price_val, price_model_preds)**0.5)
print(mean_squared_error(test_y_price_val, price_lasso_preds)**0.5)
print(mean_squared_error(test_y_rev, review_model_preds)**0.5)
print(mean_squared_error(test_y_rev, review_lasso_preds)**0.5)
17.402409522740697
19.820236139120393
0.16737755918836186
0.3399277039726617

At first glance, these models seem pretty good. They are able to predict price within +- $20 and predict the review within +- 0.3 stars. However, to get a better idea of the variance of this testing accuracy, lets do a 10 fold cross validation and see what root mean squared error we get then

In [16]:
from sklearn.model_selection import cross_validate

X, y_price, y_review = clean_df.drop(['img_url', 'price', 'reviews'], axis=1), clean_df['price'], clean_df['reviews']
X = np.array(X)
y_price = np.array(y_price)
y_reviews = np.array(y_review)

cv_price_ridge = cross_validate(price_model, X, y_price, cv=10, scoring="neg_root_mean_squared_error")
cv_price_lasso = cross_validate(price_lasso, X, y_price, cv=10, scoring="neg_root_mean_squared_error")
cv_review_ridge = cross_validate(review_model, X, y_review, cv=10, scoring="neg_root_mean_squared_error")
cv_review_lasso = cross_validate(review_lasso, X, y_review, cv=10, scoring="neg_root_mean_squared_error")
In [17]:
print(cv_price_ridge['test_score'])
print(cv_price_lasso['test_score'])
print(cv_review_ridge['test_score'])
print(cv_review_lasso['test_score'])
[-59.92924243 -43.71639203 -19.44040295  -0.40311592  -0.40771299
  -0.36153783  -0.36154145  -0.36153952  -2.96102946 -15.10798584]
[-61.02219191 -33.6497509  -22.26374138 -13.46315633 -13.52800426
 -12.11103451 -12.05804652 -12.07681424 -13.10716621 -12.33113314]
[-0.41735063 -0.40518046 -0.13680322 -0.00990129 -0.01001479 -0.01001759
 -0.0100146  -0.0100146  -0.04919307 -0.11871858]
[-0.35675705 -0.31623534 -0.3009941  -0.39103417 -0.35623323 -0.35457065
 -0.34443032 -0.34443032 -0.35786093 -0.33214345]

As we can see for predicting price, while in some cross validation folds the error is very little ($20) in others it is very high ($50), while for reviews the error also fluctuates from little error around +- 0.05 stars to 0.4 stars.

Classification

Now, let's see if classification models work better and have less variance in their accuracy. For our analysis, we chose to implement the logistic regression classification model.

To do this we had to create labels that correspond to price and review values

In [18]:
reviewconditions = [
    review_clean<=3.75,
    (review_clean>3.75) & (review_clean<=4.25),
    (review_clean>4.25) & (review_clean<=4.6),
    review_clean>4.6]
reviewchoices = [0,1,2,3]
review_labels = np.select(reviewconditions, reviewchoices, default=-1)
In [19]:
priceconditions = [
    price_clean<=40.0,
    (price_clean>40.0) & (price_clean<=60.0),
    (price_clean>60.0) & (price_clean<=80.0),
    (price_clean>80.0) & (price_clean<=100.0),
    price_clean>100.0]
pricechoices = [0,1,2,3,4]
price_labels = np.select(priceconditions, pricechoices, default=-1)
In [20]:
df["review_labels"] = review_labels
df["price_labels"] = price_labels
class_df = df.dropna()
class_df
Out[20]:
0 1 2 3 4 5 6 7 8 9 ... 20545 20546 20547 20548 20549 price reviews img_url review_labels price_labels
0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 ... 1.000000 1.000000 1.000000 1.000000 1.000000 99.00 5.0 https://www.amazon.com/Fair-Lady-Sleeves-Dress... 3 3
1 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 ... 0.478431 0.352941 0.949020 0.917647 0.909804 28.99 4.2 https://www.amazon.com/OUGES-Womens-Pattern-Po... 1 0
2 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 ... 1.000000 1.000000 1.000000 1.000000 1.000000 22.83 4.2 https://www.amazon.com/KORSIS-Womens-Summer-Fl... 1 0
3 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 ... 1.000000 1.000000 1.000000 1.000000 1.000000 69.99 3.8 https://www.amazon.com/Bridesmaid-Dresses-Chif... 1 2
4 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 ... 1.000000 1.000000 1.000000 1.000000 1.000000 99.99 4.9 https://www.amazon.com/Noras-dress-Appliques-S... 3 3
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
475 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 ... 1.000000 1.000000 1.000000 1.000000 1.000000 82.99 4.6 https://www.amazon.com/Alicepub-Bridesmaid-Dre... 2 3
476 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 ... 1.000000 1.000000 1.000000 1.000000 1.000000 83.99 4.2 https://www.amazon.com/Wedding-Bridesmaid-Dres... 1 3
477 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 ... 1.000000 1.000000 1.000000 1.000000 1.000000 79.99 4.5 https://www.amazon.com/Alicepub-Pleated-Chiffo... 2 2
478 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 ... 0.996078 0.996078 0.996078 0.996078 0.996078 84.99 4.3 https://www.amazon.com/Lily-Wedding-Mermaid-Br... 2 3
479 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 ... 1.000000 1.000000 1.000000 1.000000 1.000000 85.99 4.4 https://www.amazon.com/YSMei-Vintage-Evening-B... 2 3

434 rows × 20555 columns

In [21]:
X_class, y_price_class, y_review_class = class_df.drop(['img_url', 'price_labels', 'reviews'], axis=1), class_df['price_labels'], class_df['review_labels']
In [23]:
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import LogisticRegression
import warnings
warnings.filterwarnings('ignore')

reviewLog = LogisticRegression()
priceLog = LogisticRegression()

cv_rev = cross_val_score(reviewLog, X_class, y_review_class, cv=10)
cv_price = cross_val_score(priceLog, X_class, y_price_class, cv=10)
In [24]:
print(cv_rev)
print(cv_price)
[0.54545455 0.61363636 0.79545455 0.97727273 1.         1.
 1.         1.         0.97674419 0.88372093]
[0.84090909 0.93181818 0.93181818 1.         1.         1.
 1.         1.         1.         0.93023256]
In [25]:
import statistics

print(statistics.stdev(cv_rev))
print(statistics.mean(cv_rev))

print(statistics.stdev(cv_price))
print(statistics.mean(cv_price))
0.17206184075501207
0.8792283298097252
0.053889005226225806
0.9634778012684989

We still see some variance in the accuracy with accuracy as low as around 60% when trained under one fold and 90% accuracy when trained on another fold. Still we can see that the image is giving strong signals about the price and avg rating.

What features are important in predicting a dresses price and average review?

Now that we have built our models and seen predictive power significant to some degree, we can use these models to better understand what features predict price and reviews. Specifically, we can begin to understand what parts of the dress are most impactful in determining price and do the same for reviews.

Creating A Condensed Dataset

The analysis of which features more most important in an image is extremely computationally-intensive. Therefore, to reduce the load, we need to compress the dataset. One method for this is instead of having 3 columns for each r, g, b value, we just take the mean of the three values. This cuts the number of columns from 20,550 to 6,850.

In [26]:
condensed = []

for url in dress.img_url:
    pixels = processImage(url)
    row = []
    
    for px in pixels:
        try:
            r,g,b = px
            total = 0
            total += r/255
            total += g/255
            total += b/255

            total = total/3
            row.append(total)
        except:
            l = 0
    
    condensed.append(row)
In [27]:
cond_df = pd.DataFrame.from_records(condensed)
In [28]:
cond_df["price"] = price_labels
cond_df["reviews"] = review_labels
cond_df = cond_df.dropna()
cond_df.head()
Out[28]:
0 1 2 3 4 5 6 7 8 9 ... 6842 6843 6844 6845 6846 6847 6848 6849 price reviews
0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.000000 ... 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.00000 3 3
1 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.000000 ... 0.529412 0.588235 0.594771 0.573856 0.559477 0.526797 0.534641 0.92549 0 1
2 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 0.922876 ... 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.00000 0 1
3 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.000000 ... 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.00000 2 1
4 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.000000 ... 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.00000 3 3

5 rows × 6852 columns

Now that we have created the condensed dataset, it is time to get the X and y values we will fit on in order to get what features are important.

In [29]:
price_cond = cond_df["price"]
review_cond = cond_df["reviews"]
X_cond = cond_df.drop(["price", "reviews"], axis=1)

Now our last step is just to create the RFE, or recursive feature elimination, which is used to see which feaures are important and highlight them in a grid. For the sake of speed, we will only run the mode on the first 30 data-points, through the images from the presentation came from running it on far more points.

In [30]:
from sklearn.svm import SVC
from sklearn.datasets import load_digits
from sklearn.feature_selection import RFE
import matplotlib.pyplot as plt

# Create the RFE object and rank each pixel
svc = SVC(kernel="linear", C=1)
rfe = RFE(estimator=svc, n_features_to_select=1, step=1)
rfe.fit(X_cond.iloc[0:150], review_cond[0:150])
ranking = rfe.ranking_.reshape(137, 50)

# Plot pixel ranking
plt.matshow(ranking, cmap=plt.cm.Blues)
plt.colorbar()
plt.title("Ranking of pixels with RFE")
plt.show()
In [31]:
from sklearn.svm import SVC
from sklearn.datasets import load_digits
from sklearn.feature_selection import RFE
import matplotlib.pyplot as plt

# Create the RFE object and rank each pixel
svc = SVC(kernel="linear", C=1)
rfe = RFE(estimator=svc, n_features_to_select=1, step=1)
rfe.fit(X_cond.iloc[0:150], review_cond[0:150])
ranking = rfe.ranking_.reshape(137, 50)

# Plot pixel ranking
plt.matshow(ranking, cmap=plt.cm.Blues)
plt.colorbar()
plt.title("Ranking of pixels with RFE")
plt.show()

Thus, at just 30 condensed images, you cannot tell much, but with much more you can see that the top and shape of the bottom of the dress are really important in predicting price, while the threads in the middle are important for predicting reviews.

I also included the following plots that just show how the cross validated accuracy changes with the number of features to show again that only a fraction of pixels are needed to get most of the accuracy in predicting price and reviews.

In [ ]:
import matplotlib.pyplot as plt
from sklearn.svm import SVC
from sklearn.model_selection import StratifiedKFold
from sklearn.feature_selection import RFECV
from sklearn.datasets import make_classification


rfecv = RFECV(estimator=svc, step=1, cv=StratifiedKFold(2),
              scoring='accuracy')
rfecv.fit(X_cond, price_cond)

print("Optimal number of features : %d" % rfecv.n_features_)

# Plot number of features VS. cross-validation scores
plt.figure()
plt.xlabel("Number of features selected")
plt.ylabel("Cross validation score (nb of correct classifications)")
plt.plot(range(1, len(rfecv.grid_scores_) + 1), rfecv.grid_scores_)
plt.show()
In [ ]:
import matplotlib.pyplot as plt
from sklearn.svm import SVC
from sklearn.model_selection import StratifiedKFold
from sklearn.feature_selection import RFECV
from sklearn.datasets import make_classification


rfecv = RFECV(estimator=svc, step=1, cv=StratifiedKFold(2),
              scoring='accuracy')
rfecv.fit(X_cond, review_cond)

print("Optimal number of features : %d" % rfecv.n_features_)

# Plot number of features VS. cross-validation scores
plt.figure()
plt.xlabel("Number of features selected")
plt.ylabel("Cross validation score (nb of correct classifications)")
plt.plot(range(1, len(rfecv.grid_scores_) + 1), rfecv.grid_scores_)
plt.show()