def change_window(): # Смена окна if Variables.name == 'Главное меню': Variables.window = MainWindow() elif Variables.name == 'Настройки': Variables.window = Settings() elif Variables.name == 'Предыгровое меню': Variables.window = Pre_game_setting() elif Variables.name == 'Игра': Variables.window = Pole([var.lab_w, var.lab_h], var.lab_col) elif Variables.name == 'Помощь': Variables.window = Help() elif Variables.name == 'Испытания': Variables.window = Pole([randint(6, 8), randint(6, 8)], randint(2, 5)) elif Variables.name == 'Установка результата': Variables.window = Dilog() elif Variables.name == 'Рейтинг': Variables.window = Rating() Variables.window.first_update()
class MovieTester: nmovie = 10 print('loading data...') movnames = pd.read_csv('data/movie_titles.txt', usecols=range(3), header=None, encoding="ISO-8859-1") movdict_list = [] for i in range(nmovie): movdat = pd.read_csv('data/mv_' + str(i + 1).zfill(7) + '.txt', skiprows=1, header=None, encoding="utf-8") nusr = movdat.shape[0] for j in range(nusr): movdict = dict() movdict['user'] = movdat.iloc[j, 0] #user id movdict['rating'] = movdat.iloc[j, 1] #rating movdict['movie'] = movnames.iloc[i, 2] #movie name movdict_list.append(movdict) data = pd.DataFrame(movdict_list) print('done.') rater = Rating.Rating(25, 0.3, 5) rater.fit(data) errors = [] movies_to_predict = movnames.iloc[:nmovie, 2].values for m in range(nmovie): watched_userIDs = data.loc[data['movie'] == movies_to_predict[m], 'user'].values for i in range(len(watched_userIDs)): errors.append( rater.predict(watched_userIDs[i], movies_to_predict[m]) - rater.actual(watched_userIDs[i], movies_to_predict[m])) print('-------------------------') print("Predicted ratings are off by " + str(np.average(errors)) + "+/-" + str(np.std(errors) / len(watched_userIDs)**0.5) + " on average for " + movies_to_predict[m] + ".") print("People who like " + movies_to_predict[m] + " might also like " + rater.recommend(movies_to_predict[m]) + ".")
// Into org.apache.spark.mllib.recommendation.Rating class def parseRating(str: String): Rating= { val fields = str.split("::") Rating(fields(0).toInt, fields(1).toInt, fields(2).toDouble) } // create an RDD of Ratings objects val ratingsRDD = ratingText.map(parseRating).cache() println("Total number of ratings: " + ratingsRDD.count()) println("Total number of movies rated: " + ratingsRDD.map(_.product).distinct().count()) println("Total number of users who rated movies: " + ratingsRDD.map(_.user).distinct().count()) / load the data into DataFrames val usersDF = sc.textFile("/home/jovyan/work/datasets/spark-ebook/users.dat"). map(parseUser).toDF()
def main(): ratings = data.readFile(filedir + ratingsFilename, "::") rating.ratings = ratings rating.printFirstKItems(ratings) globalAvg = rating.calculateGlobalAvg(ratings) rating.printGlobalAvg(globalAvg) trainAndTestSets = rating.getTrainAndTestSets(ratings) rp.predictBasedOnGlobalAvg(trainAndTestSets, globalAvg) aggItemTrain = rp.predictRatingPerItem(trainAndTestSets, globalAvg) aggUserTrain = rp.predictRatingPerUser(trainAndTestSets, globalAvg) rp.predictByLinairRegression(trainAndTestSets, aggItemTrain, aggUserTrain, globalAvg)
def predictRating(trainAndTestSets, globalAvg, basedOn): meanRmses = [] foldMovieRatings = [{} for i in range(len(trainAndTestSets))] for fold, dataSet in enumerate(trainAndTestSets): print("\nFold " + str(fold) + ":") trainSet = dataSet[0] testSet = dataSet[1] movieRatings = None if (basedOn == 0): # aggregate ratings by user id movieRatings = rating.aggregateByUser(trainSet, testSet) else: # aggregate ratings by movie id movieRatings = rating.aggregateByMovie(trainSet, testSet) trainMovies = movieRatings["trainMovies"] testMovies = movieRatings["testMovies"] foldMovieRatings[fold].update(trainMovies) ################# # TRAIN ################# trainRmses = [] for id, trainRatings in trainMovies.items(): # if movie does not exist in train set, then use global avg of the movie movieAvg = np.mean( trainMovies[id]) if id in trainMovies else globalAvg se = (movieAvg - trainRatings)**2 rmse = np.sqrt(np.mean(se)) trainRmses.append(rmse) # print train error: meanTrainRmse = np.mean(trainRmses) print("\tTrain RMSE: " + str(meanTrainRmse)) ################# # TEST ################# testRmses = [] for id, testRatings in testMovies.items(): movieAvg = 0.0 # if movie does not exist in train set, then use global avg of the movie if id in trainMovies: movieAvg = np.mean(trainMovies[id]) else: movieAvg = globalAvg se = (movieAvg - testRatings)**2 testRmses.append(np.sqrt(np.mean(se))) # print test error: meanTestRmse = np.mean(testRmses) print("\tTest RMSE: " + str(meanTestRmse)) meanRmses.append([meanTrainRmse, meanTestRmse]) return [np.array(meanRmses), foldMovieRatings]
print Superheroes.superheroes[i] #lists the available superheroes i += 1 y = random.randint(0, 11) #generates random integer between 0 and 11 z = random.randint(0, 11) #generates random integer between 0 and 11 while (z == y): z = random.randint(0, 11) #ensures that the random numbers are different print 'Your two superheroes are\n' print Superheroes.superheroes[y] print Superheroes.superheroes[z] print 'Complete the team by entering two more superheroes\n' string1 = raw_input() string2 = raw_input() count1 = 0 while count1 <= 11 and string1 != Superheroes.superheroes[ count1]: #compares with the list of superheroes count1 += 1 count2 = 0 while count2 <= 11 and string2 != Superheroes.superheroes[count2]: count2 += 1 a = Rating.strength(y) b = Rating.strength(z) c = Rating.strength(count1) d = Rating.strength(count2) Effective_Strength = Calculate.average(a, b, c, d) print 'Effective strength of superhero team:', Effective_Strength if Effective_Strength >= 8: print 'Congratulations' else: print 'You Lose' print 'End of game'
/ Get the top 4 movie predictions for user 4169 val topRecsForUser = model.recommendProducts(4169, 5) // get movie titles to show with recommendations val movieTitles=moviesDF.map(array => (array(0), array(1))). collectAsMap() // print out top recommendations for user 4169 with titles topRecsForUser.map(rating => (movieTitles( rating.product), rating.rating)).foreach(println) ##Model Evaluation / get user product pair from testRatings val testUserProductRDD = testRatingsRDD.map { case Rating(user, product, rating) => (user, product) } // get predicted ratings to compare to test ratings val predictionsForTestRDD = model.predict(testUserProductRDD) predictionsForTestRDD.take(10).mkString("\n") / prepare predictions for comparison val predictionsKeyedByUserProductRDD = predictionsForTestRDD.map{ case Rating(user, product, rating) => ((user, product), rating) } // prepare test for comparison val testKeyedByUserProductRDD = testRatingsRDD.map{
def test_count(self): self.assertEqual(rating.rating_film(12), 'BIMBINGAN ORANG TUA')
def test_value(self): self.assertAlmostEqual(rating.rating_film(12), 'BIMBINGAN ORANG TUA')
def getDefaultRating(self): return Rating(self._initialMean, self._initialStandardDeviation)