Question
I found this code on chegg and I have a problem that I cannot solve. It suppose to create an output file but it does
I found this code on chegg and I have a problem that I cannot solve. It suppose to create an output file but it does not. Assignment comes with a train and test file to run the code with but I cannot upload those files here. I would be happy with any help but especially a fixed code, thank you.
#include
#include
#include
#include
#include
#include
// Structure to represent a rating given by a user to an item
struct Rating {
int user;
int item;
float rating;
};
// Read ratings from the train.csv file and store them in a vector
std::vector
std::vector
std::ifstream file(filename);
std::string line;
// Skip the first line with the column names
std::getline(file, line);
while (std::getline(file, line)) {
Rating rating;
std::stringstream ss(line);
std::string cell;
std::getline(ss, cell, ',');
rating.user = std::stoi(cell);
std::getline(ss, cell, ',');
rating.item = std::stoi(cell);
std::getline(ss, cell, ',');
rating.rating = std::stof(cell);
ratings.push_back(rating);
}
return ratings;
}
// Calculate the cosine similarity between two vectors of ratings
float cosineSimilarity(const std::unordered_map
float dotProduct = 0;
float magnitude1 = 0;
float magnitude2 = 0;
for (const auto& [item, rating] : ratings1) {
if (ratings2.count(item)) {
dotProduct += rating * ratings2.at(item);
}
magnitude1 += rating * rating;
}
for (const auto& [item, rating] : ratings2) {
magnitude2 += rating * rating;
}
return dotProduct / (std::sqrt(magnitude1) * std::sqrt(magnitude2));
}
int main() {
// Read the ratings from the train.csv file
std::vector
// Create a map from user IDs to vectors of ratings
std::unordered_map
for (const Rating& rating : ratings) {
userRatings[rating.user][rating.item] = rating.rating;
}
// Open the test.csv file
std::ifstream file("test.csv");
std::string line;
// Skip the first line with the column names
std::getline(file, line);
while (std::getline(file, line)) {
// Read a test case from the file
std::stringstream ss(line);
std::string cell;
int user;
int item;
std::getline(ss, cell, ',');
user = std::stoi(cell);
std::getline(ss, cell, ',');
item
}
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started