<jupyter_start><jupyter_text>Modelling Discogs Marketplace price predictions  EDA and selecting data<jupyter_code>from google.colab import drive
drive.mount('/content/drive')
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.model_selection import train_test_split
from sklearn import metrics
from sklearn.linear_model import LinearRegression

import pickle
df = pd.read_csv("/content/drive/MyDrive/Data/electro_raw_data.csv", parse_dates=["release_date"], na_values="N/A")
df.head()
df.shape<jupyter_output><empty_output><jupyter_text>Convert release date to year<jupyter_code>df["release_year"] = df['release_date'].dt.year<jupyter_output><empty_output><jupyter_text>Only keep records priced under 100 eur<jupyter_code>df = df[df["price"] < 100]<jupyter_output><empty_output><jupyter_text>Parse item condition to numerical values<jupyter_code># Parses item condition value to numerical values
def parse_item_condition_to_int(condition: str) -> int:
    return {
        "Poor (P)": 0,
        "Fair (F)": 0,
        "Good (G)": 1,
        "Good Plus (G+)": 1,
        "Very Good (VG)": 2,
        "Very Good Plus (VG+)": 3,
        "Generic": 3,
        "Not Graded": 3,
        "No Cover": 3,
        "Near Mint (NM or M-)": 4,
        "Mint (M)": 5
    }[condition]
df["media_condition"] = df["media_condition"].apply(
    lambda cond: parse_item_condition_to_int(cond))
df["sleeve_condition"] = df["sleeve_condition"].apply(
    lambda cond: parse_item_condition_to_int(cond))<jupyter_output><empty_output><jupyter_text>Drop N/A rows<jupyter_code>df = df.dropna()<jupyter_output><empty_output><jupyter_text>Drop unneeded columns<jupyter_code>df = df.drop(["artist", "title", "label", "release_date", "release_page"], axis="columns")
df.head()
df.shape<jupyter_output><empty_output><jupyter_text>Encoding and scaling data<jupyter_code>one_hot_encoder = OneHotEncoder().fit(df[["release_format"]])
encoded_data = one_hot_encoder.transform(df[["release_format"]]).todense()
scaler = StandardScaler().fit(
    df.drop(["release_format", "price"], axis="columns"))
scaled_data = scaler.transform(
    df.drop(["release_format", "price"], axis="columns"))
encoded_features = np.concatenate([encoded_data, scaled_data], axis=-1)
train_features, test_features, train_price, test_price = train_test_split(
    encoded_features, df["price"]
)<jupyter_output><empty_output><jupyter_text>Training the model<jupyter_code>model = LinearRegression(fit_intercept=False)
model.fit(train_features, train_price)<jupyter_output><empty_output><jupyter_text>Evaluating the model<jupyter_code>score = model.score(test_features, test_price)
predicted = model.predict(test_features)
mae = metrics.mean_absolute_error(test_price, predicted)
print(f"Model score: {score}")
print(f"Mean absolute error: {mae}")
expected = test_price
plt.scatter(expected, predicted)
plt.plot([0, 50], [0, 50], '--k')
plt.axis('tight')
plt.xlabel('True price')
plt.ylabel('Predicted price')<jupyter_output><empty_output><jupyter_text>Exporting the models<jupyter_code>with open("model.pkl", "wb") as f:
  pickle.dump(model, f)
with open("one_hot_encoder.pkl", "wb") as f:
  pickle.dump(one_hot_encoder, f)
with open("scaler.pkl", "wb") as f:
  pickle.dump(scaler, f)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1404293381037567, 'fraction_numerical': 0.007155635062611807, 'mean_word_length': 6.82051282051282, 'pattern_counts': {'":': 11, '<': 42, '<?xml version=': 0, '>': 42, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '10', 'dir': 'jupyter-structured-clean-dedup', 'id': '513753', 'license': 'MIT', 'n_tokens_mistral': 1215, 'n_tokens_neox': 1169, 'n_words': 228, 'path': 'Preparing_data_and_models.ipynb', 'repo_name': 'grigorjevas/Discogs-price-prediction', 'size': '3354'}