一、个人简介
💖💖作者:计算机编程果茶熊 💙💙个人简介:曾长期从事计算机专业培训教学,担任过编程老师,同时本人也热爱上课教学,擅长Java、微信小程序、Python、Golang、安卓Android等多个IT方向。会做一些项目定制化开发、代码讲解、答辩教学、文档编写、也懂一些降重方面的技巧。平常喜欢分享一些自己开发中遇到的问题的解决办法,也喜欢交流技术,大家有技术代码这一块的问题可以问我! 💛💛想说的话:感谢大家的关注与支持! 💜💜 网站实战项目 安卓/小程序实战项目 大数据实战项目 计算机毕业设计选题 💕💕文末获取源码联系计算机编程果茶熊
二、系统介绍
开发语言:Python 后端框架:Django 前端:Vue 数据库:MySQL 系统架构:B/S 开发工具:PyCharm
基于Python Django框架开发的房地产数据分析平台,采用B/S架构设计,前端使用Vue框架构建交互界面,后端数据存储于MySQL数据库中。该系统专注新房市场数据的收集、整理和智能分析,通过集成线性回归算法实现房价走势预测功能。系统提供完整的用户管理体系,支持多角色权限控制,确保数据访问的安全性和规范性。广州新房数据管理模块负责房源信息的录入、更新和维护,涵盖房屋位置、面积、价格、配套设施等关键属性。线性回归预测管理是系统的核心功能,通过历史交易数据和市场指标,运用机器学习算法对未来房价趋势进行科学预测。系统资讯管理模块提供房地产市场动态、政策解读和行业分析等信息服务。
三、视频解说
四、部分功能展示
五、部分代码展示
from pyspark.sql import SparkSession
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import StandardScaler
import numpy as np
import pandas as pd
import json
from datetime import datetime, timedelta
from .models import HouseData, UserProfile, PredictionResult
spark = SparkSession.builder.appName("HousePriceAnalysis").config("spark.sql.adaptive.enabled", "true").getOrCreate()
@csrf_exempt
def house_data_analysis(request):
if request.method == 'POST':
data = json.loads(request.body)
district = data.get('district', '')
start_date = data.get('start_date')
end_date = data.get('end_date')
house_queryset = HouseData.objects.filter(district=district, created_date__range=[start_date, end_date])
house_data_list = []
for house in house_queryset:
house_data_list.append({
'id': house.id,
'price': house.price,
'area': house.area,
'location': house.location,
'floor': house.floor,
'age': house.age,
'subway_distance': house.subway_distance,
'school_distance': house.school_distance
})
df = pd.DataFrame(house_data_list)
if not df.empty:
spark_df = spark.createDataFrame(df)
spark_df.createOrReplaceTempView("house_data")
avg_price = spark.sql("SELECT AVG(price) as avg_price FROM house_data").collect()[0]['avg_price']
price_distribution = spark.sql("SELECT CASE WHEN price < 30000 THEN '低价区间' WHEN price BETWEEN 30000 AND 50000 THEN '中价区间' ELSE '高价区间' END as price_range, COUNT(*) as count FROM house_data GROUP BY CASE WHEN price < 30000 THEN '低价区间' WHEN price BETWEEN 30000 AND 50000 THEN '中价区间' ELSE '高价区间' END").collect()
correlation_data = spark.sql("SELECT CORR(price, area) as price_area_corr, CORR(price, floor) as price_floor_corr, CORR(price, subway_distance) as price_subway_corr FROM house_data").collect()[0]
monthly_trend = spark.sql("SELECT MONTH(created_date) as month, AVG(price) as avg_monthly_price FROM house_data GROUP BY MONTH(created_date) ORDER BY month").collect()
area_analysis = spark.sql("SELECT CASE WHEN area < 80 THEN '小户型' WHEN area BETWEEN 80 AND 120 THEN '中户型' ELSE '大户型' END as area_type, AVG(price) as avg_price, COUNT(*) as count FROM house_data GROUP BY CASE WHEN area < 80 THEN '小户型' WHEN area BETWEEN 80 AND 120 THEN '中户型' ELSE '大户型' END").collect()
result = {
'avg_price': round(avg_price, 2),
'price_distribution': [{'range': row['price_range'], 'count': row['count']} for row in price_distribution],
'correlation': {
'price_area': round(correlation_data['price_area_corr'], 3),
'price_floor': round(correlation_data['price_floor_corr'], 3),
'price_subway': round(correlation_data['price_subway_corr'], 3)
},
'monthly_trend': [{'month': row['month'], 'price': round(row['avg_monthly_price'], 2)} for row in monthly_trend],
'area_analysis': [{'type': row['area_type'], 'avg_price': round(row['avg_price'], 2), 'count': row['count']} for row in area_analysis],
'total_count': len(house_data_list)
}
return JsonResponse({'status': 'success', 'data': result})
else:
return JsonResponse({'status': 'error', 'message': '未找到符合条件的数据'})
@csrf_exempt
def price_prediction_model(request):
if request.method == 'POST':
data = json.loads(request.body)
area = float(data.get('area'))
floor = int(data.get('floor'))
age = int(data.get('age'))
subway_distance = float(data.get('subway_distance'))
school_distance = float(data.get('school_distance'))
district = data.get('district')
user_id = data.get('user_id')
training_data = HouseData.objects.filter(district=district).values_list('area', 'floor', 'age', 'subway_distance', 'school_distance', 'price')
if len(training_data) < 10:
return JsonResponse({'status': 'error', 'message': '训练数据不足,无法进行预测'})
X_train = np.array([[item[0], item[1], item[2], item[3], item[4]] for item in training_data])
y_train = np.array([item[5] for item in training_data])
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
model = LinearRegression()
model.fit(X_train_scaled, y_train)
X_predict = np.array([[area, floor, age, subway_distance, school_distance]])
X_predict_scaled = scaler.transform(X_predict)
predicted_price = model.predict(X_predict_scaled)[0]
confidence_score = model.score(X_train_scaled, y_train)
feature_importance = {
'area_weight': abs(model.coef_[0]),
'floor_weight': abs(model.coef_[1]),
'age_weight': abs(model.coef_[2]),
'subway_weight': abs(model.coef_[3]),
'school_weight': abs(model.coef_[4])
}
price_range = {
'min_price': predicted_price * 0.9,
'max_price': predicted_price * 1.1,
'predicted_price': predicted_price
}
similar_houses = HouseData.objects.filter(district=district, area__range=[area*0.9, area*1.1], floor__range=[floor-2, floor+2]).order_by('?')[:5]
similar_list = [{'id': h.id, 'price': h.price, 'area': h.area, 'location': h.location} for h in similar_houses]
prediction_result = PredictionResult.objects.create(
user_id=user_id,
district=district,
input_area=area,
input_floor=floor,
input_age=age,
predicted_price=predicted_price,
confidence_score=confidence_score,
prediction_date=datetime.now()
)
return JsonResponse({
'status': 'success',
'predicted_price': round(predicted_price, 2),
'confidence_score': round(confidence_score, 3),
'price_range': {k: round(v, 2) for k, v in price_range.items()},
'feature_importance': {k: round(v, 4) for k, v in feature_importance.items()},
'similar_houses': similar_list,
'prediction_id': prediction_result.id
})
@csrf_exempt
def user_management_system(request):
if request.method == 'POST':
action = request.POST.get('action')
if action == 'register':
username = request.POST.get('username')
email = request.POST.get('email')
password = request.POST.get('password')
phone = request.POST.get('phone')
if User.objects.filter(username=username).exists():
return JsonResponse({'status': 'error', 'message': '用户名已存在'})
if User.objects.filter(email=email).exists():
return JsonResponse({'status': 'error', 'message': '邮箱已被注册'})
user = User.objects.create_user(username=username, email=email, password=password)
user_profile = UserProfile.objects.create(
user=user,
phone=phone,
registration_date=datetime.now(),
last_login_date=datetime.now(),
search_count=0,
prediction_count=0,
user_type='普通用户',
status='active'
)
return JsonResponse({'status': 'success', 'message': '注册成功', 'user_id': user.id})
elif action == 'login':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
profile = UserProfile.objects.get(user=user)
profile.last_login_date = datetime.now()
profile.save()
user_data = {
'user_id': user.id,
'username': user.username,
'email': user.email,
'phone': profile.phone,
'user_type': profile.user_type,
'search_count': profile.search_count,
'prediction_count': profile.prediction_count,
'registration_date': profile.registration_date.strftime('%Y-%m-%d')
}
return JsonResponse({'status': 'success', 'message': '登录成功', 'user_data': user_data})
else:
return JsonResponse({'status': 'error', 'message': '账户已被禁用'})
else:
return JsonResponse({'status': 'error', 'message': '用户名或密码错误'})
elif action == 'update_profile':
user_id = request.POST.get('user_id')
new_phone = request.POST.get('phone')
new_email = request.POST.get('email')
user = User.objects.get(id=user_id)
profile = UserProfile.objects.get(user=user)
if new_email and new_email != user.email:
if User.objects.filter(email=new_email).exclude(id=user_id).exists():
return JsonResponse({'status': 'error', 'message': '邮箱已被其他用户使用'})
user.email = new_email
user.save()
if new_phone:
profile.phone = new_phone
profile.save()
return JsonResponse({'status': 'success', 'message': '资料更新成功'})
elif action == 'get_user_statistics':
user_id = request.POST.get('user_id')
profile = UserProfile.objects.get(user_id=user_id)
recent_predictions = PredictionResult.objects.filter(user_id=user_id).order_by('-prediction_date')[:10]
prediction_history = [{'date': p.prediction_date.strftime('%Y-%m-%d'), 'district': p.district, 'predicted_price': p.predicted_price} for p in recent_predictions]
monthly_activity = PredictionResult.objects.filter(user_id=user_id, prediction_date__gte=datetime.now()-timedelta(days=30)).count()
favorite_districts = PredictionResult.objects.filter(user_id=user_id).values('district').annotate(count=Count('district')).order_by('-count')[:3]
statistics = {
'total_predictions': profile.prediction_count,
'total_searches': profile.search_count,
'monthly_activity': monthly_activity,
'prediction_history': prediction_history,
'favorite_districts': [d['district'] for d in favorite_districts],
'account_age': (datetime.now().date() - profile.registration_date.date()).days
}
return JsonResponse({'status': 'success', 'statistics': statistics})
六、部分文档展示
七、END
💕💕文末获取源码联系计算机编程果茶熊