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.

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:
Your not sure how effective these models will be in predicting price and reviews, but you decide its worth a shot to find out.
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.
import pandas as pd
import numpy as np
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")
dress = pd.concat([dresses, dresses2, dresses3, dresses4, dresses5, dresses6, dresses7, dresses8, dresses9, dresses10], axis=0)
dress = dress.reset_index()
dress.head()
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.
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)
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
price_clean.plot.hist()
review_clean.plot.hist()
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
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
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.
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
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
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.
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)
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)
from sklearn.linear_model import Ridge
from sklearn.linear_model import Lasso
review_model = Ridge()
price_model = Ridge()
review_lasso = Lasso()
price_lasso = Lasso()
# 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)
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.
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)
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
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")
print(cv_price_ridge['test_score'])
print(cv_price_lasso['test_score'])
print(cv_review_ridge['test_score'])
print(cv_review_lasso['test_score'])
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.
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
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)
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)
df["review_labels"] = review_labels
df["price_labels"] = price_labels
class_df = df.dropna()
class_df
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']
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)
print(cv_rev)
print(cv_price)
import statistics
print(statistics.stdev(cv_rev))
print(statistics.mean(cv_rev))
print(statistics.stdev(cv_price))
print(statistics.mean(cv_price))
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.
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.
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.
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)
cond_df = pd.DataFrame.from_records(condensed)
cond_df["price"] = price_labels
cond_df["reviews"] = review_labels
cond_df = cond_df.dropna()
cond_df.head()
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.
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.
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()
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.
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()
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()