row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
42,970
|
#include<stdio.h>
struct fcfs{
int totaltime;
int bursttime;
int waitingtime;
}p[10];
void main(){
int n;
printf("Enter the number of processes");
scanf("%d",&n);
int i=0;
printf("Enter the burst time of the following\n");
while(i<n){
printf("Enter the process burst time\n");
scanf("%d",&p[i].bursttime);
i++;
}
int ar[n];
int k=0;
int temp;
for(int i=0;i<n;i++){
ar[i]=p[i].bursttime;
}
for(int h=0;h<n-1;h+1){
for(int i=0;i<n-1;i++){
if(ar[i]<ar[i+1]){
temp=ar[i];
ar[i]=ar[i+1];
ar[i+1]=temp;
}
}
}
int j=0;
int waitingtime1=0;
for(int i=0;i<n;i++){
if(p[i].bursttime==ar[i]){
p[i].waitingtime=waitingtime1;
printf("The waiting time of process %d is %d \n",i+1,p[i].waitingtime);
p[i].totaltime=p[i].bursttime+p[i].waitingtime;
printf("The turnaround time of process %d is %d \n",i+1,p[i].totaltime);
waitingtime1=p[i].totaltime;
j=p[i].waitingtime+j;
}}
float average=j/n;
printf("The average waiting time is %f \n",average);
}
debug the error
|
d436a037dc8b472dd524437112a0bf58
|
{
"intermediate": 0.410580575466156,
"beginner": 0.44763416051864624,
"expert": 0.14178527891635895
}
|
42,971
|
#include<stdio.h>
struct sjfs{
int totaltime;
int bursttime;
int waitingtime;
}p[10];
void main(){
int n;
printf("Enter the number of processes");
scanf("%d",&n);
int i=0;
printf("Enter the burst time of the following\n");
while(i<n){
printf("Enter the process burst time\n");
scanf("%d",&p[i].bursttime);
i++;
}
int ar[n];
int k=0;
int temp;
for(int i=0;i<n;i++){
ar[i]=p[i].bursttime;
}
for(int h=0;h<n-1;h+1){
for(int i=0;i<n-1;i++){
if(ar[i]<ar[i+1]){
temp=ar[i];
ar[i]=ar[i+1];
ar[i+1]=temp;
}
}
}
int j=0;
int waitingtime1=0;
for(int i=0;i<n;i++){
if(p[i].bursttime==ar[i]){
p[i].waitingtime=waitingtime1;
printf("The waiting time of process %d is %d \n",i+1,p[i].waitingtime);
p[i].totaltime=p[i].bursttime+p[i].waitingtime;
printf("The turnaround time of process %d is %d \n",i+1,p[i].totaltime);
waitingtime1=p[i].totaltime;
j=p[i].waitingtime+j;
}}
float average=j/n;
printf("The average waiting time is %f \n",average);
} debug the error short job
|
7d36358e720ac05148438939875699e7
|
{
"intermediate": 0.4310765862464905,
"beginner": 0.40437379479408264,
"expert": 0.1645495742559433
}
|
42,972
|
On the incident form when form loads want to show populate alert message assigned to manager location? How to achieve this?
|
b99796c8a1a90efc7b4630e556755bee
|
{
"intermediate": 0.4416297972202301,
"beginner": 0.1708727926015854,
"expert": 0.3874974846839905
}
|
42,973
|
On the incident form when form loads want to show populate alert message assigned to manager location? How to achieve this? Servicenow
|
03125f788d9dc21b84c24484c01e39b8
|
{
"intermediate": 0.47910982370376587,
"beginner": 0.1621679663658142,
"expert": 0.3587222099304199
}
|
42,974
|
best qf pf qs and ps configuration for ecommerce search using solr
|
34159e766d66c3dc5b8d5d472b151789
|
{
"intermediate": 0.22957612574100494,
"beginner": 0.2427176684141159,
"expert": 0.5277061462402344
}
|
42,975
|
Prompt
Heapsort is a widely-used sorting algorithm. Please write an introduction to Heapsort including its basic idea, main steps, complexity and important properties. Write some pseudo code to illustrate the process of Heapsort.
|
b66b1a7e24bebc8e514d9d785ceef88f
|
{
"intermediate": 0.1292683482170105,
"beginner": 0.1343165934085846,
"expert": 0.7364150881767273
}
|
42,976
|
Please improve the model's response by rewriting or editing it
Sure, I can write an introduction to Heapsort. Heapsort is a sorting algorithm based on the heap data structure. Heap is a tree-based data structure, where
Either each parent node’s value is larger or equal to its child nodes, which we call a min heap
Or each parent node’s value is smaller or equal to its child nodes, which we call a max heap
The basic idea of Heapsort is “divide and conquer”, where we divide the array we want to sort into two parts, of which one is sorted and the other unsorted. We will find the smallest or largest elements in the unsorted part and insert it into the sorted part, until the unsorted part is empty. The main steps are:
Create a heap out of the whole array.
Swap the first element, which is either the largest or the smallest element, depending on the type of the heap, with the last element. Now the size of the sorted part grows by 1 and the unsorted part shrinks by 1.
Adjust the first element (previously the last element at step 2) to the correct position.
Repeat steps 2 and 3 until there is no unsorted part.
The complexity of each step is:
Create a heap. Time complexity O(n log n), space complexity O(1)
Repeat the sorting iterations. Time complexity O(n log n), space complexity O(1)
Therefore, the overall time complexity is O(n log n), space complexity O(1).
The most important properties of Heapsort include:
optimal time complexity which is O(n log n)
It’s in-place, with space complexity O(1)
It’s unstable, which means that the relative order of the equal elements in the original array is not preserved.
Heapsort is usually faster than quicksort, which has a worst-case time complexity of O(n^2)
Here is some pseudo code for Heapsort:
Pseudocode for Heapsort
Heapify a subtree rooted at node i to ensure it satisfies the max-heap property.
This assumes that the left and right subtrees of i are max-heaps.
n is the total number of elements in the array.
procedure heapify(arr, n, i):
largest = i
left_child = 2 * i + 1
right_child = 2 * i + 2
|
d55de3c1034d6a7f28a5d7cf73549d47
|
{
"intermediate": 0.33314448595046997,
"beginner": 0.2196039855480194,
"expert": 0.44725149869918823
}
|
42,977
|
I will give you a peice of a python code and a asociated issue with it, read it analys it and suggest me the chage to the issue and rewrite the code
code -
import random
def coinFlip():
if random.randint(0, 1):
return 'Heads!'
else:
return 'Tails!'
return 'The coin landed on its edge!'
print(coinFlip())
smell -
return 'The coin landed on its edge!' line
|
b548ad12cafd757ea0d6cf536f64c96a
|
{
"intermediate": 0.30182257294654846,
"beginner": 0.46533605456352234,
"expert": 0.2328413873910904
}
|
42,978
|
I have a code understand the code and convert the code in OOP concept class form.
import cv2
import pandas as pd
import json
from thefuzz import fuzz
from itertools import product
used_bounding_boxes = {}
def preprocess_entity(entity):
try:
token = entity.replace(",", "").strip()
return token
except:
pass
def calculate_proximity_score(box_a, box_b):
vertical_overlap = max(0, min(box_a["bottom"], box_b["bottom"]) - max(box_a["top"], box_b["top"]))
vertical_distance = 0 if vertical_overlap > 0 else min(abs(box_a["top"] - box_b["bottom"]), abs(box_a["bottom"] - box_b["top"]))
horizontal_overlap = max(0, min(box_a["right"], box_b["right"]) - max(box_a["left"], box_b["left"]))
horizontal_distance = 0 if horizontal_overlap > 0 else abs(box_a["right"] - box_b["left"])
return horizontal_distance + 2 * vertical_distance
def is_nearby(box_a, box_b, max_line_difference=5, max_distance=100):
return calculate_proximity_score(box_a, box_b) <= max_distance + 2 * max_line_difference
def merge_boxes(boxes):
min_left = min(box["left"] for box in boxes)
max_right = max(box["right"] for box in boxes)
min_top = min(box["top"] for box in boxes)
max_bottom = max(box["bottom"] for box in boxes)
return {"left": min_left, "right": max_right, "top": min_top, "bottom": max_bottom}
def find_potential_matches(dataframe, token, threshold=75):
potential_matches = []
for _, row in dataframe.iterrows():
ocr_text = preprocess_entity(row["text"])
score = fuzz.ratio(token, ocr_text)
if score > threshold:
potential_matches.append({
"box": {"left": row["left"], "right": row["right"], "top": row["top"], "bottom": row["bottom"]},
"score": score
})
return potential_matches
def find_best_sequence_heuristic(matches_list):
if not matches_list or len(matches_list[0]) == 0:
return []
best_sequence = [min(matches_list[0], key=lambda match: match["score"])]
for next_matches in matches_list[1:]:
current_box = best_sequence[-1]["box"]
next_best_match = min(next_matches, key=lambda match: calculate_proximity_score(current_box, match["box"]))
best_sequence.append(next_best_match)
return best_sequence
def process_single_token_entity(dataframe, entity, threshold=75):
global used_bounding_boxes
best_match = None
best_score = threshold
entity = preprocess_entity(entity)
if entity not in used_bounding_boxes:
used_bounding_boxes[entity] = []
for _, row in dataframe.iterrows():
ocr_text = preprocess_entity(row['text'])
score = fuzz.ratio(entity, ocr_text)
current_box = {'left': row['left'], 'right': row['right'], 'top': row['top'], 'bottom': row['bottom']}
if score > best_score and current_box not in used_bounding_boxes[entity]:
best_score = score
best_match = current_box
if best_match:
used_bounding_boxes[entity].append(best_match)
return best_match
def box_overlap(box1, box2):
"""Check if there’s any overlap in any coordinate between two boxes."""
return box1["left"] == box2["left"] or box1["right"] == box2["right"]
def all_boxes_unique(sequence_boxes, used_boxes):
"""Ensure no part of the boxes in sequence_boxes overlaps with any box in used_boxes."""
for seq_box in sequence_boxes:
for used_box in used_boxes:
if box_overlap(seq_box, used_box):
return False
return True
def get_next_best_sequence(all_potential_matches, previous_matches, entity):
"""
Try to find the next best sequence of matches that hasn’t used any part of the bounding boxes.
"""
# Flatten the list of used boxes for easier comparison.
used_boxes = [box for sequence in previous_matches.get(entity, []) for box in sequence]
for sequence in product(*all_potential_matches):
sequence_boxes = [match["box"] for match in sequence]
if all_boxes_unique(sequence_boxes, used_boxes):
return sequence # Found a sequence where no box part has been used before
return None # No unique sequence found
#working code
# def process_multi_token_entity(dataframe, entity, threshold=85):
# global used_bounding_boxes
# # if entity not in used_bounding_boxes:
# # used_bounding_boxes[entity] = []
# tokens = entity.split()
# all_potential_matches = [find_potential_matches(dataframe, token, threshold) for token in tokens]
# # Ensuring all tokens have at least one match
# if not all(matches for matches in all_potential_matches):
# return None
# # This assumes used_bounding_boxes[entity] holds lists of used sequences of boxes (not merged boxes)
# previous_matches = used_bounding_boxes.get(entity, [])
# next_best_sequence = get_next_best_sequence(all_potential_matches, used_bounding_boxes, entity)
# if next_best_sequence:
# new_boxes_sequence = [match["box"] for match in next_best_sequence]
# merged_box = merge_boxes(new_boxes_sequence)
# # If we found a new sequence, add it to the used sequences for this entity
# if entity not in used_bounding_boxes:
# used_bounding_boxes[entity] = []
# used_bounding_boxes[entity].append(new_boxes_sequence)
# return merged_box
# return None
def process_multi_token_entity(dataframe, entity, threshold=75, max_distance=100, max_line_difference=3):
global used_bounding_boxes
tokens = entity.split()
all_potential_matches = [find_potential_matches(dataframe, token, threshold) for token in tokens]
if not all(matches for matches in all_potential_matches):
return None
if entity not in used_bounding_boxes:
used_bounding_boxes[entity] = []
previous_matches = used_bounding_boxes.get(entity, [])
all_sequences = list(product(*all_potential_matches)) # Create all possible sequences
valid_sequences = [] # List to hold sequences that meet the is_nearby condition
for sequence in all_sequences:
sequence_boxes = [match["box"] for match in sequence]
sequence_is_valid = True
for i in range(len(sequence_boxes) - 1):
if not is_nearby(sequence_boxes[i], sequence_boxes[i + 1], max_line_difference, max_distance):
sequence_is_valid = False
break
if sequence_is_valid:
valid_sequences.append(sequence)
# Sort valid sequences by their cumulative proximity score, to prioritize those with boxes closer together
valid_sequences = sorted(valid_sequences, key=lambda seq: sum(calculate_proximity_score(seq[i]["box"], seq[i+1]["box"]) for i in range(len(seq) - 1)))
next_best_sequence = None
for sequence in valid_sequences:
sequence_boxes = [match["box"] for match in sequence]
if all_boxes_unique(sequence_boxes, [box for sublist in previous_matches for box in sublist]):
next_best_sequence = sequence
break
if next_best_sequence:
new_boxes_sequence = [match["box"] for match in next_best_sequence]
merged_box = merge_boxes(new_boxes_sequence)
used_bounding_boxes[entity].append(new_boxes_sequence)
return merged_box
return None
def draw_bounding_boxes(image_path, bounding_boxes, entity_names):
image = cv2.imread(image_path)
font = cv2.FONT_HERSHEY_SIMPLEX
for box, name in zip(bounding_boxes, entity_names):
if box:
cv2.rectangle(image, (box["left"], box["top"]), (box["right"], box["bottom"]), (0, 255, 0), 2)
cv2.putText(image, name, (box["left"], max(box["top"] - 10, 0)), font, 0.5, (0, 0, 255), 2)
cv2.imwrite("annotated_image_using_dp1119.jpg", image)
def main(json_path, csv_path, image_path):
with open(json_path, "r") as f:
data = json.load(f)
dataframe = pd.read_csv(csv_path)
bounding_boxes = []
entity_names = []
# Existing processing for non-special sections
special_sections = ["amounts_and_tax","Payment Details"] # Define special handling cases here
for section in ["invoice_details", "Payment Details", "amounts_and_tax"]:
entities = data.get(section, {})
# Check if the current section needs special handling
if section not in special_sections:
for entity_name, entity_value in entities.items():
entity_value_no_comma = preprocess_entity(entity_value)
if " " in entity_value_no_comma:
box = process_multi_token_entity(dataframe, entity_value_no_comma)
else:
box = process_single_token_entity(dataframe, entity_value_no_comma)
if box:
bounding_boxes.append(box)
entity_names.append(entity_name)
else:
# Special handling for "amounts_and_tax" section
reversed_dataframe = dataframe.iloc[::-1].reset_index(drop=True) # Reverse the dataframe
for entity_name, entity_value in entities.items():
entity_value_no_comma = preprocess_entity(entity_value)
if " " in entity_value_no_comma:
# Use the reversed_dataframe for multi-token entities
box = process_multi_token_entity(reversed_dataframe, entity_value_no_comma)
else:
# Use the reversed_dataframe for single-token entities
box = process_single_token_entity(reversed_dataframe, entity_value_no_comma)
if box:
bounding_boxes.append(box)
entity_names.append(entity_name)
draw_bounding_boxes(image_path, bounding_boxes, entity_names)
main("/home/ritik1s/Desktop/bbox_issues/temp_GPT/row_skip.json", "/home/ritik1s/Desktop/bbox_issues/temp_GPT/check.csv", "/home/ritik1s/Desktop/bbox_issues/temp_GPT/check.jpeg")
|
78b31291ab1d0749a4aecaf89c6aed47
|
{
"intermediate": 0.3812512159347534,
"beginner": 0.3363266587257385,
"expert": 0.28242212533950806
}
|
42,979
|
我们希望基于
open class BaseBlockDataSource : IBlockDataSource {
private val dataFlows = ConcurrentHashMap<KClass<*>, MutableStateFlow<*>>()
// 新增映射,用于追踪与每个flow相关联的收集作业
private val flowCollectJobs = ConcurrentHashMap<KClass<*>, MutableList<Job>>()
private val coroutineScope = CoroutineScope(Dispatchers.Default) // 使用默认调度器,用于收集作业
override fun init() {
// 初始化工作
}
override fun <T : Any> registerFlow(klass: KClass<out T>, flow: MutableStateFlow<T>) {
if (!dataFlows.containsKey(klass)) {
dataFlows[klass] = flow
}
}
override fun <T : Any> unRegisterFlow(klass: KClass<out T>) {
if (dataFlows.containsKey(klass)) {
// 取消与该flow有关的监听
flowCollectJobs[klass]?.forEach {
it.cancel()
}
flowCollectJobs.remove(klass)
dataFlows.remove(klass)
}
}
@Suppress("UNCHECKED_CAST")
override fun <T : Any> updateData(klass: KClass<T>, data: T) {
(dataFlows[klass] as? MutableStateFlow<T>)?.updateValue(data)
}
@Suppress("UNCHECKED_CAST")
override fun destroy() {
dataFlows.values.forEach { flow ->
(flow as? MutableStateFlow<Any?>)?.value = null// 重置为null或进行其他清理工作
}
flowCollectJobs.values.forEach { jobs -> jobs.forEach { it.cancel() } } // 取消所有收集作业
dataFlows.clear()
flowCollectJobs.clear()
}
override fun <T : Any> getDataFlow(klass: KClass<T>, initialValue: T?): Flow<T>? {
return dataFlows[klass]?.let { flow ->
if (initialValue != null && flow.value == null) {
// 如果流不存在且有初始值,则创建并注册新的流
val newFlow = MutableStateFlow(initialValue)
dataFlows[klass] = newFlow
newFlow
} else {
flow as? Flow<T>
}
}
}
override fun <T : Any> collectFlow(klass: KClass<T>, flow: MutableStateFlow<T>, collector: suspend (T) -> Unit) {
val job = coroutineScope.launch {
flow.collect(collector)
}
val jobs = flowCollectJobs.getOrPut(klass) { mutableListOf() }
jobs.add(job)
}
private fun <T> MutableStateFlow<T>.updateValue(newValue: T) {
this.value = newValue
}
override fun <T> interceptDataFlow(interceptor: BlockDataInterceptor<T>) {
TODO("Not yet implemented")
}
这个类实现一个代理的中间类,他的主要职责包括帮助业务方使用 datasource的一些能力,同时它会实现一些请求方法或者自己监听一些事件,然后触发datasource的数据流更新
|
583c85a9879a69028fb7340a3b3f3ff8
|
{
"intermediate": 0.3040710687637329,
"beginner": 0.5160355567932129,
"expert": 0.17989343404769897
}
|
42,980
|
var relGlide = new GlideRecord("cmdb_rel_ci);
var queryString = "child.ip_address=" +current.variables.ip_address;
relGlide.addEncodedQuery(queryString);
relGlide.query();
while (relGlide.next()){
{
i have his code query to be run on catalog item for a reference variable and f(relGlide.parent.operational_status ==1) of parents record found with the query, capture the name of all records and show them in alert window servicenow
|
cb9a1db4ed5897fbfc486c1c6f635941
|
{
"intermediate": 0.5097412467002869,
"beginner": 0.19563737511634827,
"expert": 0.29462140798568726
}
|
42,981
|
secure way to create invitation on client and claim it from the server written in typescript
|
8cf7997cb41b299f35124d7ce791d9e3
|
{
"intermediate": 0.23481212556362152,
"beginner": 0.36673688888549805,
"expert": 0.3984510004520416
}
|
42,982
|
I want to extract tags - "Satisfied" or "Not Satisfied" from a string in python irrepective of tags
|
3b740b66e6f3182dd8d47fcd2ab2d8f3
|
{
"intermediate": 0.4484120011329651,
"beginner": 0.11965880542993546,
"expert": 0.43192917108535767
}
|
42,983
|
Create one class named "BoundingBoxFInder" and cover all the function in that class
import cv2
import pandas as pd
import json
from thefuzz import fuzz
from itertools import product
used_bounding_boxes = {}
def preprocess_entity(entity):
try:
token = entity.replace(",", "").strip()
return token
except:
pass
def calculate_proximity_score(box_a, box_b):
vertical_overlap = max(0, min(box_a["bottom"], box_b["bottom"]) - max(box_a["top"], box_b["top"]))
vertical_distance = 0 if vertical_overlap > 0 else min(abs(box_a["top"] - box_b["bottom"]), abs(box_a["bottom"] - box_b["top"]))
horizontal_overlap = max(0, min(box_a["right"], box_b["right"]) - max(box_a["left"], box_b["left"]))
horizontal_distance = 0 if horizontal_overlap > 0 else abs(box_a["right"] - box_b["left"])
return horizontal_distance + 2 * vertical_distance
def is_nearby(box_a, box_b, max_line_difference=5, max_distance=100):
return calculate_proximity_score(box_a, box_b) <= max_distance + 2 * max_line_difference
def merge_boxes(boxes):
min_left = min(box["left"] for box in boxes)
max_right = max(box["right"] for box in boxes)
min_top = min(box["top"] for box in boxes)
max_bottom = max(box["bottom"] for box in boxes)
return {"left": min_left, "right": max_right, "top": min_top, "bottom": max_bottom}
def find_potential_matches(dataframe, token, threshold=75):
potential_matches = []
for _, row in dataframe.iterrows():
ocr_text = preprocess_entity(row["text"])
score = fuzz.ratio(token, ocr_text)
if score > threshold:
potential_matches.append({
"box": {"left": row["left"], "right": row["right"], "top": row["top"], "bottom": row["bottom"]},
"score": score
})
return potential_matches
def find_best_sequence_heuristic(matches_list):
if not matches_list or len(matches_list[0]) == 0:
return []
best_sequence = [min(matches_list[0], key=lambda match: match["score"])]
for next_matches in matches_list[1:]:
current_box = best_sequence[-1]["box"]
next_best_match = min(next_matches, key=lambda match: calculate_proximity_score(current_box, match["box"]))
best_sequence.append(next_best_match)
return best_sequence
def process_single_token_entity(dataframe, entity, threshold=75):
global used_bounding_boxes
best_match = None
best_score = threshold
entity = preprocess_entity(entity)
if entity not in used_bounding_boxes:
used_bounding_boxes[entity] = []
for _, row in dataframe.iterrows():
ocr_text = preprocess_entity(row['text'])
score = fuzz.ratio(entity, ocr_text)
current_box = {'left': row['left'], 'right': row['right'], 'top': row['top'], 'bottom': row['bottom']}
if score > best_score and current_box not in used_bounding_boxes[entity]:
best_score = score
best_match = current_box
if best_match:
used_bounding_boxes[entity].append(best_match)
return best_match
def box_overlap(box1, box2):
"""Check if there’s any overlap in any coordinate between two boxes."""
return box1["left"] == box2["left"] or box1["right"] == box2["right"]
def all_boxes_unique(sequence_boxes, used_boxes):
"""Ensure no part of the boxes in sequence_boxes overlaps with any box in used_boxes."""
for seq_box in sequence_boxes:
for used_box in used_boxes:
if box_overlap(seq_box, used_box):
return False
return True
def get_next_best_sequence(all_potential_matches, previous_matches, entity):
"""
Try to find the next best sequence of matches that hasn’t used any part of the bounding boxes.
"""
# Flatten the list of used boxes for easier comparison.
used_boxes = [box for sequence in previous_matches.get(entity, []) for box in sequence]
for sequence in product(*all_potential_matches):
sequence_boxes = [match["box"] for match in sequence]
if all_boxes_unique(sequence_boxes, used_boxes):
return sequence # Found a sequence where no box part has been used before
return None # No unique sequence found
#working code
# def process_multi_token_entity(dataframe, entity, threshold=85):
# global used_bounding_boxes
# # if entity not in used_bounding_boxes:
# # used_bounding_boxes[entity] = []
# tokens = entity.split()
# all_potential_matches = [find_potential_matches(dataframe, token, threshold) for token in tokens]
# # Ensuring all tokens have at least one match
# if not all(matches for matches in all_potential_matches):
# return None
# # This assumes used_bounding_boxes[entity] holds lists of used sequences of boxes (not merged boxes)
# previous_matches = used_bounding_boxes.get(entity, [])
# next_best_sequence = get_next_best_sequence(all_potential_matches, used_bounding_boxes, entity)
# if next_best_sequence:
# new_boxes_sequence = [match["box"] for match in next_best_sequence]
# merged_box = merge_boxes(new_boxes_sequence)
# # If we found a new sequence, add it to the used sequences for this entity
# if entity not in used_bounding_boxes:
# used_bounding_boxes[entity] = []
# used_bounding_boxes[entity].append(new_boxes_sequence)
# return merged_box
# return None
def process_multi_token_entity(dataframe, entity, threshold=75, max_distance=100, max_line_difference=3):
global used_bounding_boxes
tokens = entity.split()
all_potential_matches = [find_potential_matches(dataframe, token, threshold) for token in tokens]
if not all(matches for matches in all_potential_matches):
return None
if entity not in used_bounding_boxes:
used_bounding_boxes[entity] = []
previous_matches = used_bounding_boxes.get(entity, [])
all_sequences = list(product(*all_potential_matches)) # Create all possible sequences
valid_sequences = [] # List to hold sequences that meet the is_nearby condition
for sequence in all_sequences:
sequence_boxes = [match["box"] for match in sequence]
sequence_is_valid = True
for i in range(len(sequence_boxes) - 1):
if not is_nearby(sequence_boxes[i], sequence_boxes[i + 1], max_line_difference, max_distance):
sequence_is_valid = False
break
if sequence_is_valid:
valid_sequences.append(sequence)
# Sort valid sequences by their cumulative proximity score, to prioritize those with boxes closer together
valid_sequences = sorted(valid_sequences, key=lambda seq: sum(calculate_proximity_score(seq[i]["box"], seq[i+1]["box"]) for i in range(len(seq) - 1)))
next_best_sequence = None
for sequence in valid_sequences:
sequence_boxes = [match["box"] for match in sequence]
if all_boxes_unique(sequence_boxes, [box for sublist in previous_matches for box in sublist]):
next_best_sequence = sequence
break
if next_best_sequence:
new_boxes_sequence = [match["box"] for match in next_best_sequence]
merged_box = merge_boxes(new_boxes_sequence)
used_bounding_boxes[entity].append(new_boxes_sequence)
return merged_box
return None
def draw_bounding_boxes(image_path, bounding_boxes, entity_names):
image = cv2.imread(image_path)
font = cv2.FONT_HERSHEY_SIMPLEX
for box, name in zip(bounding_boxes, entity_names):
if box:
cv2.rectangle(image, (box["left"], box["top"]), (box["right"], box["bottom"]), (0, 255, 0), 2)
cv2.putText(image, name, (box["left"], max(box["top"] - 10, 0)), font, 0.5, (0, 0, 255), 2)
cv2.imwrite("annotated_image_using_dp1119.jpg", image)
def main(json_path, csv_path, image_path):
with open(json_path, "r") as f:
data = json.load(f)
dataframe = pd.read_csv(csv_path)
bounding_boxes = []
entity_names = []
# Existing processing for non-special sections
special_sections = ["amounts_and_tax","Payment Details"] # Define special handling cases here
for section in ["invoice_details", "Payment Details", "amounts_and_tax"]:
entities = data.get(section, {})
# Check if the current section needs special handling
if section not in special_sections:
for entity_name, entity_value in entities.items():
entity_value_no_comma = preprocess_entity(entity_value)
if " " in entity_value_no_comma:
box = process_multi_token_entity(dataframe, entity_value_no_comma)
else:
box = process_single_token_entity(dataframe, entity_value_no_comma)
if box:
bounding_boxes.append(box)
entity_names.append(entity_name)
else:
# Special handling for "amounts_and_tax" section
reversed_dataframe = dataframe.iloc[::-1].reset_index(drop=True) # Reverse the dataframe
for entity_name, entity_value in entities.items():
entity_value_no_comma = preprocess_entity(entity_value)
if " " in entity_value_no_comma:
# Use the reversed_dataframe for multi-token entities
box = process_multi_token_entity(reversed_dataframe, entity_value_no_comma)
else:
# Use the reversed_dataframe for single-token entities
box = process_single_token_entity(reversed_dataframe, entity_value_no_comma)
if box:
bounding_boxes.append(box)
entity_names.append(entity_name)
draw_bounding_boxes(image_path, bounding_boxes, entity_names)
main("/home/ritik1s/Desktop/bbox_issues/temp_GPT/row_skip.json", "/home/ritik1s/Desktop/bbox_issues/temp_GPT/check.csv", "/home/ritik1s/Desktop/bbox_issues/temp_GPT/check.jpeg")
|
4c8480469d95b7018a0676e3048f7891
|
{
"intermediate": 0.38629549741744995,
"beginner": 0.40669921040534973,
"expert": 0.20700526237487793
}
|
42,984
|
In script include if i found sysid then how to get short description value
|
1bb57bbcb7b1e32a8a4b733995a988d6
|
{
"intermediate": 0.36648035049438477,
"beginner": 0.29298365116119385,
"expert": 0.3405359983444214
}
|
42,985
|
python write loop that tries decoding a string in different charsets. it should catch exception and try another if the current tested fails
|
1196aa4eacdc57059eb915a8a5a5da9b
|
{
"intermediate": 0.37375855445861816,
"beginner": 0.3268009424209595,
"expert": 0.2994404733181
}
|
42,986
|
python write loop that tries decoding a string in different charsets. it should catch exception and try another if the current tested fails
|
1a3b9fad5fc1a5de74d8eae1c90a5e97
|
{
"intermediate": 0.37375855445861816,
"beginner": 0.3268009424209595,
"expert": 0.2994404733181
}
|
42,987
|
in c++ what is linked list
|
60c5d68c51c1ef124b5b44e258de8cd7
|
{
"intermediate": 0.3522651791572571,
"beginner": 0.3130916655063629,
"expert": 0.3346431851387024
}
|
42,988
|
hi
|
b346142e5ad758e7db3aa13d0a95e036
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
42,989
|
I want to extract tags - “Satisfied” or “Not Satisfied” from a string in python irrepective of tags
To extract tags like “Satisfied” or “Not Satisfied” from a string in Python, regardless of where these tags are situated within the string or how they are capitalized, you can use regular expressions. Python’s re module is perfect for this kind of pattern matching and extraction.
Below is an example function that searches for both “Satisfied” and “Not Satisfied” in the input text. It assumes that the tags can appear in any case (e.g., lower, upper, title).
import re
def extract_satisfaction_tags(text):
# This regular expression looks for ‘satisfied’ or ‘not satisfied’ in a case-insensitive manner
pattern = re.compile(r’\b(not\s)?satisfied\b’, re.IGNORECASE)
matches = pattern.findall(text)
# Each match is a tuple because of the capturing group, transform it into a more readable form
tags = [’ '.join(match).strip() for match in matches]
# Print or return the tags based on your preference
return tags
# Example usage
text = “I am completely not satisfied with the service. However, later I felt somewhat satisfied.”
tags_found = extract_satisfaction_tags(text)
print(tags_found)
This function uses a regular expression with a basic pattern to find instances of “satisfied” or “not satisfied”, taking into account case-insensitivity (re.IGNORECASE). It returns these instances as a list. The \b in the pattern ensures that we are matching whole words only, thus avoiding partial matches like “dissatisfied” unless explicitly included in the pattern.
If there are more specific constraints (e.g., extracting only if the text appears within certain delimiters, or in a particular context), you’d need to adjust the regular expression accordingly.
This example combines both “Satisfied” and “Not Satisfied” into a single pattern for efficiency, and it showcases how to handle optional words in patterns (like “not” before “satisfied”) using (not\s)?, which makes "not " optional in the search.
there will be either satisfied or not satisfied in the string. Just check which one is present. I satisfied, make a flag - customer_satisfied = True else customer_satisfied = False
There will be either “Satisfied” tag or “Not Satisfied” tag present in the string not both. So, if you found “Satisfied” make a flag customer_satisfied and set it to True otherwise set it to False
|
8fd48c4361e9df2009bcf5fa2ab8587b
|
{
"intermediate": 0.5362439155578613,
"beginner": 0.15608511865139008,
"expert": 0.3076709806919098
}
|
42,990
|
A program below is a doubly linked program, define the listed functions follow the direction that i give on top of each function.
struct DEItem {
int val;
DEItem* prev;
DEItem* next;
// Feel free to add a constructor if you desire
};
class DEList {
public:
// Constructs an empty Double-Ended List
DEList();
// Destructor to clean-up memory of current list
~DEList();
// returns a Boolean 'true' if the list is empty
bool empty() const;
// returns number of items in the list
int size() const;
// returns front item or -1 if empty list
int front() const;
// returns back item or -1 if empty list
int back() const;
// Adds a new integer to the front of the list
void push_front(int new_val);
// Adds a new integer to the back of the list
void push_back(int new_val);
// Removes the front item of the list (if it exists)
void pop_front();
// Removes the back item of the list (if it exists)
void pop_back();
// Converts the contents of the list to a string with spaces between
// each element an NO trailing newline (and no space before the
// first element or after the last element)
std::string conv_to_string() const;
private:
// ADD your data members here:
DEItem* head;
DEItem* tail;
int Itemcount;
};
|
403d34678748fd2b4471f80bf4f80da4
|
{
"intermediate": 0.175200417637825,
"beginner": 0.6628226041793823,
"expert": 0.16197696328163147
}
|
42,991
|
In the below function 'select_action', the 'action_mean', from the computation 'action_mean, action_log_std = actor(state_tensor)' gives the result between -1,1. After that we are computing 'normal_dist' using the 'normal_dist = torch.distributions.Normal(action_mean, action_std), action = normal_dist.sample()', here we are getting the results in wide ranges of negative and positive sides, then after clipping the 'action' from normal distribution leads the action space values only in the boundaries either bounds_low or bounds_high, I am not getting the ranges of values between the bounds for all variables. what should we do now. Is there any method to rectify my existing problem or update me any new approach on actor, critic and select_action functions, to resolve my existing issue.
bounds_low = np.array([0.18e-6, 0.18e-6, 0.18e-6, 0.18e-6, 0.18e-6, 0.5e-6, 0.5e-6, 0.5e-6, 0.5e-6, 0.5e-6, 15e-6, 0.1e-12, 0.8])
bounds_high = np.array([0.2e-6, 0.2e-6, 0.2e-6, 0.2e-6, 0.2e-6, 50e-6, 50e-6, 50e-6, 50e-6, 50e-6, 30e-6, 10e-12, 1.4])
target_metrics = {
'Area': (1e-12, 1e-10),
'PowerDissipation': (0.005, 0.25),
'SlewRate': (20, 60),
'Gain': (70, 100),
'Bandwidth3dB': (30e3, 100e3),
'UnityGainFreq': (30e6, 100e6),
'PhaseMargin': (65, 90)
}
# Initialize Networks and Optimizers
state_size = 45 # State size, Normalized continuous variables (13), One-hot encoded regions (24), binary saturation state (1), normalized performance metrics (7)
action_size = 13 # Action size to tune the 13 variables
hidden_sizes_actor = [128, 128]
hidden_sizes_critic = [128, 128]
action_std_init = 0.5
learning_rate_actor = 1e-4
learning_rate_critic = 1e-3
# Define the Actor and Critic Networks
class ActorNetwork(nn.Module):
def __init__(self, state_size, action_size, hidden_sizes, action_std_init):
super(ActorNetwork, self).__init__()
self.fc_in = nn.Linear(state_size, hidden_sizes[0])
self.hidden_layers = nn.ModuleList()
for i in range(len(hidden_sizes)-1):
self.hidden_layers.append(nn.Linear(hidden_sizes[i], hidden_sizes[i+1]))
self.fc_out = nn.Linear(hidden_sizes[-1], action_size)
self.log_std = nn.Parameter(torch.ones(1, action_size) * torch.log(torch.tensor(action_std_init))) # Use log to ensure std > 0 # Parameter for exploration
#self.activation = nn.ReLU()
self.activation = nn.ELU() # Change ReLU to ELU
# Initialize weights
self.init_weights()
def forward(self, state):
x = self.activation(self.fc_in(state))
for hidden_layer in self.hidden_layers:
x = self.activation(hidden_layer(x))
action_mean = self.fc_out(x)
log_std = self.log_std.exp().expand_as(action_mean) # Ensure the right shape
return action_mean, log_std
def init_weights(self):
for m in self.modules():
if isinstance(m, nn.Linear):
nn.init.xavier_uniform_(m.weight) # Improved initialization
nn.init.constant_(m.bias, 0)
class CriticNetwork(nn.Module):
def __init__(self, state_size, hidden_sizes):
super(CriticNetwork, self).__init__()
self.fc_in = nn.Linear(state_size, hidden_sizes[0])
self.hidden_layers = nn.ModuleList()
for i in range(len(hidden_sizes)-1):
self.hidden_layers.append(nn.Linear(hidden_sizes[i], hidden_sizes[i+1]))
self.fc_out = nn.Linear(hidden_sizes[-1], 1)
#self.activation = nn.ReLU()
self.activation = nn.ELU() # Change ReLU to ELU
# Initialize weights
self.init_weights()
def forward(self, state):
x = self.activation(self.fc_in(state))
for hidden_layer in self.hidden_layers:
x = self.activation(hidden_layer(x))
value = self.fc_out(x)
return value
def init_weights(self):
for m in self.modules():
if isinstance(m, nn.Linear):
nn.init.xavier_uniform_(m.weight) # Improved initialization
nn.init.constant_(m.bias, 0)
# Select Action Function
def select_action(state, actor, critic, bounds_low, bounds_high, performance_metrics):
state_tensor = torch.from_numpy(state).float().unsqueeze(0)
action_mean, action_log_std = actor(state_tensor)
print("action_mean",action_mean)
action_std = action_log_std.exp()
# Create a normal distribution and sample an action
normal_dist = torch.distributions.Normal(action_mean, action_std)
action = normal_dist.sample()
print("action normal dist", action)
log_prob = normal_dist.log_prob(action).sum(dim=1, keepdim=True)
# Clip your actions to their limits
#action = action.clamp(torch.tensor(bounds_low).unsqueeze(0), torch.tensor(bounds_high).unsqueeze(0))
action = action.clamp(torch.tensor(bounds_low).unsqueeze(0), torch.tensor(bounds_high).unsqueeze(0) - torch.tensor(bounds_low).unsqueeze(0))
# Estimate the value of the state using the critic network
value = critic(state_tensor)
return action.numpy(), log_prob, value.squeeze(), performance_metrics
|
3e38903a9b9020483513dab6d6f2801d
|
{
"intermediate": 0.39097070693969727,
"beginner": 0.33674120903015137,
"expert": 0.27228808403015137
}
|
42,992
|
I have a react component that is using rc-select library. When I click on select my container with the icon of arrow gets attribute unselectable='on'. What does it mean and do I have the means to change it?
|
437e381d72f36e476e5acef6ecac6857
|
{
"intermediate": 0.7920643091201782,
"beginner": 0.1115182414650917,
"expert": 0.09641741216182709
}
|
42,993
|
route: match: Host(`api.retailrocket.ru`, `api.retailrocket.net`, `cdn.retailrocket.ru`, `cdn.retailrocket.net`) && PathPrefix(`/api/{ver:(1.0|2.0|3.0)}/{var:(.*)?}{reg:[Rr]}eco{more:m{1,2}}endation`) replacePathRegex: regex: /api/(.*) replacement: /$1 У меня есть route в файле values. Как мне сделать, чтобы lifecycle: preStop: exec: command: - sleep - '{{ ((.Values.lifecycle).preStop).sleepSeconds | default 30 }}' было написано в манифесте только если route не задан?
|
dc85b42a5b1bf68bbcfad136a7ef12b6
|
{
"intermediate": 0.36208975315093994,
"beginner": 0.3868351876735687,
"expert": 0.25107502937316895
}
|
42,994
|
Create one class named "BoundingBoxFInder" and cover all the function in that class
import cv2
import pandas as pd
import json
from thefuzz import fuzz
from itertools import product
used_bounding_boxes = {}
def preprocess_entity(entity):
try:
token = entity.replace(",", "").strip()
return token
except:
pass
def calculate_proximity_score(box_a, box_b):
vertical_overlap = max(0, min(box_a["bottom"], box_b["bottom"]) - max(box_a["top"], box_b["top"]))
vertical_distance = 0 if vertical_overlap > 0 else min(abs(box_a["top"] - box_b["bottom"]), abs(box_a["bottom"] - box_b["top"]))
horizontal_overlap = max(0, min(box_a["right"], box_b["right"]) - max(box_a["left"], box_b["left"]))
horizontal_distance = 0 if horizontal_overlap > 0 else abs(box_a["right"] - box_b["left"])
return horizontal_distance + 2 * vertical_distance
def is_nearby(box_a, box_b, max_line_difference=5, max_distance=100):
return calculate_proximity_score(box_a, box_b) <= max_distance + 2 * max_line_difference
def merge_boxes(boxes):
min_left = min(box["left"] for box in boxes)
max_right = max(box["right"] for box in boxes)
min_top = min(box["top"] for box in boxes)
max_bottom = max(box["bottom"] for box in boxes)
return {"left": min_left, "right": max_right, "top": min_top, "bottom": max_bottom}
def find_potential_matches(dataframe, token, threshold=75):
potential_matches = []
for _, row in dataframe.iterrows():
ocr_text = preprocess_entity(row["text"])
score = fuzz.ratio(token, ocr_text)
if score > threshold:
potential_matches.append({
"box": {"left": row["left"], "right": row["right"], "top": row["top"], "bottom": row["bottom"]},
"score": score
})
return potential_matches
def find_best_sequence_heuristic(matches_list):
if not matches_list or len(matches_list[0]) == 0:
return []
best_sequence = [min(matches_list[0], key=lambda match: match["score"])]
for next_matches in matches_list[1:]:
current_box = best_sequence[-1]["box"]
next_best_match = min(next_matches, key=lambda match: calculate_proximity_score(current_box, match["box"]))
best_sequence.append(next_best_match)
return best_sequence
def process_single_token_entity(dataframe, entity, threshold=75):
global used_bounding_boxes
best_match = None
best_score = threshold
entity = preprocess_entity(entity)
if entity not in used_bounding_boxes:
used_bounding_boxes[entity] = []
for _, row in dataframe.iterrows():
ocr_text = preprocess_entity(row['text'])
score = fuzz.ratio(entity, ocr_text)
current_box = {'left': row['left'], 'right': row['right'], 'top': row['top'], 'bottom': row['bottom']}
if score > best_score and current_box not in used_bounding_boxes[entity]:
best_score = score
best_match = current_box
if best_match:
used_bounding_boxes[entity].append(best_match)
return best_match
def box_overlap(box1, box2):
"""Check if there’s any overlap in any coordinate between two boxes."""
return box1["left"] == box2["left"] or box1["right"] == box2["right"]
def all_boxes_unique(sequence_boxes, used_boxes):
"""Ensure no part of the boxes in sequence_boxes overlaps with any box in used_boxes."""
for seq_box in sequence_boxes:
for used_box in used_boxes:
if box_overlap(seq_box, used_box):
return False
return True
def get_next_best_sequence(all_potential_matches, previous_matches, entity):
"""
Try to find the next best sequence of matches that hasn’t used any part of the bounding boxes.
"""
# Flatten the list of used boxes for easier comparison.
used_boxes = [box for sequence in previous_matches.get(entity, []) for box in sequence]
for sequence in product(*all_potential_matches):
sequence_boxes = [match["box"] for match in sequence]
if all_boxes_unique(sequence_boxes, used_boxes):
return sequence # Found a sequence where no box part has been used before
return None # No unique sequence found
def process_multi_token_entity(dataframe, entity, threshold=75, max_distance=100, max_line_difference=3):
global used_bounding_boxes
tokens = entity.split()
all_potential_matches = [find_potential_matches(dataframe, token, threshold) for token in tokens]
if not all(matches for matches in all_potential_matches):
return None
if entity not in used_bounding_boxes:
used_bounding_boxes[entity] = []
previous_matches = used_bounding_boxes.get(entity, [])
all_sequences = list(product(*all_potential_matches)) # Create all possible sequences
valid_sequences = [] # List to hold sequences that meet the is_nearby condition
for sequence in all_sequences:
sequence_boxes = [match["box"] for match in sequence]
sequence_is_valid = True
for i in range(len(sequence_boxes) - 1):
if not is_nearby(sequence_boxes[i], sequence_boxes[i + 1], max_line_difference, max_distance):
sequence_is_valid = False
break
if sequence_is_valid:
valid_sequences.append(sequence)
# Sort valid sequences by their cumulative proximity score, to prioritize those with boxes closer together
valid_sequences = sorted(valid_sequences, key=lambda seq: sum(calculate_proximity_score(seq[i]["box"], seq[i+1]["box"]) for i in range(len(seq) - 1)))
next_best_sequence = None
for sequence in valid_sequences:
sequence_boxes = [match["box"] for match in sequence]
if all_boxes_unique(sequence_boxes, [box for sublist in previous_matches for box in sublist]):
next_best_sequence = sequence
break
if next_best_sequence:
new_boxes_sequence = [match["box"] for match in next_best_sequence]
merged_box = merge_boxes(new_boxes_sequence)
used_bounding_boxes[entity].append(new_boxes_sequence)
return merged_box
return None
def draw_bounding_boxes(image_path, bounding_boxes, entity_names):
image = cv2.imread(image_path)
font = cv2.FONT_HERSHEY_SIMPLEX
for box, name in zip(bounding_boxes, entity_names):
if box:
cv2.rectangle(image, (box["left"], box["top"]), (box["right"], box["bottom"]), (0, 255, 0), 2)
cv2.putText(image, name, (box["left"], max(box["top"] - 10, 0)), font, 0.5, (0, 0, 255), 2)
cv2.imwrite("annotated_image_using_dp1119.jpg", image)
def main(json_path, csv_path, image_path):
with open(json_path, "r") as f:
data = json.load(f)
dataframe = pd.read_csv(csv_path)
bounding_boxes = []
entity_names = []
# Existing processing for non-special sections
special_sections = ["amounts_and_tax","Payment Details"] # Define special handling cases here
for section in ["invoice_details", "Payment Details", "amounts_and_tax"]:
entities = data.get(section, {})
# Check if the current section needs special handling
if section not in special_sections:
for entity_name, entity_value in entities.items():
entity_value_no_comma = preprocess_entity(entity_value)
if " " in entity_value_no_comma:
box = process_multi_token_entity(dataframe, entity_value_no_comma)
else:
box = process_single_token_entity(dataframe, entity_value_no_comma)
if box:
bounding_boxes.append(box)
entity_names.append(entity_name)
else:
# Special handling for "amounts_and_tax" section
reversed_dataframe = dataframe.iloc[::-1].reset_index(drop=True) # Reverse the dataframe
for entity_name, entity_value in entities.items():
entity_value_no_comma = preprocess_entity(entity_value)
if " " in entity_value_no_comma:
# Use the reversed_dataframe for multi-token entities
box = process_multi_token_entity(reversed_dataframe, entity_value_no_comma)
else:
# Use the reversed_dataframe for single-token entities
box = process_single_token_entity(reversed_dataframe, entity_value_no_comma)
if box:
bounding_boxes.append(box)
entity_names.append(entity_name)
draw_bounding_boxes(image_path, bounding_boxes, entity_names)
main("/home/ritik1s/Desktop/bbox_issues/temp_GPT/row_skip.json", "/home/ritik1s/Desktop/bbox_issues/temp_GPT/check.csv", "/home/ritik1s/Desktop/bbox_issues/temp_GPT/check.jpeg")
|
63fd0a74ba0fa19b905d0e33dbea784d
|
{
"intermediate": 0.38629549741744995,
"beginner": 0.40669921040534973,
"expert": 0.20700526237487793
}
|
42,995
|
find the partition clause from this Teradata table:
|
fdc26d9d38073865db7acfe12cf58856
|
{
"intermediate": 0.3413776159286499,
"beginner": 0.27234840393066406,
"expert": 0.3862740397453308
}
|
42,996
|
in this javascript in the else statement (when the final scores are displayed) I want to set the map bounds to show the extent of all the markers and street view locations added to the map - 'let streetLatitude; // Define streetLatitude globally
let streetLongitude; // Define streetLongitude globally
let marker; // Define marker globally to make it accessible across functions
let data; // Declare data globally
let currentIndex = 0; // Initialize index globally
let totalScore = 0; // Initialize total points variable
function fetchStreetDetails() {
fetch("main.json")
.then((response) => response.json())
.then((jsonData) => {
data = jsonData; // Store the data globally
const entryCount = data.length; // data is already an array of objects
const streetDetails = data[0];
// Extract street details
streetLatitude = streetDetails.StreetLatitude;
streetLongitude = streetDetails.StreetLongitude;
streetHeading = streetDetails.StreetHeading;
streetPitch = streetDetails.StreetPitch;
streetPanoID = streetDetails.StreetPanoID;
const StreetPoints = streetDetails.Points;
const panorama = new google.maps.StreetViewPanorama(
document.getElementById("streetview"),
{
position: { lat: streetLatitude, lng: streetLongitude },
addressControl: false,
pano: streetPanoID,
heading: streetHeading,
pitch: streetPitch,
}
);
console.log("Street Latitude: " + streetLatitude);
console.log("Street Longitude: " + streetLongitude);
console.log("Street Heading: " + streetHeading);
console.log("Street Pitch: " + streetPitch);
console.log("Street PanoID: " + streetPanoID);
console.log("Street Location: " + StreetPoints);
// Update numberoffeeds div
const numberoffeedsElement =
document.getElementById("numberoffeeds");
numberoffeedsElement.textContent = `There are ${entryCount} questions in this game.`;
})
.catch((error) => console.error("Error fetching data: ", error));
}
fetchStreetDetails();
function initMap() {
const mapStyles = [
{
featureType: "poi",
stylers: [
{
visibility: "off",
},
],
},
{
featureType: "poi.park",
stylers: [
{
visibility: "off",
},
],
},
{
"featureType": "transit",
"stylers": [
{
"visibility": "off"
}
]
}
];
const mapOptions = {
center: { lat: 51.540073, lng: -0.010874 },
zoom: 8,
styles: mapStyles,
};
const map = new google.maps.Map(
document.getElementById("map"),
mapOptions
);
// Function to add marker on click
function addMarker(event) {
const clickLocation = event.latLng;
marker = new google.maps.Marker({
position: clickLocation,
map: map,
draggable: true, // Set draggable to true
});
// Remove the click listener after adding a marker
google.maps.event.removeListener(clickListener);
// Add functionality after clicking the map
createSubmitButton(clickLocation);
}
// Create a function to add the submit button
function createSubmitButton(distance, clickLocation) {
const buttonsDiv = document.getElementById("buttons");
// Check if the button already exists before creating a new one
if (!document.getElementById("submit")) {
const submitButton = document.createElement("button");
submitButton.id = "submit";
submitButton.textContent = `Submit`;
submitButton.className = "button";
// Add event listener for the submit button (you can define the functionality here)
submitButton.addEventListener("click", () => {
console.log("Submit button clicked!");
// Create the next button
const nextButton = document.createElement("button");
nextButton.id = "nextButton";
nextButton.textContent = "Next"; // Customize button text as needed
nextButton.className = "nextbutton";
// Add event listener for the new button (optional, if needed)
nextButton.addEventListener("click", () => {
// Handle ‘nextButton’ click here
console.log("Next button clicked!");
buttons.removeChild(nextButton);
const wheremessage = "Next location. Where is this?";
// Update the 'results' div using DOM manipulation
const resultsDiv = document.getElementById("results");
resultsDiv.textContent = wheremessage;
// Check if there is next entry in the data
if (data && currentIndex < data.length - 1) {
currentIndex++; // Update the index to get the next street view details
const nextStreetDetails = data[currentIndex];
streetLatitude = nextStreetDetails.StreetLatitude;
streetLongitude = nextStreetDetails.StreetLongitude;
streetHeading = nextStreetDetails.StreetHeading;
streetPitch = nextStreetDetails.StreetPitch;
streetPanoID = nextStreetDetails.StreetPanoID;
const StreetPoints = nextStreetDetails.Points;
const panorama = new google.maps.StreetViewPanorama(
document.getElementById("streetview"),
{
position: { lat: streetLatitude, lng: streetLongitude },
addressControl: false,
pano: streetPanoID,
heading: streetHeading,
pitch: streetPitch,
}
);
console.log("Street Latitude: " + streetLatitude);
console.log("Street Longitude: " + streetLongitude);
console.log("Street Heading: " + streetHeading);
console.log("Street Pitch: " + streetPitch);
console.log("Street PanoID: " + streetPanoID);
console.log("Street Location: " + StreetPoints);
// Add click listener to the map to allow marker placement
const nextClickListener = map.addListener("click", addMarker);
} else {
console.log("No next entry in the data.");
// Calculate total points
const finalScores = `Total Score: ${totalScore}`;
// Update the 'streetview' div with final scores
const streetviewDiv = document.getElementById("streetview");
streetviewDiv.innerHTML = finalScores; // Update content with innerHTML
const overmessage = "Game Over";
const resultsDiv = document.getElementById("results");
resultsDiv.textContent = overmessage;
}
});
// Replace the buttons
buttonsDiv.replaceChild(nextButton, submitButton);
// Get the current marker position when the button is pressed
const markerPosition = marker.getPosition();
// Calculate distance using marker position and street coordinates
const distance = calculateDistance(
markerPosition.lat(),
markerPosition.lng(),
streetLatitude,
streetLongitude
);
// Adjust points based on distance
let score = 5000 - distance;
if (score < 0) {
score = 0;
}
console.log(
"Distance from marker to street: " + distance + " meters. You scored: " + score
);
totalScore += score; // Add current points to total
const message =
"You scored " + score;
// Update the 'results' div using DOM manipulation
const resultsDiv = document.getElementById("results");
resultsDiv.textContent = message;
// Createpolyline on marker add
drawPolyline(clickLocation);
// Set the marker as non-draggable
marker.setDraggable(false);
});
buttonsDiv.appendChild(submitButton);
}
} // Add click listener to the map
const clickListener = map.addListener("click", addMarker);
function calculateDistance(lat1, lng1, lat2, lng2) {
const deltaLat = ((lat2 - lat1) * Math.PI) / 180;
const deltaLng = ((lng2 - lng1) * Math.PI) / 180;
const earthRadius = 6371e3; // meters
const a = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2);
const b =
Math.cos((lat1 * Math.PI) / 180) *
Math.cos((lat2 * Math.PI) / 180) *
Math.sin(deltaLng / 2) *
Math.sin(deltaLng / 2);
const c = 2 * Math.atan2(Math.sqrt(a + b), Math.sqrt(1 - a - b)); // Calculate distance using Pythagorean theorem
const distance = earthRadius * c; // Round the distance to nearest meter using Math.round()
const roundedDistance = Math.round(distance);
return roundedDistance;
} // Function to draw polyline between marker and street location
function drawPolyline() {
const markerPosition = marker.getPosition(); // Get the current position of the marker
const polyline = new google.maps.Polyline({
path: [
markerPosition.toJSON(),
{ lat: streetLatitude, lng: streetLongitude },
],
strokeColor: "#FF0000", // red color
strokeWeight: 2,
map: map,
});
// Set map bounds to encompass marker and polyline
const bounds = new google.maps.LatLngBounds(); // Use google.maps here
bounds.extend(markerPosition);
bounds.extend(polyline.getPath().getAt(1));
map.fitBounds(bounds);
}
}
'
|
29f3822e4a5b9b74b6f55a42a6090f25
|
{
"intermediate": 0.4269886612892151,
"beginner": 0.3238230347633362,
"expert": 0.24918825924396515
}
|
42,997
|
Change the following submission file:
"""Submission file for an AdamW optimizer with warmup+cosine LR in PyTorch."""
from typing import Dict, Iterator, List, Tuple
from absl import logging
import torch
import torch.distributed.nn as dist_nn
from torch.optim.lr_scheduler import CosineAnnealingLR
from torch.optim.lr_scheduler import LinearLR
from torch.optim.lr_scheduler import SequentialLR
from algorithmic_efficiency import spec
from algorithmic_efficiency.pytorch_utils import pytorch_setup
USE_PYTORCH_DDP = pytorch_setup()[0]
def init_optimizer_state(workload: spec.Workload,
model_params: spec.ParameterContainer,
model_state: spec.ModelAuxiliaryState,
hyperparameters: spec.Hyperparameters,
rng: spec.RandomState) -> spec.OptimizerState:
"""Creates an AdamW optimizer and a learning rate schedule."""
del model_state
del rng
optimizer_state = {
'optimizer':
torch.optim.AdamW(
model_params.parameters(),
lr=hyperparameters.learning_rate,
betas=(1.0 - hyperparameters.one_minus_beta1,
hyperparameters.beta2),
eps=1e-8,
weight_decay=hyperparameters.weight_decay,
fused=False),
}
def pytorch_cosine_warmup(step_hint: int, hyperparameters, optimizer):
warmup_steps = hyperparameters.warmup_factor * step_hint
warmup = LinearLR(
optimizer, start_factor=1e-10, end_factor=1., total_iters=warmup_steps)
cosine_steps = max(step_hint - warmup_steps, 1)
cosine_decay = CosineAnnealingLR(optimizer, T_max=cosine_steps)
return SequentialLR(
optimizer, schedulers=[warmup, cosine_decay], milestones=[warmup_steps])
optimizer_state['scheduler'] = pytorch_cosine_warmup(
workload.step_hint, hyperparameters, optimizer_state['optimizer'])
return optimizer_state
def update_params(workload: spec.Workload,
current_param_container: spec.ParameterContainer,
current_params_types: spec.ParameterTypeTree,
model_state: spec.ModelAuxiliaryState,
hyperparameters: spec.Hyperparameters,
batch: Dict[str, spec.Tensor],
loss_type: spec.LossType,
optimizer_state: spec.OptimizerState,
eval_results: List[Tuple[int, float]],
global_step: int,
rng: spec.RandomState) -> spec.UpdateReturn:
"""Return (updated_optimizer_state, updated_params, updated_model_state)."""
del current_params_types
del loss_type
del eval_results
current_model = current_param_container
current_model.train()
optimizer_state['optimizer'].zero_grad()
logits_batch, new_model_state = workload.model_fn(
params=current_model,
augmented_and_preprocessed_input_batch=batch,
model_state=model_state,
mode=spec.ForwardPassMode.TRAIN,
rng=rng,
update_batch_norm=True)
label_smoothing = (
hyperparameters.label_smoothing if hasattr(hyperparameters,
'label_smoothing') else 0.0)
loss_dict = workload.loss_fn(
label_batch=batch['targets'],
logits_batch=logits_batch,
mask_batch=batch.get('weights'),
label_smoothing=label_smoothing)
summed_loss = loss_dict['summed']
n_valid_examples = loss_dict['n_valid_examples']
if USE_PYTORCH_DDP:
# Use dist_nn.all_reduce to ensure correct loss and gradient scaling.
summed_loss = dist_nn.all_reduce(summed_loss)
n_valid_examples = dist_nn.all_reduce(n_valid_examples)
loss = summed_loss / n_valid_examples
loss.backward()
if hasattr(hyperparameters, 'grad_clip'):
grad_clip = hyperparameters.grad_clip
torch.nn.utils.clip_grad_norm_(
current_model.parameters(), max_norm=grad_clip)
optimizer_state['optimizer'].step()
optimizer_state['scheduler'].step()
# Log training metrics - loss, grad_norm, batch_size.
if global_step <= 10 or global_step % 500 == 0:
with torch.no_grad():
parameters = [p for p in current_model.parameters() if p.grad is not None]
grad_norm = torch.norm(
torch.stack([torch.norm(p.grad.detach(), 2) for p in parameters]), 2)
if workload.metrics_logger is not None:
workload.metrics_logger.append_scalar_metrics(
{
'loss': loss.item(),
'grad_norm': grad_norm.item(),
}, global_step)
logging.info('%d) loss = %0.3f, grad_norm = %0.3f',
global_step,
loss.item(),
grad_norm.item())
return (optimizer_state, current_param_container, new_model_state)
def get_batch_size(workload_name):
# Return the global batch size.
if workload_name == 'criteo1tb':
return 262_144
elif workload_name == 'fastmri':
return 32
elif workload_name == 'imagenet_resnet':
return 1024
elif workload_name == 'imagenet_vit':
return 1024
elif workload_name == 'librispeech_conformer':
return 256
elif workload_name == 'librispeech_deepspeech':
return 256
elif workload_name == 'ogbg':
return 512
elif workload_name == 'wmt':
return 128
elif workload_name == 'mnist':
return 16
else:
raise ValueError(f'Unsupported workload name: {workload_name}.')
def data_selection(workload: spec.Workload,
input_queue: Iterator[Dict[str, spec.Tensor]],
optimizer_state: spec.OptimizerState,
current_param_container: spec.ParameterContainer,
model_state: spec.ModelAuxiliaryState,
hyperparameters: spec.Hyperparameters,
global_step: int,
rng: spec.RandomState) -> Dict[str, spec.Tensor]:
"""Select data from the infinitely repeating, pre-shuffled input queue.
Each element of the queue is a batch of training examples and labels.
"""
del workload
del optimizer_state
del current_param_container
del model_state
del hyperparameters
del global_step
del rng
batch = next(input_queue)
return batch
WITH the following optimizer and not Adafactor. Make necessary changes in the code with hyperparameters wherever necessarry. Write clean code with proper indendation without errors:
import torch
from torch.optim.optimizer import Optimizer
import math
class Fusedbun(Optimizer):
def __init__(self, params, lr=1e-3, eps=1e-8, beta_decay=0.8, Lambda=0.01, momentum_beta=0.9, centralize=True, use_rms=True):
defaults = dict(lr=lr, eps=eps, beta_decay=beta_decay, Lambda=Lambda, momentum_beta=momentum_beta, centralize=centralize, use_rms=use_rms)
super(Fusedbun, self).__init__(params, defaults)
@torch.no_grad()
def step(self, closure=None):
loss = None
if closure is not None:
loss = closure()
for group in self.param_groups:
lr = group['lr']
eps = group['eps']
beta_decay = group['beta_decay']
Lambda = group['Lambda']
momentum_beta = group['momentum_beta']
centralize = group['centralize']
use_rms = group['use_rms']
for p in group['params']:
if p.grad is None:
continue
grad = p.grad.data
if centralize and len(p.shape) > 1:
grad = grad.sub(grad.mean(dim=tuple(range(1, len(grad.shape))), keepdim=True))
state = self.state[p]
if len(state) == 0:
state['step'] = 0
state['accumulator'] = torch.zeros_like(p.data)
if momentum_beta > 0:
state['momentum_buffer'] = torch.zeros_like(p.data)
acc = state['accumulator']
t = state['step'] + 1
state['step'] = t
if p.dim() > 1:
grad_squared = grad.square().mean(dim=0)
else:
grad_squared = grad.square()
beta_t = 1.0 - math.pow(t, -beta_decay)
acc.mul_(beta_t).add_(grad_squared, alpha=1-beta_t)
denom = acc.sqrt().add(eps)
grad_normalized = grad / denom if use_rms else grad
if momentum_beta > 0:
momentum_buffer = state['momentum_buffer']
momentum_buffer.mul_(momentum_beta).add_(grad_normalized, alpha=1-momentum_beta)
grad_normalized = momentum_buffer
p.data.add_(grad_normalized, alpha=-lr)
return loss
|
852309caed7555e9d5213c90924b2bb0
|
{
"intermediate": 0.3418622612953186,
"beginner": 0.4212113618850708,
"expert": 0.2369263619184494
}
|
42,998
|
Create one class named "BoundingBoxFInder" and cover all the function in that class And return the complete code
import cv2
import pandas as pd
import json
from thefuzz import fuzz
from itertools import product
used_bounding_boxes = {}
def preprocess_entity(entity):
try:
token = entity.replace(",", "").strip()
return token
except:
pass
def calculate_proximity_score(box_a, box_b):
vertical_overlap = max(0, min(box_a["bottom"], box_b["bottom"]) - max(box_a["top"], box_b["top"]))
vertical_distance = 0 if vertical_overlap > 0 else min(abs(box_a["top"] - box_b["bottom"]), abs(box_a["bottom"] - box_b["top"]))
horizontal_overlap = max(0, min(box_a["right"], box_b["right"]) - max(box_a["left"], box_b["left"]))
horizontal_distance = 0 if horizontal_overlap > 0 else abs(box_a["right"] - box_b["left"])
return horizontal_distance + 2 * vertical_distance
def is_nearby(box_a, box_b, max_line_difference=5, max_distance=100):
return calculate_proximity_score(box_a, box_b) <= max_distance + 2 * max_line_difference
def merge_boxes(boxes):
min_left = min(box["left"] for box in boxes)
max_right = max(box["right"] for box in boxes)
min_top = min(box["top"] for box in boxes)
max_bottom = max(box["bottom"] for box in boxes)
return {"left": min_left, "right": max_right, "top": min_top, "bottom": max_bottom}
def find_potential_matches(dataframe, token, threshold=75):
potential_matches = []
for _, row in dataframe.iterrows():
ocr_text = preprocess_entity(row["text"])
score = fuzz.ratio(token, ocr_text)
if score > threshold:
potential_matches.append({
"box": {"left": row["left"], "right": row["right"], "top": row["top"], "bottom": row["bottom"]},
"score": score
})
return potential_matches
def find_best_sequence_heuristic(matches_list):
if not matches_list or len(matches_list[0]) == 0:
return []
best_sequence = [min(matches_list[0], key=lambda match: match["score"])]
for next_matches in matches_list[1:]:
current_box = best_sequence[-1]["box"]
next_best_match = min(next_matches, key=lambda match: calculate_proximity_score(current_box, match["box"]))
best_sequence.append(next_best_match)
return best_sequence
def process_single_token_entity(dataframe, entity, threshold=75):
global used_bounding_boxes
best_match = None
best_score = threshold
entity = preprocess_entity(entity)
if entity not in used_bounding_boxes:
used_bounding_boxes[entity] = []
for _, row in dataframe.iterrows():
ocr_text = preprocess_entity(row['text'])
score = fuzz.ratio(entity, ocr_text)
current_box = {'left': row['left'], 'right': row['right'], 'top': row['top'], 'bottom': row['bottom']}
if score > best_score and current_box not in used_bounding_boxes[entity]:
best_score = score
best_match = current_box
if best_match:
used_bounding_boxes[entity].append(best_match)
return best_match
def box_overlap(box1, box2):
"""Check if there’s any overlap in any coordinate between two boxes."""
return box1["left"] == box2["left"] or box1["right"] == box2["right"]
def all_boxes_unique(sequence_boxes, used_boxes):
"""Ensure no part of the boxes in sequence_boxes overlaps with any box in used_boxes."""
for seq_box in sequence_boxes:
for used_box in used_boxes:
if box_overlap(seq_box, used_box):
return False
return True
def get_next_best_sequence(all_potential_matches, previous_matches, entity):
"""
Try to find the next best sequence of matches that hasn’t used any part of the bounding boxes.
"""
# Flatten the list of used boxes for easier comparison.
used_boxes = [box for sequence in previous_matches.get(entity, []) for box in sequence]
for sequence in product(*all_potential_matches):
sequence_boxes = [match["box"] for match in sequence]
if all_boxes_unique(sequence_boxes, used_boxes):
return sequence # Found a sequence where no box part has been used before
return None # No unique sequence found
def process_multi_token_entity(dataframe, entity, threshold=75, max_distance=100, max_line_difference=3):
global used_bounding_boxes
tokens = entity.split()
all_potential_matches = [find_potential_matches(dataframe, token, threshold) for token in tokens]
if not all(matches for matches in all_potential_matches):
return None
if entity not in used_bounding_boxes:
used_bounding_boxes[entity] = []
previous_matches = used_bounding_boxes.get(entity, [])
all_sequences = list(product(*all_potential_matches)) # Create all possible sequences
valid_sequences = [] # List to hold sequences that meet the is_nearby condition
for sequence in all_sequences:
sequence_boxes = [match["box"] for match in sequence]
sequence_is_valid = True
for i in range(len(sequence_boxes) - 1):
if not is_nearby(sequence_boxes[i], sequence_boxes[i + 1], max_line_difference, max_distance):
sequence_is_valid = False
break
if sequence_is_valid:
valid_sequences.append(sequence)
# Sort valid sequences by their cumulative proximity score, to prioritize those with boxes closer together
valid_sequences = sorted(valid_sequences, key=lambda seq: sum(calculate_proximity_score(seq[i]["box"], seq[i+1]["box"]) for i in range(len(seq) - 1)))
next_best_sequence = None
for sequence in valid_sequences:
sequence_boxes = [match["box"] for match in sequence]
if all_boxes_unique(sequence_boxes, [box for sublist in previous_matches for box in sublist]):
next_best_sequence = sequence
break
if next_best_sequence:
new_boxes_sequence = [match["box"] for match in next_best_sequence]
merged_box = merge_boxes(new_boxes_sequence)
used_bounding_boxes[entity].append(new_boxes_sequence)
return merged_box
return None
def draw_bounding_boxes(image_path, bounding_boxes, entity_names):
image = cv2.imread(image_path)
font = cv2.FONT_HERSHEY_SIMPLEX
for box, name in zip(bounding_boxes, entity_names):
if box:
cv2.rectangle(image, (box["left"], box["top"]), (box["right"], box["bottom"]), (0, 255, 0), 2)
cv2.putText(image, name, (box["left"], max(box["top"] - 10, 0)), font, 0.5, (0, 0, 255), 2)
cv2.imwrite("annotated_image_using_dp1119.jpg", image)
def main(json_path, csv_path, image_path):
with open(json_path, "r") as f:
data = json.load(f)
dataframe = pd.read_csv(csv_path)
bounding_boxes = []
entity_names = []
# Existing processing for non-special sections
special_sections = ["amounts_and_tax","Payment Details"] # Define special handling cases here
for section in ["invoice_details", "Payment Details", "amounts_and_tax"]:
entities = data.get(section, {})
# Check if the current section needs special handling
if section not in special_sections:
for entity_name, entity_value in entities.items():
entity_value_no_comma = preprocess_entity(entity_value)
if " " in entity_value_no_comma:
box = process_multi_token_entity(dataframe, entity_value_no_comma)
else:
box = process_single_token_entity(dataframe, entity_value_no_comma)
if box:
bounding_boxes.append(box)
entity_names.append(entity_name)
else:
# Special handling for "amounts_and_tax" section
reversed_dataframe = dataframe.iloc[::-1].reset_index(drop=True) # Reverse the dataframe
for entity_name, entity_value in entities.items():
entity_value_no_comma = preprocess_entity(entity_value)
if " " in entity_value_no_comma:
# Use the reversed_dataframe for multi-token entities
box = process_multi_token_entity(reversed_dataframe, entity_value_no_comma)
else:
# Use the reversed_dataframe for single-token entities
box = process_single_token_entity(reversed_dataframe, entity_value_no_comma)
if box:
bounding_boxes.append(box)
entity_names.append(entity_name)
draw_bounding_boxes(image_path, bounding_boxes, entity_names)
main("/home/ritik1s/Desktop/bbox_issues/temp_GPT/row_skip.json", "/home/ritik1s/Desktop/bbox_issues/temp_GPT/check.csv", "/home/ritik1s/Desktop/bbox_issues/temp_GPT/check.jpeg")
|
ef7fa522e956eb7ea165f011d749d5fd
|
{
"intermediate": 0.39301010966300964,
"beginner": 0.4095187485218048,
"expert": 0.19747115671634674
}
|
42,999
|
can you create an entire site for me that an electricity consumption calculator with these steps,Instructions
1. Identify the appliances you use from the list below.
2. Indicate the number of appliances and the hours of use per day.
3. If you know the wattage of the appliance, please indicate in Watts (W).
[Average values have already been entered by default]
4. Tap the picture or click on the OFF/ON button to switch appliance on.
5. Monthly energy consumption and cost of electricity are indicated automatically.
6. Click View Chart to display chart by Energy (kWh) or Cost (GHS).
NB:
a. To make any modifications to your entry, switch appliance off first.
b. Scale down to a diversity factor of 80% if you were not home 20% of the time within the month.
i want it to be done in laravel so if u can
|
a061537aec5cfda8e53bb0ca23c3001c
|
{
"intermediate": 0.4261883795261383,
"beginner": 0.30068284273147583,
"expert": 0.27312880754470825
}
|
43,000
|
vehicleForm = this.fb.group({
Id: [0],
Immatriculation: ['', [Validators.required, this.validateImmatriculation]],
NumeroSerie: ['',[Validators.required,this.validateSerialNumber]],
NumeroAssurance: ['',[Validators.required, this.validateAssuranceNumber]],
DateAchat: ['', [Validators.required]],
Constructeur: ['', [Validators.required]],
Modele: [{value:'', disabled:true}, [Validators.required]],
Segment: ['',[Validators.required]],
NombrePlaces: [0, [Validators.required]],
DateDerniereModification: ['', [Validators.required]],
TypeCarburant: ['', [Validators.required]],
TypeBoiteVitesse: ['', [Validators.required]],
TypeVehicule: ['', [Validators.required]],
ConsommationMoyenne: [0, [Validators.required]],
Cylindree: [0, [Validators.required]],
Poids: ['', [Validators.required]],
PuissanceMoteur: [0, [Validators.required]],
EmissionCo2: [0, [Validators.required]],
PrixAchat: [0, [Validators.required]],
VignetteCritair: ['', [Validators.required]],
ValiditeCritair: ['', [Validators.required]],
Achat: ['', [Validators.required]],
DateMiseEnCirculation: ['', [Validators.required]],
Location: ['', [Validators.required]],
Kilometrage: [0, [Validators.required]],
RapportPoidsPuissance: [0, [Validators.required]],
IdConducteur: ['', [Validators.required]],
Libelle : ['', [Validators.required]],
});
|
dfa3dea88defec2c489a3f5bbd3d6fd6
|
{
"intermediate": 0.3889070451259613,
"beginner": 0.27813395857810974,
"expert": 0.33295896649360657
}
|
43,001
|
extract file name from a path
|
902fb461ddc9ecd3e021c30fd3dd2fd3
|
{
"intermediate": 0.41206514835357666,
"beginner": 0.21457916498184204,
"expert": 0.3733556866645813
}
|
43,002
|
Generate a code for a realistic 3d rally game
|
a593e419253a50ea025de72e9c57af8d
|
{
"intermediate": 0.20605777204036713,
"beginner": 0.22567877173423767,
"expert": 0.5682633519172668
}
|
43,003
|
Generate a code for a realistic 3d rally game on Python
|
d4ea0ed84fbb4b1d30da3f3a9d602607
|
{
"intermediate": 0.3238174617290497,
"beginner": 0.23455946147441864,
"expert": 0.44162309169769287
}
|
43,004
|
Generate a code for a rally game on Python
|
fc2be4590a8291c6d5da43100869a40c
|
{
"intermediate": 0.3442254066467285,
"beginner": 0.3463679850101471,
"expert": 0.3094066381454468
}
|
43,005
|
const proxySettings = {
mode: "fixed_servers",
rules: {
singleProxy: {
scheme: "http",
host: "38.154.227.167", // set host here
port: 5868
},
bypassList: ["<-loopback>"]
}
};
const proxyAuth = {
username: "luscaojl",
password: "msln1cr68koc"
};
if (proxyAuth.username && proxyAuth.password) {
proxySettings.rules.singleProxy.username = proxyAuth.username;
proxySettings.rules.singleProxy.password = proxyAuth.password;
}
chrome.proxy.settings.set({ value: proxySettings, scope: "regular" }, () => {
if (chrome.runtime.lastError) {
console.error("Failed to set proxy settings:", chrome.runtime.lastError);
} else {
console.log("Proxy settings configured successfully!");
}
});
chrome.proxy.onProxyError.addListener((error) => {
console.error("Proxy error:", error);
});
Uncaught TypeError: Invalid invocation
|
22a1a91fefaebab8054b17e032918b04
|
{
"intermediate": 0.31952202320098877,
"beginner": 0.49151891469955444,
"expert": 0.1889590471982956
}
|
43,006
|
Analyse the complete code and Fix this error
Exception has occurred: AttributeError
'BoundingBoxFinder' object has no attribute 'used_bounding_boxes'
File "/home/ritik1s/Desktop/bbox_issues/temp_GPT/bbx_by_me.py", line 62, in process_single_token_entity
if entity not in self.used_bounding_boxes:
^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/ritik1s/Desktop/bbox_issues/temp_GPT/bbx_by_me.py", line 177, in process_data
box = self.process_single_token_entity(dataframe, entity_value_no_comma)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/ritik1s/Desktop/bbox_issues/temp_GPT/bbx_by_me.py", line 201, in <module>
bbox_finder.process_data("/home/ritik1s/Desktop/bbox_issues/temp_GPT/row_skip.json", "/home/ritik1s/Desktop/bbox_issues/temp_GPT/check.csv", "/home/ritik1s/Desktop/bbox_issues/temp_GPT/check.jpeg")
AttributeError: 'BoundingBoxFinder' object has no attribute 'used_bounding_boxes' in the given code
import cv2
import pandas as pd
import json
from thefuzz import fuzz
from itertools import product
class BoundingBoxFinder:
def init(self):
self.used_bounding_boxes = {}
def preprocess_entity(self, entity):
try:
token = entity.replace(",", "").strip()
return token
except:
pass
def calculate_proximity_score(self, box_a, box_b):
vertical_overlap = max(0, min(box_a["bottom"], box_b["bottom"]) - max(box_a["top"], box_b["top"]))
vertical_distance = 0 if vertical_overlap > 0 else min(abs(box_a["top"] - box_b["bottom"]), abs(box_a["bottom"] - box_b["top"]))
horizontal_overlap = max(0, min(box_a["right"], box_b["right"]) - max(box_a["left"], box_b["left"]))
horizontal_distance = 0 if horizontal_overlap > 0 else abs(box_a["right"] - box_b["left"])
return horizontal_distance + 2 * vertical_distance
def is_nearby(self, box_a, box_b, max_line_difference=5, max_distance=100):
return self.calculate_proximity_score(box_a, box_b) <= max_distance + 2 * max_line_difference
def merge_boxes(self, boxes):
min_left = min(box["left"] for box in boxes)
max_right = max(box["right"] for box in boxes)
min_top = min(box["top"] for box in boxes)
max_bottom = max(box["bottom"] for box in boxes)
return {"left": min_left, "right": max_right, "top": min_top, "bottom": max_bottom}
def find_potential_matches(self, dataframe, token, threshold=75):
potential_matches = []
for _, row in dataframe.iterrows():
ocr_text = self.preprocess_entity(row["text"])
score = fuzz.ratio(token, ocr_text)
if score > threshold:
potential_matches.append({
"box": {"left": row["left"], "right": row["right"], "top": row["top"], "bottom": row["bottom"]},
"score": score
})
return potential_matches
def find_best_sequence_heuristic(self, matches_list):
if not matches_list or len(matches_list[0]) == 0:
return []
best_sequence = [min(matches_list[0], key=lambda match: match["score"])]
for next_matches in matches_list[1:]:
current_box = best_sequence[-1]["box"]
next_best_match = min(next_matches, key=lambda match: self.calculate_proximity_score(current_box, match["box"]))
best_sequence.append(next_best_match)
return best_sequence
def process_single_token_entity(self, dataframe, entity, threshold=75):
best_match = None
best_score = threshold
entity = self.preprocess_entity(entity)
if entity not in self.used_bounding_boxes:
self.used_bounding_boxes[entity] = []
for _, row in dataframe.iterrows():
ocr_text = self.preprocess_entity(row["text"])
score = fuzz.ratio(entity, ocr_text)
current_box = {"left": row["left"], "right": row["right"], "top": row["top"], "bottom": row["bottom"]}
if score > best_score and current_box not in self.used_bounding_boxes[entity]:
best_score = score
best_match = current_box
if best_match:
self.used_bounding_boxes[entity].append(best_match)
return best_match
def box_overlap(self, box1, box2):
"""Check if there"s any overlap in any coordinate between two boxes."""
return box1["left"] == box2["left"] or box1["right"] == box2["right"]
def all_boxes_unique(self, sequence_boxes, used_boxes):
"""Ensure no part of the boxes in sequence_boxes overlaps with any box in used_boxes."""
for seq_box in sequence_boxes:
for used_box in used_boxes:
if self.box_overlap(seq_box, used_box):
return False
return True
def get_next_best_sequence(self, all_potential_matches, previous_matches, entity):
"""
Try to find the next best sequence of matches that hasn"t used any part of the bounding boxes.
"""
# Flatten the list of used boxes for easier comparison.
used_boxes = [box for sequence in previous_matches.get(entity, []) for box in sequence]
for sequence in product(*all_potential_matches):
sequence_boxes = [match["box"] for match in sequence]
if self.all_boxes_unique(sequence_boxes, used_boxes):
return sequence # Found a sequence where no box part has been used before
return None # No unique sequence found
def process_multi_token_entity(self, dataframe, entity, threshold=75, max_distance=100, max_line_difference=3):
tokens = entity.split()
all_potential_matches = [self.find_potential_matches(dataframe, token, threshold) for token in tokens]
if not all(matches for matches in all_potential_matches):
return None
if entity not in self.used_bounding_boxes:
self.used_bounding_boxes[entity] = []
previous_matches = self.used_bounding_boxes.get(entity, [])
all_sequences = list(product(*all_potential_matches)) # Create all possible sequences
valid_sequences = [] # List to hold sequences that meet the is_nearby condition
for sequence in all_sequences:
sequence_boxes = [match["box"] for match in sequence]
sequence_is_valid = True
for i in range(len(sequence_boxes) - 1):
if not self.is_nearby(sequence_boxes[i], sequence_boxes[i + 1], max_line_difference, max_distance):
sequence_is_valid = False
break
if sequence_is_valid:
valid_sequences.append(sequence)
# Sort valid sequences by their cumulative proximity score, to prioritize those with boxes closer together
valid_sequences = sorted(valid_sequences, key=lambda seq: sum(self.calculate_proximity_score(seq[i]["box"], seq[i+1]["box"]) for i in range(len(seq) - 1)))
next_best_sequence = None
for sequence in valid_sequences:
sequence_boxes = [match["box"] for match in sequence]
if self.all_boxes_unique(sequence_boxes, [box for sublist in previous_matches for box in sublist]):
next_best_sequence = sequence
break
if next_best_sequence:
new_boxes_sequence = [match["box"] for match in next_best_sequence]
merged_box = self.merge_boxes(new_boxes_sequence)
self.used_bounding_boxes[entity].append(new_boxes_sequence)
return merged_box
return None
def draw_bounding_boxes(self, image_path, bounding_boxes, entity_names):
image = cv2.imread(image_path)
font = cv2.FONT_HERSHEY_SIMPLEX
for box, name in zip(bounding_boxes, entity_names):
if box:
cv2.rectangle(image, (box["left"], box["top"]), (box["right"], box["bottom"]), (0, 255, 0), 2)
cv2.putText(image, name, (box["left"], max(box["top"] - 10, 0)), font, 0.5, (0, 0, 255), 2)
cv2.imwrite("annotated_image.jpg", image)
def process_data(self, json_path, csv_path, image_path):
with open(json_path, "r") as f:
data = json.load(f)
dataframe = pd.read_csv(csv_path)
bounding_boxes = []
entity_names = []
# Existing processing for non-special sections
special_sections = ["amounts_and_tax", "Payment Details"] # Define special handling cases here
for section in ["invoice_details", "Payment Details", "amounts_and_tax"]:
entities = data.get(section, {})
# Check if the current section needs special handling
if section not in special_sections:
for entity_name, entity_value in entities.items():
entity_value_no_comma = self.preprocess_entity(entity_value)
if " " in entity_value_no_comma:
box = self.process_multi_token_entity(dataframe, entity_value_no_comma)
else:
box = self.process_single_token_entity(dataframe, entity_value_no_comma)
if box:
bounding_boxes.append(box)
entity_names.append(entity_name)
else:
# Special handling for "amounts_and_tax" section
reversed_dataframe = dataframe.iloc[::-1].reset_index(drop=True) # Reverse the dataframe
for entity_name, entity_value in entities.items():
entity_value_no_comma = self.preprocess_entity(entity_value)
if " " in entity_value_no_comma:
# Use the reversed_dataframe for multi-token entities
box = self.process_multi_token_entity(reversed_dataframe, entity_value_no_comma)
else:
# Use the reversed_dataframe for single-token entities
box = self.process_single_token_entity(reversed_dataframe, entity_value_no_comma)
if box:
bounding_boxes.append(box)
entity_names.append(entity_name)
self.draw_bounding_boxes(image_path, bounding_boxes, entity_names)
# Example usage
if __name__ == "main":
bbox_finder = BoundingBoxFinder()
bbox_finder.process_data("/home/ritik1s/Desktop/bbox_issues/temp_GPT/row_skip.json", "/home/ritik1s/Desktop/bbox_issues/temp_GPT/check.csv", "/home/ritik1s/Desktop/bbox_issues/temp_GPT/check.jpeg")
bbox_finder.main("/home/ritik1s/Desktop/bbox_issues/temp_GPT/row_skip.json", "/home/ritik1s/Desktop/bbox_issues/temp_GPT/check.csv", "/home/ritik1s/Desktop/bbox_issues/temp_GPT/check.jpeg")
|
a2eac712829e0a8e994961b498650089
|
{
"intermediate": 0.29222285747528076,
"beginner": 0.34436002373695374,
"expert": 0.3634171187877655
}
|
43,007
|
Analyse the complete code and Fix this error
Exception has occurred: AttributeError
'BoundingBoxFinder' object has no attribute 'used_bounding_boxes'
File "/home/ritik1s/Desktop/bbox_issues/temp_GPT/bbx_by_me.py", line 62, in process_single_token_entity
if entity not in self.used_bounding_boxes:
^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/ritik1s/Desktop/bbox_issues/temp_GPT/bbx_by_me.py", line 177, in process_data
box = self.process_single_token_entity(dataframe, entity_value_no_comma)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/ritik1s/Desktop/bbox_issues/temp_GPT/bbx_by_me.py", line 201, in <module>
bbox_finder.process_data("/home/ritik1s/Desktop/bbox_issues/temp_GPT/row_skip.json", "/home/ritik1s/Desktop/bbox_issues/temp_GPT/check.csv", "/home/ritik1s/Desktop/bbox_issues/temp_GPT/check.jpeg")
AttributeError: 'BoundingBoxFinder' object has no attribute 'used_bounding_boxes' in the given code
import cv2
import pandas as pd
import json
from thefuzz import fuzz
from itertools import product
class BoundingBoxFinder:
def init(self):
print("Initializing used_bounding_boxes")
self.used_bounding_boxes = {}
def preprocess_entity(self, entity):
try:
token = entity.replace(",", "").strip()
return token
except:
pass
def calculate_proximity_score(self, box_a, box_b):
vertical_overlap = max(0, min(box_a["bottom"], box_b["bottom"]) - max(box_a["top"], box_b["top"]))
vertical_distance = 0 if vertical_overlap > 0 else min(abs(box_a["top"] - box_b["bottom"]), abs(box_a["bottom"] - box_b["top"]))
horizontal_overlap = max(0, min(box_a["right"], box_b["right"]) - max(box_a["left"], box_b["left"]))
horizontal_distance = 0 if horizontal_overlap > 0 else abs(box_a["right"] - box_b["left"])
return horizontal_distance + 2 * vertical_distance
def is_nearby(self, box_a, box_b, max_line_difference=5, max_distance=100):
return self.calculate_proximity_score(box_a, box_b) <= max_distance + 2 * max_line_difference
def merge_boxes(self, boxes):
min_left = min(box["left"] for box in boxes)
max_right = max(box["right"] for box in boxes)
min_top = min(box["top"] for box in boxes)
max_bottom = max(box["bottom"] for box in boxes)
return {"left": min_left, "right": max_right, "top": min_top, "bottom": max_bottom}
def find_potential_matches(self, dataframe, token, threshold=75):
potential_matches = []
for _, row in dataframe.iterrows():
ocr_text = self.preprocess_entity(row["text"])
score = fuzz.ratio(token, ocr_text)
if score > threshold:
potential_matches.append({
"box": {"left": row["left"], "right": row["right"], "top": row["top"], "bottom": row["bottom"]},
"score": score
})
return potential_matches
def find_best_sequence_heuristic(self, matches_list):
if not matches_list or len(matches_list[0]) == 0:
return []
best_sequence = [min(matches_list[0], key=lambda match: match["score"])]
for next_matches in matches_list[1:]:
current_box = best_sequence[-1]["box"]
next_best_match = min(next_matches, key=lambda match: self.calculate_proximity_score(current_box, match["box"]))
best_sequence.append(next_best_match)
return best_sequence
def process_single_token_entity(self, dataframe, entity, threshold=75):
best_match = None
best_score = threshold
entity = self.preprocess_entity(entity)
if entity not in self.used_bounding_boxes:
self.used_bounding_boxes[entity] = []
for _, row in dataframe.iterrows():
ocr_text = self.preprocess_entity(row["text"])
score = fuzz.ratio(entity, ocr_text)
current_box = {"left": row["left"], "right": row["right"], "top": row["top"], "bottom": row["bottom"]}
if score > best_score and current_box not in self.used_bounding_boxes[entity]:
best_score = score
best_match = current_box
if best_match:
self.used_bounding_boxes[entity].append(best_match)
return best_match
def box_overlap(self, box1, box2):
"""Check if there"s any overlap in any coordinate between two boxes."""
return box1["left"] == box2["left"] or box1["right"] == box2["right"]
def all_boxes_unique(self, sequence_boxes, used_boxes):
"""Ensure no part of the boxes in sequence_boxes overlaps with any box in used_boxes."""
for seq_box in sequence_boxes:
for used_box in used_boxes:
if self.box_overlap(seq_box, used_box):
return False
return True
def get_next_best_sequence(self, all_potential_matches, previous_matches, entity):
"""
Try to find the next best sequence of matches that hasn"t used any part of the bounding boxes.
"""
# Flatten the list of used boxes for easier comparison.
used_boxes = [box for sequence in previous_matches.get(entity, []) for box in sequence]
for sequence in product(*all_potential_matches):
sequence_boxes = [match["box"] for match in sequence]
if self.all_boxes_unique(sequence_boxes, used_boxes):
return sequence # Found a sequence where no box part has been used before
return None # No unique sequence found
def process_multi_token_entity(self, dataframe, entity, threshold=75, max_distance=100, max_line_difference=3):
tokens = entity.split()
all_potential_matches = [self.find_potential_matches(dataframe, token, threshold) for token in tokens]
if not all(matches for matches in all_potential_matches):
return None
if entity not in self.used_bounding_boxes:
self.used_bounding_boxes[entity] = []
previous_matches = self.used_bounding_boxes.get(entity, [])
all_sequences = list(product(*all_potential_matches)) # Create all possible sequences
valid_sequences = [] # List to hold sequences that meet the is_nearby condition
for sequence in all_sequences:
sequence_boxes = [match["box"] for match in sequence]
sequence_is_valid = True
for i in range(len(sequence_boxes) - 1):
if not self.is_nearby(sequence_boxes[i], sequence_boxes[i + 1], max_line_difference, max_distance):
sequence_is_valid = False
break
if sequence_is_valid:
valid_sequences.append(sequence)
# Sort valid sequences by their cumulative proximity score, to prioritize those with boxes closer together
valid_sequences = sorted(valid_sequences, key=lambda seq: sum(self.calculate_proximity_score(seq[i]["box"], seq[i+1]["box"]) for i in range(len(seq) - 1)))
next_best_sequence = None
for sequence in valid_sequences:
sequence_boxes = [match["box"] for match in sequence]
if self.all_boxes_unique(sequence_boxes, [box for sublist in previous_matches for box in sublist]):
next_best_sequence = sequence
break
if next_best_sequence:
new_boxes_sequence = [match["box"] for match in next_best_sequence]
merged_box = self.merge_boxes(new_boxes_sequence)
self.used_bounding_boxes[entity].append(new_boxes_sequence)
return merged_box
return None
def draw_bounding_boxes(self, image_path, bounding_boxes, entity_names):
image = cv2.imread(image_path)
font = cv2.FONT_HERSHEY_SIMPLEX
for box, name in zip(bounding_boxes, entity_names):
if box:
cv2.rectangle(image, (box["left"], box["top"]), (box["right"], box["bottom"]), (0, 255, 0), 2)
cv2.putText(image, name, (box["left"], max(box["top"] - 10, 0)), font, 0.5, (0, 0, 255), 2)
cv2.imwrite("annotated_imagecls.jpg", image)
def process_data(self, json_path, csv_path, image_path):
with open(json_path, "r") as f:
data = json.load(f)
dataframe = pd.read_csv(csv_path)
bounding_boxes = []
entity_names = []
# Existing processing for non-special sections
special_sections = ["amounts_and_tax", "Payment Details"] # Define special handling cases here
for section in ["invoice_details", "Payment Details", "amounts_and_tax"]:
entities = data.get(section, {})
# Check if the current section needs special handling
if section not in special_sections:
for entity_name, entity_value in entities.items():
entity_value_no_comma = self.preprocess_entity(entity_value)
if " " in entity_value_no_comma:
box = self.process_multi_token_entity(dataframe, entity_value_no_comma)
else:
box = self.process_single_token_entity(dataframe, entity_value_no_comma)
if box:
bounding_boxes.append(box)
entity_names.append(entity_name)
else:
# Special handling for "amounts_and_tax" section
reversed_dataframe = dataframe.iloc[::-1].reset_index(drop=True) # Reverse the dataframe
for entity_name, entity_value in entities.items():
entity_value_no_comma = self.preprocess_entity(entity_value)
if " " in entity_value_no_comma:
# Use the reversed_dataframe for multi-token entities
box = self.process_multi_token_entity(reversed_dataframe, entity_value_no_comma)
else:
# Use the reversed_dataframe for single-token entities
box = self.process_single_token_entity(reversed_dataframe, entity_value_no_comma)
if box:
bounding_boxes.append(box)
entity_names.append(entity_name)
self.draw_bounding_boxes(image_path, bounding_boxes, entity_names)
# Example usage
if __name__ == "__main__":
bbox_finder = BoundingBoxFinder()
bbox_finder.process_data("/home/ritik1s/Desktop/bbox_issues/temp_GPT/row_skip.json", "/home/ritik1s/Desktop/bbox_issues/temp_GPT/check.csv", "/home/ritik1s/Desktop/bbox_issues/temp_GPT/check.jpeg")
# bbox_finder.main("/home/ritik1s/Desktop/bbox_issues/temp_GPT/row_skip.json", "/home/ritik1s/Desktop/bbox_issues/temp_GPT/check.csv", "/home/ritik1s/Desktop/bbox_issues/temp_GPT/check.jpeg")
|
72f72a6d955845cf0bd258ca6f2e2e01
|
{
"intermediate": 0.2850978970527649,
"beginner": 0.38620349764823914,
"expert": 0.3286985456943512
}
|
43,008
|
how to increase search relevancy in solr using edismax parameters
|
3d0b583db455aff5093a5d513a1aeb59
|
{
"intermediate": 0.17434392869472504,
"beginner": 0.18893729150295258,
"expert": 0.63671875
}
|
43,009
|
We have two catalog items that use the same variable set. We would like to make one of the individual variables inactive in one of the items but keep it active in the other item. Is this at all possible?
|
b54783d0f0569b21866a0a2b00c566eb
|
{
"intermediate": 0.3209644556045532,
"beginner": 0.3922867178916931,
"expert": 0.28674888610839844
}
|
43,010
|
напиши метод который будет передавать сообщение {"isReverse":false,"operationId":883791}
в
@RabbitListener(queues = SEND_BILL_QUEUE)
|
1c00719a7577ef6465a025e0aed40412
|
{
"intermediate": 0.33077308535575867,
"beginner": 0.38312703371047974,
"expert": 0.2860998809337616
}
|
43,011
|
python remove all instances of uFFFD replacement character in a string
|
e4e790ac2cd845cff2791470fb74d78b
|
{
"intermediate": 0.40391209721565247,
"beginner": 0.1682177633047104,
"expert": 0.42787015438079834
}
|
43,013
|
I have 3 coco style datasets that are large. Each dataset has the same classes. I want to use fifty one to load these datasets and then find the most unique data and then select the top 5000 and export them in a coco style dataset along with its media. In python
|
8b21231ead40798f4429e12dc3b638f8
|
{
"intermediate": 0.5088475942611694,
"beginner": 0.19528426229953766,
"expert": 0.2958681583404541
}
|
43,014
|
This is my code for RL algorithm, where the algorithm tune the 'action' ['L1', 'L3', 'L5', 'L6', 'L7', 'W1', 'W3', 'W5', 'W6', 'W7', 'Io', 'CP', 'VC'] with in its bounds, to get the desired target['all transistors are in saturation_condition', 'area', 'power dissipation', 'DC gain', 'Slew rate', 'Bandwidth3dB', 'Unity gain bandwidth', 'Phase margin'] with in its predefined range, from my circuit simulator where my two stage opamp circuit is simulated. Now i need to modify the existing implementation with Graph Newral Network with RL algorithm. For my new requirement What should I need to modify/update in the existing code, How should I implement the GNN with RL in the existing code and Where Should I Implement the GNN with RL.
from Simulator_Env1 import CircuitSimulator
class CircuitEnvironment:
def __init__(self, server_address, username, password, bounds_low, bounds_high, target_metrics):
def connect_to_simulator(self):
def disconnect_from_simulator(self):
def normalize_parameters(self, parameters):
return normalized_parameters
def encode_regions(self, transistor_regions):
return encoded_regions
def encode_saturation_condition(self, saturation_condition):
return 0
def normalize_performance_metrics(self, performance_metrics):
return normalized_metrics
def reset(self):
return state, performance_metrics
def step(self, raw_actions, previous_metrics):
return state, reward, done, previous_metrics
def is_performance_metrics_in_target(self, metrics):
return np.all(metrics >= self.PERFORMANCE_METRICS_TARGET_LOW) and np.all(metrics <= self.PERFORMANCE_METRICS_TARGET_HIGH)
def calculate_reward(self, c_metrics, p_metrics, transistor_regions, previous_transistor_regions):
return reward
def check_done(self, performance_metrics, encoded_saturation_condition):
return True
def initialize_actor_critic_networks(self, state_size, action_size, hidden_sizes_actor, hidden_sizes_critic, action_std_init, learning_rate_actor, learning_rate_critic, bounds_low, bounds_high):
self.actor = ActorNetwork(state_size, action_size, hidden_sizes_actor, bounds_low, bounds_high, action_std_init)
self.critic = CriticNetwork(state_size, hidden_sizes_critic)
self.optimizer_actor = optim.Adam(self.actor.parameters(), lr=learning_rate_actor)
self.optimizer_critic = optim.Adam(self.critic.parameters(), lr=learning_rate_critic)
# Define the Actor and Critic Networks
class ActorNetwork(nn.Module):
def __init__(self, state_size, action_size, hidden_sizes, bounds_low, bounds_high, action_std_init):
def forward(self, state):
return action_mean, log_std
def scale_action(self, action):
return scaled_action
class CriticNetwork(nn.Module):
def __init__(self, state_size, hidden_sizes):
def forward(self, state):
return value
# Select Action Function
def select_action(state, actor, critic, performance_metrics):
return action.detach().numpy(), log_prob, value.squeeze().detach().numpy(), performance_metrics
# Generalized Advantage Estimation (GAE)
return returns, advantages
# Policy and Value Network Update Function
def update_policy(actor, critic, optimizer_actor, optimizer_critic, states, actions, old_log_probs, returns, advantages, batch_size, epsilon):
# Prepare data for training
# Create DataLoader
# Iterate over batches
for batch in dataloader:
batch_states, batch_actions, batch_old_log_probs, batch_returns, batch_advantages = batch
# Compute new log probabilities and values
# Compute PPO loss for actor
# Compute value loss for critic
# Update actor and critic
# Constants
# Define the values for server_address, username, password, bounds, and target metrics
# Define the constants and target metrics for reward calculation
# Create the environment
env = CircuitEnvironment(server_address, username, password, bounds_low, bounds_high, target_metrics)
# Initialize Networks and Optimizers
env.initialize_actor_critic_networks(state_size, action_size, hidden_sizes_actor, hidden_sizes_critic, action_std_init, learning_rate_actor, learning_rate_critic, bounds_low, bounds_high)
# Set the Hyperparameters
# Set initial epsilon value and decay rate
# Training Loop
for episode in range(num_episodes):
# Define the Training Loop
state, performance_metrics = env.reset()
# Run one episode
for t in range(max_timesteps):
action, log_prob, value, perf_metrics = select_action(state, env.actor, env.critic, performance_metrics)
action = np.clip(action, bounds_low, bounds_high)
next_state, reward, done, previous_metrics = env.step(action, perf_metrics) # Take action in environment
performance_metrics = previous_metrics
state = next_state
if done:
break
# Compute returns and advantages
# Update policy and value network
# Update epsilon
# Log episode information
total_reward = sum(episode_rewards)
env.disconnect_from_simulator()
|
d1d029b89aefc4de1e7c11bfdef6d9e3
|
{
"intermediate": 0.2711947560310364,
"beginner": 0.40696650743484497,
"expert": 0.32183870673179626
}
|
43,015
|
urllib3.exceptions.SSLError: EOF occurred in violation of protocol (_ssl.c:997)
The above exception was the direct cause of the following exception:
urllib3.exceptions.ProxyError: ('Unable to connect to proxy', SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:997)')))
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Fazel\PycharmProjects\indicators_calculate\venv\lib\site-packages\requests\adapters.py", line 486, in send
resp = conn.urlopen(
File "C:\Users\Fazel\PycharmProjects\indicators_calculate\venv\lib\site-packages\urllib3\connectionpool.py", line 847, in urlopen
retries = retries.increment(
File "C:\Users\Fazel\PycharmProjects\indicators_calculate\venv\lib\site-packages\urllib3\util\retry.py", line 515, in increment
raise MaxRetryError(_pool, url, reason) from reason # type: ignore[arg-type]
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='api.cryptodatadownload.com', port=443): Max retries exceeded with url: /v1/data/ohlc/binance/available?_=1710850639991 (Caused by ProxyError('Unable to connect to proxy', SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:997)'))))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Fazel\PycharmProjects\indicators_calculate\download_hour_minute_data.py", line 54, in <module>
download_files_concurrently(API_URL)
File "C:\Users\Fazel\PycharmProjects\indicators_calculate\download_hour_minute_data.py", line 37, in download_files_concurrently
response = requests.get(api_url)
File "C:\Users\Fazel\PycharmProjects\indicators_calculate\venv\lib\site-packages\requests\api.py", line 73, in get
return request("get", url, params=params, **kwargs)
File "C:\Users\Fazel\PycharmProjects\indicators_calculate\venv\lib\site-packages\requests\api.py", line 59, in request
return session.request(method=method, url=url, **kwargs)
File "C:\Users\Fazel\PycharmProjects\indicators_calculate\venv\lib\site-packages\requests\sessions.py", line 589, in request
resp = self.send(prep, **send_kwargs)
File "C:\Users\Fazel\PycharmProjects\indicators_calculate\venv\lib\site-packages\requests\sessions.py", line 703, in send
r = adapter.send(request, **kwargs)
File "C:\Users\Fazel\PycharmProjects\indicators_calculate\venv\lib\site-packages\requests\adapters.py", line 513, in send
raise ProxyError(e, request=request)
requests.exceptions.ProxyError: HTTPSConnectionPool(host='api.cryptodatadownload.com', port=443): Max retries exceeded with url: /v1/data/ohlc/binance/available?_=1710850639991 (Caused by ProxyError('Unable to connect to proxy', SSLError(SSLEOFError(8, 'EOF occurred in violation of protocol (_ssl.c:997)'))))
|
c4572bea8741728d9eb1269d8519bfcb
|
{
"intermediate": 0.37372487783432007,
"beginner": 0.39035195112228394,
"expert": 0.23592323064804077
}
|
43,016
|
### ----------------------------------
### MINIMUM TECHNICAL REQUIREMENTS ###
### ----------------------------------
###-----------------------------------------
# 1. Choose a game you've previously written
# and copy and paste its code into the
# the code editor.
###-----------------------------------------
###-----------------------------------------
# 2. Create an endgame scenario that stops
# the game after a certain condition is met
# (e.g. time is up, a certain score is reached, etc.).
###-----------------------------------------
###-----------------------------------------
# 3. Create a function that accesses previous
# high scores, updates the scores, and
# displays the full list.
###-----------------------------------------
# 1) Read from an exisiting CSV file and
# store its data inside a variable.
# 2) Append the most recent score to the data
# and sort the data.
# 3) Write the updated data to the existing file.
# 4) Display the most recent version of said file.
CREATE: Repurpose an old game you've previously made and add the ability to store high scores!
|
7fe1d5e294be2f24c2220b24d19c0933
|
{
"intermediate": 0.3268020749092102,
"beginner": 0.43220922350883484,
"expert": 0.24098873138427734
}
|
43,017
|
using the example import csv def touch_ground(sprite, hit_sprite): """ Specifies what happens when ball hits the ground """ global file_name hit_sprite.set_x_speed(0) hit_sprite.set_y_speed(0) hit_sprite.go_to(0,0) hit_sprite.say("GAME OVER") stage.wait(1) hit_sprite.hide() show_scores(file_name) def set_stage(): """ Sets up the stage for the game """ stage.set_background("soccerfield") stage.disable_floor() def add_player(): """ Adds a player to the stage for the user to control """ player = codesters.Sprite("player1") player.go_to(0, -155) return player def add_ball(): """ Adds a ball to the stage and sets its attributes """ ball = codesters.Sprite("soccerball") ball.set_y_speed(-8) def head_ball(sprite, hit_sprite): """ Detects collisions between the player and ball """ global score score += 1 sprite.say(score) my_var = hit_sprite.get_y_speed() hit_sprite.set_y_speed(-my_var + 1) my_var = hit_sprite.get_x_speed() hit_sprite.set_x_speed(my_var + 1) def move_left(sprite): """ Moves the player left """ sprite.move_left(25) def move_right(sprite): """ Moves the player right """ sprite.move_right(25) def show_scores(file_name): """ Calls all CSV-related functions """ global score, player_name high_scores = get_high_scores(file_name) high_scores.append([player_name, score]) sort_by_score(high_scores) update_high_scores(file_name, high_scores) new_high_scores = get_high_scores(file_name) display_scores(new_high_scores) def get_high_scores(file_name): """ Returns data from CSV as list of lists """ my_file = open(file_name, "r") csv_contents = [] my_data = csv.reader(my_file) for row in my_data: row[1] = int(row[1]) csv_contents.append(row) my_file.close() return csv_contents def update_high_scores(file_name, my_data): """ Uses list of lists to write to new file """ my_file = open(file_name, "w") data_writer = csv.writer(my_file) for row in my_data: data_writer.writerow(row) my_file.close() def sort_by_score(data): """ Sort a list of lists by it's second column """ data.sort(reverse = True, key = lambda x: x[1]) def display_scores(data): """ Display the list of high scores """ for row in data: sprite = codesters.Text(row[0] + ": " + str(row[1]), -350, 200, "black") sprite.set_speed(10) sprite.move_right(350) stage.wait(1) sprite.hide() def main(): """ Sets up the program and calls other functions """ global score, player_name, file_name file_name = "headball_highscores.csv" score = 0 ground = codesters.Rectangle(0,-260, 500, 10, "green") ground.set_physics_off() ground.event_collision(touch_ground) set_stage() player = add_player() player_name = player.ask("What's your name?") add_ball() player.event_collision(head_ball) player.event_key("left", move_left) player.event_key("right", move_right) main()
add it to
import csv
# Global Variables
score = 0
player_name = ''
file_name = "headball_highscores.csv"
# Function to handle game over scenario and display high scores
def touch_ground(sprite, hit_sprite):
hit_sprite.set_x_speed(0)
hit_sprite.set_y_speed(0)
hit_sprite.go_to(0, 0)
hit_sprite.say("GAME OVER")
stage.wait(1)
hit_sprite.hide()
show_scores(file_name)
# Function to set up the game stage
def set_stage():
stage.set_background("soccerfield")
stage.disable_floor()
# Function to add a player to the stage
def add_player():
player = codesters.Sprite("player1")
player.go_to(0, -155)
return player
# Function to add a ball to the stage
def add_ball():
ball = codesters.Sprite("soccerball")
ball.set_y_speed(-8)
# Function to handle collisions between player and ball
def head_ball(sprite, hit_sprite):
global score
score += 1
sprite.say(score)
my_var = hit_sprite.get_y_speed()
hit_sprite.set_y_speed(-my_var + 1)
my_var = hit_sprite.get_x_speed()
hit_sprite.set_x_speed(my_var + 1)
# Function to move the player left
def move_left(sprite):
sprite.move_left(25)
# Function to move the player right
def move_right(sprite):
sprite.move_right(25)
# Function to show high scores
def show_scores(file_name):
global score, player_name
high_scores = get_high_scores(file_name)
high_scores.append([player_name, score])
sort_by_score(high_scores)
update_high_scores(file_name, high_scores)
new_high_scores = get_high_scores(file_name)
display_scores(new_high_scores)
# Function to get high scores from the CSV file
def get_high_scores(file_name):
csv_contents = []
with open(file_name, "r") as my_file:
my_data = csv.reader(my_file)
for row in my_data:
row[1] = int(row[1])
csv_contents.append(row)
return csv_contents
# Function to update high scores to the CSV file
def update_high_scores(file_name, my_data):
with open(file_name, "w") as my_file:
data_writer = csv.writer(my_file)
for row in my_data:
data_writer.writerow(row)
# Function to sort high scores by score
def sort_by_score(data):
data.sort(reverse=True, key=lambda x: x[1])
# Function to display high scores on the stage
def display_scores(data):
y_pos = 200
for idx, row in enumerate(data):
sprite = codesters.Text(row[0] + ": " + str(row[1]), -350, y_pos, "black")
sprite.set_speed(10)
sprite.move_right(350)
stage.wait(1)
sprite.hide()
y_pos -= 20
# Main function to set up the game and call other functions
def main():
global score, player_name, file_name
set_stage()
player = add_player()
player_name = player.ask("What's your name?")
player.event_collision(head_ball)
player.event_key("left", move_left)
player.event_key("right", move_right)
ground = codesters.Rectangle(0, -260, 500, 10, "green")
ground.set_physics_off()
ground.event_collision(touch_ground)
main()
main()
|
218217fd88745f76ad4ae9ad5123f6eb
|
{
"intermediate": 0.4458986222743988,
"beginner": 0.4434007406234741,
"expert": 0.11070070415735245
}
|
43,018
|
привет
|
f32912c64f4cf99e9ac72c16ce3dcb99
|
{
"intermediate": 0.3531447947025299,
"beginner": 0.2823599576950073,
"expert": 0.3644951581954956
}
|
43,019
|
hi
|
70709926304d82c078c87f4c9611fefd
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
43,020
|
how to calculate area of intersections between two bounding boxes in percents write code in python please
|
a4507b68ae8eefc7a1cb025b769601b2
|
{
"intermediate": 0.3174873888492584,
"beginner": 0.21568185091018677,
"expert": 0.4668307602405548
}
|
43,021
|
I have a custom Select in my React app made with rc-select library. How do I focus and blur in select by clicking on an icon?
|
5ffd630dd4f96f605e2cd7ea0309da57
|
{
"intermediate": 0.7763623595237732,
"beginner": 0.09885614365339279,
"expert": 0.1247815489768982
}
|
43,022
|
This is my code for RL algorithm, where the algorithm tune the 'action' ['L1', 'L3', 'L5', 'L6', 'L7', 'W1', 'W3', 'W5', 'W6', 'W7', 'Io', 'CP', 'VC'] with in its bounds, to get the desired target['all transistors are in saturation_condition', 'area', 'power dissipation', 'DC gain', 'Slew rate', 'Bandwidth3dB', 'Unity gain bandwidth', 'Phase margin'] with in its predefined range, from my circuit simulator where my two stage opamp circuit is simulated. Now i need to modify the existing implementation with Graph Newral Network with RL algorithm. For my new requirement What should I need to modify/update in the existing code, How should I implement the GNN with RL in the existing code and Where Should I Implement the GNN with RL. Please note: my circuit topology is fixed, i need to only tune the circuit design components values to achieve the target requirement, and utilize the learned knowledge to the unseen graph topology(unseen circuit)
from Simulator_Env1 import CircuitSimulator
class CircuitEnvironment:
def __init__(self, server_address, username, password, bounds_low, bounds_high, target_metrics):
def connect_to_simulator(self):
def disconnect_from_simulator(self):
def normalize_parameters(self, parameters):
return normalized_parameters
def encode_regions(self, transistor_regions):
return encoded_regions
def encode_saturation_condition(self, saturation_condition):
return 0
def normalize_performance_metrics(self, performance_metrics):
return normalized_metrics
def reset(self):
return state, performance_metrics
def step(self, raw_actions, previous_metrics):
return state, reward, done, previous_metrics
def is_performance_metrics_in_target(self, metrics):
return np.all(metrics >= self.PERFORMANCE_METRICS_TARGET_LOW) and np.all(metrics <= self.PERFORMANCE_METRICS_TARGET_HIGH)
def calculate_reward(self, c_metrics, p_metrics, transistor_regions, previous_transistor_regions):
return reward
def check_done(self, performance_metrics, encoded_saturation_condition):
return True
def initialize_actor_critic_networks(self, state_size, action_size, hidden_sizes_actor, hidden_sizes_critic, action_std_init, learning_rate_actor, learning_rate_critic, bounds_low, bounds_high):
self.actor = ActorNetwork(state_size, action_size, hidden_sizes_actor, bounds_low, bounds_high, action_std_init)
self.critic = CriticNetwork(state_size, hidden_sizes_critic)
self.optimizer_actor = optim.Adam(self.actor.parameters(), lr=learning_rate_actor)
self.optimizer_critic = optim.Adam(self.critic.parameters(), lr=learning_rate_critic)
# Define the Actor and Critic Networks
class ActorNetwork(nn.Module):
def __init__(self, state_size, action_size, hidden_sizes, bounds_low, bounds_high, action_std_init):
def forward(self, state):
return action_mean, log_std
def scale_action(self, action):
return scaled_action
class CriticNetwork(nn.Module):
def __init__(self, state_size, hidden_sizes):
def forward(self, state):
return value
# Select Action Function
def select_action(state, actor, critic, performance_metrics):
return action.detach().numpy(), log_prob, value.squeeze().detach().numpy(), performance_metrics
# Generalized Advantage Estimation (GAE)
return returns, advantages
# Policy and Value Network Update Function
def update_policy(actor, critic, optimizer_actor, optimizer_critic, states, actions, old_log_probs, returns, advantages, batch_size, epsilon):
# Prepare data for training
# Create DataLoader
# Iterate over batches
for batch in dataloader:
batch_states, batch_actions, batch_old_log_probs, batch_returns, batch_advantages = batch
# Compute new log probabilities and values
# Compute PPO loss for actor
# Compute value loss for critic
# Update actor and critic
# Constants
# Define the values for server_address, username, password, bounds, and target metrics
# Define the constants and target metrics for reward calculation
# Create the environment
env = CircuitEnvironment(server_address, username, password, bounds_low, bounds_high, target_metrics)
# Initialize Networks and Optimizers
env.initialize_actor_critic_networks(state_size, action_size, hidden_sizes_actor, hidden_sizes_critic, action_std_init, learning_rate_actor, learning_rate_critic, bounds_low, bounds_high)
# Set the Hyperparameters
# Set initial epsilon value and decay rate
# Training Loop
for episode in range(num_episodes):
# Define the Training Loop
state, performance_metrics = env.reset()
# Run one episode
for t in range(max_timesteps):
action, log_prob, value, perf_metrics = select_action(state, env.actor, env.critic, performance_metrics)
action = np.clip(action, bounds_low, bounds_high)
next_state, reward, done, previous_metrics = env.step(action, perf_metrics) # Take action in environment
performance_metrics = previous_metrics
state = next_state
if done:
break
# Compute returns and advantages
# Update policy and value network
# Update epsilon
# Log episode information
total_reward = sum(episode_rewards)
env.disconnect_from_simulator()
|
70b644d455fbdf2d75fe87b52afe3574
|
{
"intermediate": 0.35288378596305847,
"beginner": 0.3964223265647888,
"expert": 0.2506938576698303
}
|
43,023
|
in this javascript when the 'game over' message is displayed I want the map bounds to be set to fit all the markers that have been added to the map during the game - 'let streetLatitude; // Define streetLatitude globally
let streetLongitude; // Define streetLongitude globally
let marker; // Define marker globally to make it accessible across functions
let data; // Declare data globally
let currentIndex = 0; // Initialize index globally
let totalScore = 0; // Initialize total points variable
function fetchStreetDetails() {
fetch("main.json")
.then((response) => response.json())
.then((jsonData) => {
data = jsonData; // Store the data globally
const entryCount = data.length; // data is already an array of objects
const streetDetails = data[0];
// Extract street details
streetLatitude = streetDetails.StreetLatitude;
streetLongitude = streetDetails.StreetLongitude;
streetHeading = streetDetails.StreetHeading;
streetPitch = streetDetails.StreetPitch;
streetPanoID = streetDetails.StreetPanoID;
const StreetPoints = streetDetails.Points;
const panorama = new google.maps.StreetViewPanorama(
document.getElementById("streetview"),
{
position: { lat: streetLatitude, lng: streetLongitude },
addressControl: false,
pano: streetPanoID,
heading: streetHeading,
pitch: streetPitch,
}
);
console.log("Street Latitude: " + streetLatitude);
console.log("Street Longitude: " + streetLongitude);
console.log("Street Heading: " + streetHeading);
console.log("Street Pitch: " + streetPitch);
console.log("Street PanoID: " + streetPanoID);
console.log("Street Location: " + StreetPoints);
// Update numberoffeeds div
const numberoffeedsElement =
document.getElementById("numberoffeeds");
numberoffeedsElement.textContent = `There are ${entryCount} questions in this game.`;
})
.catch((error) => console.error("Error fetching data: ", error));
}
fetchStreetDetails();
function initMap() {
const mapStyles = [
{
featureType: "poi",
stylers: [
{
visibility: "off",
},
],
},
{
featureType: "poi.park",
stylers: [
{
visibility: "off",
},
],
},
{
"featureType": "transit",
"stylers": [
{
"visibility": "off"
}
]
}
];
const mapOptions = {
center: { lat: 21.382325, lng: -8.170154652 },
zoom: 3,
styles: mapStyles,
};
const map = new google.maps.Map(
document.getElementById("map"),
mapOptions
);
// Function to add marker on click
function addMarker(event) {
const clickLocation = event.latLng;
marker = new google.maps.Marker({
position: clickLocation,
map: map,
draggable: true, // Set draggable to true
});
// Remove the click listener after adding a marker
google.maps.event.removeListener(clickListener);
// Add functionality after clicking the map
createSubmitButton(clickLocation);
}
// Define the CSS animation style separately (outside the button creation)
document.head.insertAdjacentHTML(
"beforeend",
`
<style>
.nextButtonAnimation {
animation: flip 1s ease-in-out 1 alternate forwards;
perspective: 1000px; /* Set perspective for 3D effect */
}
@keyframes flip {
0% { transform: rotateY(0deg); }
50% { transform: rotateY(-180deg); }
100% { transform: rotateY(0deg); }
}
</style>
`
);
// Create a function to add the submit button
function createSubmitButton(distance, clickLocation) {
const buttonsDiv = document.getElementById("buttons");
// Check if the button already exists before creating a new one
if (!document.getElementById("submit")) {
const submitButton = document.createElement("button");
submitButton.id = "submit";
submitButton.textContent = `Submit`;
submitButton.className = "button";
// Add event listener for the submit button (you can define the functionality here)
submitButton.addEventListener("click", () => {
console.log("Submit button clicked!");
// Create the new button
const nextButton = document.createElement("button");
nextButton.id = "nextButton";
nextButton.textContent = "Next"; // Customize button text as needed
nextButton.className = "nextbutton";
// Apply CSS animation class for easy management
nextButton.classList.add("nextButtonAnimation");
// Add event listener for the new button (optional, if needed)
nextButton.addEventListener("click", () => {
// Create a LatLng object representing the new position
const newLatLng = new google.maps.LatLng(21.382325, -8.170154652);
// Set the map center and zoom level
map.setCenter(newLatLng);
map.setZoom(3);
// Handle ‘nextButton’ click here
console.log("Next button clicked!");
buttons.removeChild(nextButton);
const wheremessage = "Next location. Where is this?";
// Update the 'results' div using DOM manipulation
const resultsDiv = document.getElementById("results");
resultsDiv.textContent = wheremessage;
// Check if there is next entry in the data
if (data && currentIndex < data.length - 1) {
currentIndex++; // Update the index to get the next street view details
const nextStreetDetails = data[currentIndex];
streetLatitude = nextStreetDetails.StreetLatitude;
streetLongitude = nextStreetDetails.StreetLongitude;
streetHeading = nextStreetDetails.StreetHeading;
streetPitch = nextStreetDetails.StreetPitch;
streetPanoID = nextStreetDetails.StreetPanoID;
const StreetPoints = nextStreetDetails.Points;
const panorama = new google.maps.StreetViewPanorama(
document.getElementById("streetview"),
{
position: { lat: streetLatitude, lng: streetLongitude },
addressControl: false,
pano: streetPanoID,
heading: streetHeading,
pitch: streetPitch,
}
);
console.log("Street Latitude: " + streetLatitude);
console.log("Street Longitude: " + streetLongitude);
console.log("Street Heading: " + streetHeading);
console.log("Street Pitch: " + streetPitch);
console.log("Street PanoID: " + streetPanoID);
console.log("Street Location: " + StreetPoints);
// Add click listener to the map to allow marker placement
const nextClickListener = map.addListener("click", addMarker);
} else {
console.log("No next entry in the data.");
// Calculate total points
const finalScores = `Total Score: ${totalScore}`;
// Update the 'streetview' div with final scores
const streetviewDiv = document.getElementById("streetview");
streetviewDiv.innerHTML = finalScores; // Update content with innerHTML
const overmessage = "Game Over";
const resultsDiv = document.getElementById("results");
resultsDiv.textContent = overmessage;
}
});
// Replace the buttons
buttonsDiv.replaceChild(nextButton, submitButton);
// Get the current marker position when the button is pressed
const markerPosition = marker.getPosition();
// Calculate distance using marker position and street coordinates
const distance = calculateDistance(
markerPosition.lat(),
markerPosition.lng(),
streetLatitude,
streetLongitude
);
// Adjust points based on distance
let score = 5000 - distance;
if (score < 0) {
score = 0;
}
console.log(
"Distance from marker to street: " + distance + " meters. You scored: " + score
);
totalScore += score; // Add current points to total
const message =
"You scored " + score;
// Update the 'results' div using DOM manipulation
const resultsDiv = document.getElementById("results");
resultsDiv.textContent = message;
// Createpolyline on marker add
drawPolyline(clickLocation);
// Set the marker as non-draggable
marker.setDraggable(false);
});
buttonsDiv.appendChild(submitButton);
}
} // Add click listener to the map
const clickListener = map.addListener("click", addMarker);
function calculateDistance(lat1, lng1, lat2, lng2) {
const deltaLat = ((lat2 - lat1) * Math.PI) / 180;
const deltaLng = ((lng2 - lng1) * Math.PI) / 180;
const earthRadius = 6371e3; // meters
const a = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2);
const b =
Math.cos((lat1 * Math.PI) / 180) *
Math.cos((lat2 * Math.PI) / 180) *
Math.sin(deltaLng / 2) *
Math.sin(deltaLng / 2);
const c = 2 * Math.atan2(Math.sqrt(a + b), Math.sqrt(1 - a - b)); // Calculate distance using Pythagorean theorem
const distance = earthRadius * c; // Round the distance to nearest meter using Math.round()
const roundedDistance = Math.round(distance);
return roundedDistance;
} // Function to draw polyline between marker and street location
function drawPolyline() {
const markerPosition = marker.getPosition(); // Get the current position of the marker
const polyline = new google.maps.Polyline({
path: [
markerPosition.toJSON(),
{ lat: streetLatitude, lng: streetLongitude },
],
strokeColor: "#FF0000", // red color
strokeWeight: 2,
map: map,
});
// Set map bounds to encompass marker and polyline
const bounds = new google.maps.LatLngBounds(); // Use google.maps here
bounds.extend(markerPosition);
bounds.extend(polyline.getPath().getAt(1));
map.fitBounds(bounds);
}
}
'
|
b6085308a7479f3529558d702e195fb5
|
{
"intermediate": 0.4048033356666565,
"beginner": 0.37997883558273315,
"expert": 0.21521785855293274
}
|
43,024
|
How is the method that renders the list of items within the select from rc-select library called and how can I trigger it in my function?
|
7d2c3cd91a2de9389d6af357d0069e3a
|
{
"intermediate": 0.8126850724220276,
"beginner": 0.06971290707588196,
"expert": 0.11760202795267105
}
|
43,025
|
Show arduino code to drive a 3 phase bldc motor
|
ea939476fa9b7284eaae66b4a0ead4a5
|
{
"intermediate": 0.3748090863227844,
"beginner": 0.17374370992183685,
"expert": 0.45144718885421753
}
|
43,026
|
i have 1 hour timefram historical data of some cryptocurrencies as csv files
each file contains following informattion(for example for AAVEBNB):
Unix Date Symbol Open High Low Close Volume AAVE Volume BNB tradecount
1.71072E+12 3/17/2024 23:00 AAVEBNB 0.2223 0.2249 0.2211 0.2224 79.349 17.6606516 41
1.71071E+12 3/17/2024 22:00 AAVEBNB 0.2203 0.2228 0.2201 0.2211 216.352 47.9264188 109
1.71071E+12 3/17/2024 21:00 AAVEBNB 0.2184 0.2203 0.2184 0.2203 6.436 1.4140628 10
1.71071E+12 3/17/2024 20:00 AAVEBNB 0.2182 0.2185 0.2172 0.2174 24.83 5.4086803 18
...
how can i calculate 4 houre timeframe of them based on 1 hour csv files?
|
2439534e00c90554d3d2d9c18602b4e3
|
{
"intermediate": 0.4038662910461426,
"beginner": 0.240049347281456,
"expert": 0.35608434677124023
}
|
43,027
|
In this javascript I want to add a map.fitBounds(bounds); statement to the else statement after 'const finalScores = `Total Score: ${totalScore}`;' so that the map is fitted to the bounds of all the "Points" locations in the json file - 'let streetLatitude; // Define streetLatitude globally
let streetLongitude; // Define streetLongitude globally
let marker; // Define marker globally to make it accessible across functions
let data; // Declare data globally
let currentIndex = 0; // Initialize index globally
let totalScore = 0; // Initialize total points variable
function fetchStreetDetails() {
fetch("main.json")
.then((response) => response.json())
.then((jsonData) => {
data = jsonData; // Store the data globally
const entryCount = data.length; // data is already an array of objects
const streetDetails = data[0];
// Extract street details
streetLatitude = streetDetails.StreetLatitude;
streetLongitude = streetDetails.StreetLongitude;
streetHeading = streetDetails.StreetHeading;
streetPitch = streetDetails.StreetPitch;
streetPanoID = streetDetails.StreetPanoID;
const StreetPoints = streetDetails.Points;
const panorama = new google.maps.StreetViewPanorama(
document.getElementById("streetview"),
{
position: { lat: streetLatitude, lng: streetLongitude },
addressControl: false,
pano: streetPanoID,
heading: streetHeading,
pitch: streetPitch,
}
);
console.log("Street Latitude: " + streetLatitude);
console.log("Street Longitude: " + streetLongitude);
console.log("Street Heading: " + streetHeading);
console.log("Street Pitch: " + streetPitch);
console.log("Street PanoID: " + streetPanoID);
console.log("Street Location: " + StreetPoints);
// Update numberoffeeds div
const numberoffeedsElement =
document.getElementById("numberoffeeds");
numberoffeedsElement.textContent = `There are ${entryCount} questions in this game.`;
})
.catch((error) => console.error("Error fetching data: ", error));
}
fetchStreetDetails();
function initMap() {
const mapStyles = [
{
featureType: "poi",
stylers: [
{
visibility: "off",
},
],
},
{
featureType: "poi.park",
stylers: [
{
visibility: "off",
},
],
},
{
"featureType": "transit",
"stylers": [
{
"visibility": "off"
}
]
}
];
const mapOptions = {
center: { lat: 21.382325, lng: -8.170154652 },
zoom: 3,
styles: mapStyles,
};
const map = new google.maps.Map(
document.getElementById("map"),
mapOptions
);
// Function to add marker on click
function addMarker(event) {
const clickLocation = event.latLng;
marker = new google.maps.Marker({
position: clickLocation,
map: map,
draggable: true, // Set draggable to true
});
// Remove the click listener after adding a marker
google.maps.event.removeListener(clickListener);
// Add functionality after clicking the map
createSubmitButton(clickLocation);
}
// Define the CSS animation style separately (outside the button creation)
document.head.insertAdjacentHTML(
"beforeend",
`
<style>
.nextButtonAnimation {
animation: flip 1s ease-in-out 1 alternate forwards;
perspective: 1000px; /* Set perspective for 3D effect */
}
@keyframes flip {
0% { transform: rotateY(0deg); }
50% { transform: rotateY(-180deg); }
100% { transform: rotateY(0deg); }
}
</style>
`
);
// Create a function to add the submit button
function createSubmitButton(distance, clickLocation) {
const buttonsDiv = document.getElementById("buttons");
// Check if the button already exists before creating a new one
if (!document.getElementById("submit")) {
const submitButton = document.createElement("button");
submitButton.id = "submit";
submitButton.textContent = `Submit`;
submitButton.className = "button";
// Add event listener for the submit button (you can define the functionality here)
submitButton.addEventListener("click", () => {
console.log("Submit button clicked!");
// Create the new button
const nextButton = document.createElement("button");
nextButton.id = "nextButton";
nextButton.textContent = "Next"; // Customize button text as needed
nextButton.className = "nextbutton";
// Apply CSS animation class for easy management
nextButton.classList.add("nextButtonAnimation");
// Add event listener for the new button (optional, if needed)
nextButton.addEventListener("click", () => {
// Create a LatLng object representing the new position
const newLatLng = new google.maps.LatLng(21.382325, -8.170154652);
// Set the map center and zoom level
map.setCenter(newLatLng);
map.setZoom(3);
// Handle ‘nextButton’ click here
console.log("Next button clicked!");
buttons.removeChild(nextButton);
const wheremessage = "Next location. Where is this?";
// Update the 'results' div using DOM manipulation
const resultsDiv = document.getElementById("results");
resultsDiv.textContent = wheremessage;
// Check if there is next entry in the data
if (data && currentIndex < data.length - 1) {
currentIndex++; // Update the index to get the next street view details
const nextStreetDetails = data[currentIndex];
streetLatitude = nextStreetDetails.StreetLatitude;
streetLongitude = nextStreetDetails.StreetLongitude;
streetHeading = nextStreetDetails.StreetHeading;
streetPitch = nextStreetDetails.StreetPitch;
streetPanoID = nextStreetDetails.StreetPanoID;
const StreetPoints = nextStreetDetails.Points;
const panorama = new google.maps.StreetViewPanorama(
document.getElementById("streetview"),
{
position: { lat: streetLatitude, lng: streetLongitude },
addressControl: false,
pano: streetPanoID,
heading: streetHeading,
pitch: streetPitch,
}
);
console.log("Street Latitude: " + streetLatitude);
console.log("Street Longitude: " + streetLongitude);
console.log("Street Heading: " + streetHeading);
console.log("Street Pitch: " + streetPitch);
console.log("Street PanoID: " + streetPanoID);
console.log("Street Location: " + StreetPoints);
// Add click listener to the map to allow marker placement
const nextClickListener = map.addListener("click", addMarker);
} else {
console.log("No next entry in the data.");
// Calculate total points
const finalScores = `Total Score: ${totalScore}`;
// Update the 'streetview' div with final scores
const streetviewDiv = document.getElementById("streetview");
streetviewDiv.innerHTML = finalScores; // Update content with innerHTML
const overmessage = "Game Over";
const resultsDiv = document.getElementById("results");
resultsDiv.textContent = overmessage;
}
});
// Replace the buttons
buttonsDiv.replaceChild(nextButton, submitButton);
// Get the current marker position when the button is pressed
const markerPosition = marker.getPosition();
// Calculate distance using marker position and street coordinates
const distance = calculateDistance(
markerPosition.lat(),
markerPosition.lng(),
streetLatitude,
streetLongitude
);
// Adjust points based on distance
let score = 5000 - distance;
if (score < 0) {
score = 0;
}
console.log(
"Distance from marker to street: " + distance + " meters. You scored: " + score
);
totalScore += score; // Add current points to total
const message =
"You scored " + score;
// Update the 'results' div using DOM manipulation
const resultsDiv = document.getElementById("results");
resultsDiv.textContent = message;
// Createpolyline on marker add
drawPolyline(clickLocation);
// Set the marker as non-draggable
marker.setDraggable(false);
});
buttonsDiv.appendChild(submitButton);
}
} // Add click listener to the map
const clickListener = map.addListener("click", addMarker);
function calculateDistance(lat1, lng1, lat2, lng2) {
const deltaLat = ((lat2 - lat1) * Math.PI) / 180;
const deltaLng = ((lng2 - lng1) * Math.PI) / 180;
const earthRadius = 6371e3; // meters
const a = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2);
const b =
Math.cos((lat1 * Math.PI) / 180) *
Math.cos((lat2 * Math.PI) / 180) *
Math.sin(deltaLng / 2) *
Math.sin(deltaLng / 2);
const c = 2 * Math.atan2(Math.sqrt(a + b), Math.sqrt(1 - a - b)); // Calculate distance using Pythagorean theorem
const distance = earthRadius * c; // Round the distance to nearest meter using Math.round()
const roundedDistance = Math.round(distance);
return roundedDistance;
} // Function to draw polyline between marker and street location
function drawPolyline() {
const markerPosition = marker.getPosition(); // Get the current position of the marker
const polyline = new google.maps.Polyline({
path: [
markerPosition.toJSON(),
{ lat: streetLatitude, lng: streetLongitude },
],
strokeColor: "#FF0000", // red color
strokeWeight: 2,
map: map,
});
// Set map bounds to encompass marker and polyline
const bounds = new google.maps.LatLngBounds(); // Use google.maps here
bounds.extend(markerPosition);
bounds.extend(polyline.getPath().getAt(1));
map.fitBounds(bounds);
}
}
'
|
e8af6b172125ca41911eb5a5e64df1e2
|
{
"intermediate": 0.3814689517021179,
"beginner": 0.4799574315547943,
"expert": 0.1385735720396042
}
|
43,028
|
import concurrent.futures
import time
from playwright.sync_api import sync_playwright
def run_browser_session(process_number) -> bool:
with sync_playwright() as p:
# Start timer
s = time.time()
# Launch a Chromium browser
browser = p.chromium.launch(headless=False, slow_mo=1000)
context = browser.new_context()
# Start tracing for screenshots, snapshots, and sources
trace_filename = f"trace_{process_number}.zip"
context.tracing.start(screenshots=True, snapshots=True, sources=True)
# Create a new page and navigate to the website
page = context.new_page()
page.goto("https://smart.gdrfad.gov.ae/HomePage.aspx?GdfraLocale=en-US")
# Fill in username and password, then click on the login button
page.get_by_label("lblUsername").fill("john9898")
page.get_by_label("lblPassword").fill("Kalpesh@08")
page.get_by_role("button", name="Login").click()
# Click on the link to create a new application
page.get_by_role("link", name="New Application Create new").click()
# Click on the link to create a new 5 years tourism entry application
page.get_by_role("link", name="New 5 Years Tourism Entry").click()
# Fill Emirate in address inside UAE
page.locator(
"#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt629_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbAddressInsideEmiratesId").get_by_role(
"link", name="-- Select -- ").click()
page.locator("li").filter(has_text="DUBAI").click()
# Select purpose of visit
page.locator(
"#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt586_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbVisitPurpose").get_by_role(
"link", name="-- Select -- ").click()
page.locator("li").filter(has_text="Tourism").click()
# Select passport type
page.locator(
"#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt217_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbPassportTypeId").get_by_role(
"link", name="-- Select -- ").click()
page.locator("li").filter(has_text="Normal").click()
# Fill in passport number
page.get_by_label("Passport Number").fill("P100000")
# Select current nationality
page.locator(
"#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt217_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbApplicantNationality").get_by_role(
"link", name="-- Select -- ").click()
page.get_by_role("combobox", name="Current Nationality", exact=True).fill("india")
page.get_by_text("INDIA", exact=True).click()
# Select previous nationality
page.locator(
"#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt217_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbApplicantPreviousNationality").get_by_role(
"link", name="-- Select -- ").click()
page.get_by_role("combobox", name="Previous Nationality", exact=True).fill("india")
page.get_by_text("INDIA", exact=True).click()
# Click Search Data button
page.get_by_role("button", name="Search Data").click()
# Enter mother's name in english
page.get_by_label("Mother Name En").fill("SIYA DEO")
# Click button to translate mother's name to arabic
page.locator('css=div[onclick="translateInputText(\'inpMotherNameEn\');"] img').click()
# Enter mother's name in english
page.get_by_label("Mother Name En").fill("SIYA DEO")
# Fill religion
page.locator(
"#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt437_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbApplicantReligion").get_by_role(
"link", name="-- Select -- ").click()
page.locator("li").filter(has_text="HINDHU").click()
# Fill marital status
page.locator(
"#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt437_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbApplicantMaritalStatus").get_by_role(
"link", name="-- Select -- ").click()
page.locator("li").filter(has_text="SINGLE").click()
# Fill education
page.locator(
"#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt437_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbApplicantEducation").get_by_role(
"link", name="-- Select -- ").click()
page.locator("li").filter(has_text="B.SC. COMMERCE & BUSINESS ADMN").click()
# Fill language
page.locator(
"#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt437_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbApplicantLanguage1").get_by_role(
"link", name="-- Select -- ").click()
page.locator("li").filter(has_text="ENGLISH").click()
# Fill coming from country
page.locator(
"#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt437_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbComingFromCountry").get_by_role(
"link", name="-- Select -- ").click()
page.get_by_role("combobox", name="Coming From Country", exact=True).fill("india")
page.get_by_text("INDIA", exact=True).click()
# Fill bank statement country
page.locator(
"#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt437_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbBankStatementCountry").get_by_role(
"link", name="-- Select -- ").click()
page.get_by_role("combobox", name="Bank Satement Country", exact=True).fill("india")
page.get_by_text("INDIA", exact=True).click()
# Fill profession
page.get_by_placeholder("Type or click for list").click()
page.get_by_placeholder("Type or click for list").fill("MANAGER")
# Fill email
page.get_by_label("Email", exact=True).fill("rpa.support@visaero.com")
page.get_by_label("Approval Email Copy Recipient").fill("rpa.support@visaero.com")
# Fill contact details mobile number
page.locator(
"#EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt629_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtinpMobileNumber").fill(
"0559856719")
# Fill preferred sms langauge
page.locator(
"#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt629_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbPreferredLanguage").get_by_role(
"link", name="-- Select -- ").click()
page.locator("li").filter(has_text="ENGLISH").click()
# Click address inside the UAE city
page.locator(
"#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt629_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbAddressInsideCityId").get_by_role(
"link", name="-- Select -- ").click()
page.locator("li").filter(has_text="Dubai").click()
# Fill address inside the UAE street, building/villa, floor and flat/villa number
page.get_by_label("Street").fill("SHAIKH ZAYED ROAD")
page.get_by_label("Building/Villa").fill("LATIFA TOWER")
page.get_by_label("Floor").fill("3")
page.get_by_label("Flat/Villa no.").fill("310")
# Fill address outside the UAE country, city
page.locator(
"#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt629_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbApplicantOutsideCountry").get_by_role(
"link", name="-- Select -- ").click()
page.get_by_role("combobox", name="Country", exact=True).fill("india")
page.get_by_text("INDIA", exact=True).click()
page.get_by_role("textbox", name="City *").fill("MUMBAI")
# Fill address outside the UAE address
page.get_by_label("Address").fill("MALAPPURAM DIST, KERALA -676507.^H301318430/03/2009 JEDDAH")
# Fill address outside the UAE mobile number
page.locator(
"#EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt629_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtinpAddressOutsideMobileNumber").click()
page.locator(
"#EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt629_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtinpAddressOutsideMobileNumber").press_sequentially(
"0501234567")
# Fill applicant faith
page.locator(
"#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt437_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbApplicantFaith").get_by_role(
"link", name="-- Select -- ").click()
page.locator("li").filter(has_text="UnKnown").click()
# Address Inside UAE area
page.get_by_role("link", name="Select Area ").click()
page.locator("li").filter(has_text="Trade Centre 1").click()
# Go on next page
# page.get_by_role("button", name="Continue").click()
# Stop tracing and close the context and browser
context.tracing.stop(path=trace_filename)
# ---------------------
context.close()
browser.close()
# End timer
e = time.time()
# Print time taken
print(f"Process {process_number}: {e - s}")
return True
def main():
with concurrent.futures.ProcessPoolExecutor(max_workers=4) as executor:
futures = [executor.submit(run_browser_session, i + 1) for i in range(4)]
if __name__ == "__main__":
main()
each process should run n number of threads. threads should execute after previous thread has finished
|
4fd9aa76c32c428eae388892d993811a
|
{
"intermediate": 0.35259759426116943,
"beginner": 0.36844804883003235,
"expert": 0.27895432710647583
}
|
43,029
|
In the rc-select library How do I cause to render dropdown menu without clicking on select but instead by clicking on a button?
|
8cd72dd45f5c7c99493c734a7e797b81
|
{
"intermediate": 0.7941488027572632,
"beginner": 0.09705399721860886,
"expert": 0.10879719257354736
}
|
43,030
|
import concurrent.futures
import time
from playwright.sync_api import sync_playwright
def run_browser_session(process_number) -> bool:
with sync_playwright() as p:
# Start timer
s = time.time()
# Launch a Chromium browser
browser = p.chromium.launch(headless=False, slow_mo=1000)
context = browser.new_context()
# Start tracing for screenshots, snapshots, and sources
trace_filename = f"trace_{process_number}.zip"
context.tracing.start(screenshots=True, snapshots=True, sources=True)
# Create a new page and navigate to the website
page = context.new_page()
page.goto(“https://smart.gdrfad.gov.ae/HomePage.aspx?GdfraLocale=en-US”)
# Fill in username and password, then click on the login button
page.get_by_label(“lblUsername”).fill(“john9898”)
page.get_by_label(“lblPassword”).fill(“Kalpesh@08”)
page.get_by_role(“button”, name=“Login”).click()
# Click on the link to create a new application
page.get_by_role(“link”, name=“New Application Create new”).click()
# Click on the link to create a new 5 years tourism entry application
page.get_by_role(“link”, name=“New 5 Years Tourism Entry”).click()
# Fill Emirate in address inside UAE
page.locator(
“#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt629_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbAddressInsideEmiratesId”).get_by_role(
“link”, name=“-- Select – ”).click()
page.locator(“li”).filter(has_text=“DUBAI”).click()
# Select purpose of visit
page.locator(
“#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt586_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbVisitPurpose”).get_by_role(
“link”, name=“-- Select – ”).click()
page.locator(“li”).filter(has_text=“Tourism”).click()
# Select passport type
page.locator(
“#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt217_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbPassportTypeId”).get_by_role(
“link”, name=“-- Select – ”).click()
page.locator(“li”).filter(has_text=“Normal”).click()
# Fill in passport number
page.get_by_label(“Passport Number”).fill(“P100000”)
# Select current nationality
page.locator(
“#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt217_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbApplicantNationality”).get_by_role(
“link”, name=“-- Select – ”).click()
page.get_by_role(“combobox”, name=“Current Nationality”, exact=True).fill(“india”)
page.get_by_text(“INDIA”, exact=True).click()
# Select previous nationality
page.locator(
“#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt217_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbApplicantPreviousNationality”).get_by_role(
“link”, name=“-- Select – ”).click()
page.get_by_role(“combobox”, name=“Previous Nationality”, exact=True).fill(“india”)
page.get_by_text(“INDIA”, exact=True).click()
# Click Search Data button
page.get_by_role(“button”, name=“Search Data”).click()
# Enter mother’s name in english
page.get_by_label(“Mother Name En”).fill(“SIYA DEO”)
# Click button to translate mother’s name to arabic
page.locator(‘css=div[onclick=“translateInputText(‘inpMotherNameEn’);”] img’).click()
# Enter mother’s name in english
page.get_by_label(“Mother Name En”).fill(“SIYA DEO”)
# Fill religion
page.locator(
“#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt437_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbApplicantReligion”).get_by_role(
“link”, name=“-- Select – ”).click()
page.locator(“li”).filter(has_text=“HINDHU”).click()
# Fill marital status
page.locator(
“#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt437_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbApplicantMaritalStatus”).get_by_role(
“link”, name=“-- Select – ”).click()
page.locator(“li”).filter(has_text=“SINGLE”).click()
# Fill education
page.locator(
“#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt437_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbApplicantEducation”).get_by_role(
“link”, name=“-- Select – ”).click()
page.locator(“li”).filter(has_text=“B.SC. COMMERCE & BUSINESS ADMN”).click()
# Fill language
page.locator(
“#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt437_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbApplicantLanguage1”).get_by_role(
“link”, name=“-- Select – ”).click()
page.locator(“li”).filter(has_text=“ENGLISH”).click()
# Fill coming from country
page.locator(
“#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt437_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbComingFromCountry”).get_by_role(
“link”, name=“-- Select – ”).click()
page.get_by_role(“combobox”, name=“Coming From Country”, exact=True).fill(“india”)
page.get_by_text(“INDIA”, exact=True).click()
# Fill bank statement country
page.locator(
“#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt437_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbBankStatementCountry”).get_by_role(
“link”, name=“-- Select – ”).click()
page.get_by_role(“combobox”, name=“Bank Satement Country”, exact=True).fill(“india”)
page.get_by_text(“INDIA”, exact=True).click()
# Fill profession
page.get_by_placeholder(“Type or click for list”).click()
page.get_by_placeholder(“Type or click for list”).fill(“MANAGER”)
# Fill email
page.get_by_label(“Email”, exact=True).fill(“<PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>”)
page.get_by_label(“Approval Email Copy Recipient”).fill(“<PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>”)
# Fill contact details mobile number
page.locator(
“#EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt629_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtinpMobileNumber”).fill(
“0559856719”)
# Fill preferred sms langauge
page.locator(
“#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt629_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbPreferredLanguage”).get_by_role(
“link”, name=“-- Select – ”).click()
page.locator(“li”).filter(has_text=“ENGLISH”).click()
# Click address inside the UAE city
page.locator(
“#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt629_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbAddressInsideCityId”).get_by_role(
“link”, name=“-- Select – ”).click()
page.locator(“li”).filter(has_text=“Dubai”).click()
# Fill address inside the UAE street, building/villa, floor and flat/villa number
page.get_by_label(“Street”).fill(“SHAIKH ZAYED ROAD”)
page.get_by_label(“Building/Villa”).fill(“LATIFA TOWER”)
page.get_by_label(“Floor”).fill(“3”)
page.get_by_label(“Flat/Villa no.”).fill(“310”)
# Fill address outside the UAE country, city
page.locator(
“#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt629_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbApplicantOutsideCountry”).get_by_role(
“link”, name=“-- Select – ”).click()
page.get_by_role(“combobox”, name=“Country”, exact=True).fill(“india”)
page.get_by_text(“INDIA”, exact=True).click()
page.get_by_role(“textbox”, name=“City *”).fill(“MUMBAI”)
# Fill address outside the UAE address
page.get_by_label(“Address”).fill(“MALAPPURAM DIST, KERALA -676507.^H301318430/03/2009 JEDDAH”)
# Fill address outside the UAE mobile number
page.locator(
“#EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt629_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtinpAddressOutsideMobileNumber”).click()
page.locator(
“#EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt629_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtinpAddressOutsideMobileNumber”).press_sequentially(
“0501234567”)
# Fill applicant faith
page.locator(
“#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt437_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbApplicantFaith”).get_by_role(
“link”, name=“-- Select – ”).click()
page.locator(“li”).filter(has_text=“UnKnown”).click()
# Address Inside UAE area
page.get_by_role(“link”, name=“Select Area ”).click()
page.locator(“li”).filter(has_text=“Trade Centre 1”).click()
# Go on next page
# page.get_by_role(“button”, name=“Continue”).click()
# Stop tracing and close the context and browser
context.tracing.stop(path=trace_filename)
# ---------------------
context.close()
browser.close()
# End timer
e = time.time()
# Print time taken
print(f"Process {process_number}: {e - s}")
return True
def main():
with concurrent.futures.ProcessPoolExecutor(max_workers=4) as executor:
futures = [executor.submit(run_browser_session, i + 1) for i in range(4)]
if name == “main”:
main()
each process should run n number of threads. threads should execute after previous thread has finished. also rename the trace.zip so that it contains process number and thread number
|
d0d58776ce30e5008012e64f3213043a
|
{
"intermediate": 0.32990938425064087,
"beginner": 0.46914997696876526,
"expert": 0.20094060897827148
}
|
43,031
|
import concurrent.futures
import time
from playwright.sync_api import sync_playwright
def run_browser_session(process_number) -> bool:
with sync_playwright() as p:
# Start timer
s = time.time()
# Launch a Chromium browser
browser = p.chromium.launch(headless=False, slow_mo=1000)
context = browser.new_context()
# Start tracing for screenshots, snapshots, and sources
trace_filename = f"trace_{process_number}.zip"
context.tracing.start(screenshots=True, snapshots=True, sources=True)
# Create a new page and navigate to the website
page = context.new_page()
page.goto(“https://smart.gdrfad.gov.ae/HomePage.aspx?GdfraLocale=en-US”)
# Fill in username and password, then click on the login button
page.get_by_label(“lblUsername”).fill(“john9898”)
page.get_by_label(“lblPassword”).fill(“Kalpesh@08”)
page.get_by_role(“button”, name=“Login”).click()
# Click on the link to create a new application
page.get_by_role(“link”, name=“New Application Create new”).click()
# Click on the link to create a new 5 years tourism entry application
page.get_by_role(“link”, name=“New 5 Years Tourism Entry”).click()
# Fill Emirate in address inside UAE
page.locator(
“#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt629_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbAddressInsideEmiratesId”).get_by_role(
“link”, name=“-- Select – ”).click()
page.locator(“li”).filter(has_text=“DUBAI”).click()
# Select purpose of visit
page.locator(
“#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt586_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbVisitPurpose”).get_by_role(
“link”, name=“-- Select – ”).click()
page.locator(“li”).filter(has_text=“Tourism”).click()
# Select passport type
page.locator(
“#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt217_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbPassportTypeId”).get_by_role(
“link”, name=“-- Select – ”).click()
page.locator(“li”).filter(has_text=“Normal”).click()
# Fill in passport number
page.get_by_label(“Passport Number”).fill(“P100000”)
# Select current nationality
page.locator(
“#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt217_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbApplicantNationality”).get_by_role(
“link”, name=“-- Select – ”).click()
page.get_by_role(“combobox”, name=“Current Nationality”, exact=True).fill(“india”)
page.get_by_text(“INDIA”, exact=True).click()
# Select previous nationality
page.locator(
“#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt217_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbApplicantPreviousNationality”).get_by_role(
“link”, name=“-- Select – ”).click()
page.get_by_role(“combobox”, name=“Previous Nationality”, exact=True).fill(“india”)
page.get_by_text(“INDIA”, exact=True).click()
# Click Search Data button
page.get_by_role(“button”, name=“Search Data”).click()
# Enter mother’s name in english
page.get_by_label(“Mother Name En”).fill(“SIYA DEO”)
# Click button to translate mother’s name to arabic
page.locator(‘css=div[onclick=“translateInputText(‘inpMotherNameEn’);”] img’).click()
# Enter mother’s name in english
page.get_by_label(“Mother Name En”).fill(“SIYA DEO”)
# Fill religion
page.locator(
“#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt437_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbApplicantReligion”).get_by_role(
“link”, name=“-- Select – ”).click()
page.locator(“li”).filter(has_text=“HINDHU”).click()
# Fill marital status
page.locator(
“#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt437_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbApplicantMaritalStatus”).get_by_role(
“link”, name=“-- Select – ”).click()
page.locator(“li”).filter(has_text=“SINGLE”).click()
# Fill education
page.locator(
“#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt437_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbApplicantEducation”).get_by_role(
“link”, name=“-- Select – ”).click()
page.locator(“li”).filter(has_text=“B.SC. COMMERCE & BUSINESS ADMN”).click()
# Fill language
page.locator(
“#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt437_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbApplicantLanguage1”).get_by_role(
“link”, name=“-- Select – ”).click()
page.locator(“li”).filter(has_text=“ENGLISH”).click()
# Fill coming from country
page.locator(
“#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt437_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbComingFromCountry”).get_by_role(
“link”, name=“-- Select – ”).click()
page.get_by_role(“combobox”, name=“Coming From Country”, exact=True).fill(“india”)
page.get_by_text(“INDIA”, exact=True).click()
# Fill bank statement country
page.locator(
“#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt437_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbBankStatementCountry”).get_by_role(
“link”, name=“-- Select – ”).click()
page.get_by_role(“combobox”, name=“Bank Satement Country”, exact=True).fill(“india”)
page.get_by_text(“INDIA”, exact=True).click()
# Fill profession
page.get_by_placeholder(“Type or click for list”).click()
page.get_by_placeholder(“Type or click for list”).fill(“MANAGER”)
# Fill email
page.get_by_label(“Email”, exact=True).fill(“<PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>”)
page.get_by_label(“Approval Email Copy Recipient”).fill(“<PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>”)
# Fill contact details mobile number
page.locator(
“#EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt629_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtinpMobileNumber”).fill(
“0559856719”)
# Fill preferred sms langauge
page.locator(
“#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt629_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbPreferredLanguage”).get_by_role(
“link”, name=“-- Select – ”).click()
page.locator(“li”).filter(has_text=“ENGLISH”).click()
# Click address inside the UAE city
page.locator(
“#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt629_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbAddressInsideCityId”).get_by_role(
“link”, name=“-- Select – ”).click()
page.locator(“li”).filter(has_text=“Dubai”).click()
# Fill address inside the UAE street, building/villa, floor and flat/villa number
page.get_by_label(“Street”).fill(“SHAIKH ZAYED ROAD”)
page.get_by_label(“Building/Villa”).fill(“LATIFA TOWER”)
page.get_by_label(“Floor”).fill(“3”)
page.get_by_label(“Flat/Villa no.”).fill(“310”)
# Fill address outside the UAE country, city
page.locator(
“#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt629_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbApplicantOutsideCountry”).get_by_role(
“link”, name=“-- Select – ”).click()
page.get_by_role(“combobox”, name=“Country”, exact=True).fill(“india”)
page.get_by_text(“INDIA”, exact=True).click()
page.get_by_role(“textbox”, name=“City *”).fill(“MUMBAI”)
# Fill address outside the UAE address
page.get_by_label(“Address”).fill(“MALAPPURAM DIST, KERALA -676507.^H301318430/03/2009 JEDDAH”)
# Fill address outside the UAE mobile number
page.locator(
“#EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt629_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtinpAddressOutsideMobileNumber”).click()
page.locator(
“#EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt629_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtinpAddressOutsideMobileNumber”).press_sequentially(
“0501234567”)
# Fill applicant faith
page.locator(
“#s2id_EmaratechSG_Theme_wt789_block_wtFormContent_SmartChannels_Application_CW_wt437_block_WebPatterns_wtcntAppSimpleSecExpandable_block_wtContent_wtContent_wtcmbApplicantFaith”).get_by_role(
“link”, name=“-- Select – ”).click()
page.locator(“li”).filter(has_text=“UnKnown”).click()
# Address Inside UAE area
page.get_by_role(“link”, name=“Select Area ”).click()
page.locator(“li”).filter(has_text=“Trade Centre 1”).click()
# Go on next page
# page.get_by_role(“button”, name=“Continue”).click()
# Stop tracing and close the context and browser
context.tracing.stop(path=trace_filename)
# ---------------------
context.close()
browser.close()
# End timer
e = time.time()
# Print time taken
print(f"Process {process_number}: {e - s}")
return True
def main():
with concurrent.futures.ProcessPoolExecutor(max_workers=4) as executor:
futures = [executor.submit(run_browser_session, i + 1) for i in range(4)]
if name == “main”:
main()
each process should run n number of threads. threads should execute after previous thread has finished. also rename the trace.zip so that it contains process number and thread number
|
f3f72fc334a277e58890eb4b98f2fc59
|
{
"intermediate": 0.32990938425064087,
"beginner": 0.46914997696876526,
"expert": 0.20094060897827148
}
|
43,032
|
"import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import cv2
import random
import tensorflow as tf
import tkinter as tk
from tkinter import filedialog
from PIL import ImageTk, Image
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
from IPython.display import display, clear_output
from tensorflow.keras.preprocessing import image
from tensorflow.keras.optimizers import Adam, SGD, RMSprop, AdamW, Adadelta, Adagrad, Adamax, Adafactor, Nadam, Ftrl
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tqdm import tqdm
import os
from sklearn.utils import shuffle
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential, Model, load_model
from tensorflow.keras.layers import (
GlobalAveragePooling2D,
Dropout,
Dense,
Conv2D,
MaxPooling2D,
Flatten,
Dropout,
BatchNormalization,
Activation,
concatenate,
Conv2DTranspose,
Input,
Reshape,
UpSampling2D,
)
from tensorflow.keras.applications import (
EfficientNetV2B0,
EfficientNetV2B1,
EfficientNetV2B2,
EfficientNetV2B3,
EfficientNetV2L,
EfficientNetV2M,
EfficientNetV2S,
)
from tensorflow.keras.applications import Xception
from tensorflow.keras.applications import VGG16, VGG19
from tensorflow.keras.applications import ResNet50, ResNet101, ResNet152, ResNetRS50, ResNetRS101
from tensorflow.keras.applications import InceptionResNetV2, ConvNeXtXLarge, ConvNeXtBase, DenseNet121, MobileNetV2, NASNetLarge, NASNetMobile
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, TensorBoard, ModelCheckpoint
from sklearn.metrics import classification_report, confusion_matrix
import ipywidgets as widgets
import io
from PIL import Image
from IPython.display import display, clear_output
from warnings import filterwarnings
from google.colab import drive
drive.mount("/content/gdrive")
def load_data(data_folders):
X_data = [] # Combined data
y_class_labels = [] # Combined classification labels
y_seg_labels = [] # Combined segmentation labels
for folderPath in data_folders:
for label in labels:
label_folder_path = os.path.join(folderPath, label)
for filename in tqdm(os.listdir(label_folder_path)):
if filename.endswith(".jpg"):
img = cv2.imread(os.path.join(label_folder_path, filename))
img = cv2.resize(img, (image_size, image_size))
X_data.append(img)
y_class_labels.append(label)
seg_filename = filename.split(".")[0] + ".png"
seg_img = cv2.imread(os.path.join(label_folder_path, seg_filename), 0)
seg_img = cv2.resize(seg_img, (image_size, image_size))
seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary
y_seg_labels.append(seg_img)
X_data = np.array(X_data)
y_class_labels = np.array(y_class_labels)
y_seg_labels = np.array(y_seg_labels)
X_data, y_class_labels, y_seg_labels = shuffle(X_data, y_class_labels, y_seg_labels, random_state=101)
return X_data, y_class_labels, y_seg_labels
def split_data(X_data, y_class_labels, y_seg_labels, class_data_counts):
X_train = []
y_train_class = []
y_train_seg = []
X_val = []
y_val_class = []
y_val_seg = []
X_test = []
y_test_class = []
y_test_seg = []
for label, count in class_data_counts.items():
label_indices = np.where(y_class_labels == label)[0]
class_X_data = X_data[label_indices]
class_y_class_labels = y_class_labels[label_indices]
class_y_seg_labels = y_seg_labels[label_indices]
train_count = count[0]
val_count = count[1]
test_count = count[2]
class_X_train = class_X_data[:train_count]
class_y_train_class = class_y_class_labels[:train_count]
class_y_train_seg = class_y_seg_labels[:train_count]
class_X_val = class_X_data[train_count: train_count + val_count]
class_y_val_class = class_y_class_labels[train_count: train_count + val_count]
class_y_val_seg = class_y_seg_labels[train_count: train_count + val_count]
class_X_test = class_X_data[train_count + val_count: train_count + val_count + test_count]
class_y_test_class = class_y_class_labels[train_count + val_count: train_count + val_count + test_count]
class_y_test_seg = class_y_seg_labels[train_count + val_count: train_count + val_count + test_count]
X_train.extend(class_X_train)
y_train_class.extend(class_y_train_class)
y_train_seg.extend(class_y_train_seg)
X_val.extend(class_X_val)
y_val_class.extend(class_y_val_class)
y_val_seg.extend(class_y_val_seg)
X_test.extend(class_X_test)
y_test_class.extend(class_y_test_class)
y_test_seg.extend(class_y_test_seg)
# Convert class labels to categorical
label_encoder = LabelEncoder()
y_train_class_encoded = label_encoder.fit_transform(y_train_class)
y_train_class_categorical = to_categorical(y_train_class_encoded)
y_val_class_encoded = label_encoder.transform(y_val_class)
y_val_class_categorical = to_categorical(y_val_class_encoded)
y_test_class_encoded = label_encoder.transform(y_test_class)
y_test_class_categorical = to_categorical(y_test_class_encoded)
return (
np.array(X_train),
np.array(y_train_class_categorical),
np.array(y_train_seg),
np.array(X_val),
np.array(y_val_class_categorical),
np.array(y_val_seg),
np.array(X_test),
np.array(y_test_class_categorical),
np.array(y_test_seg),
)
def count_labels(y_class_categorical, label_encoder):
# Convert one-hot encoded labels back to label encoded
y_class_labels = np.argmax(y_class_categorical, axis=1)
# Convert label encoded labels back to original class names
y_class_names = label_encoder.inverse_transform(y_class_labels)
unique, counts = np.unique(y_class_names, return_counts=True)
return dict(zip(unique, counts))
def build_model(input_shape, num_classes):
num_filter = 32 # 16/32 best, 8: best classification but no segment
# Encoder (Done)
inputs = Input(input_shape)
conv1 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(inputs)
bn1 = BatchNormalization()(conv1)
relu1 = Activation("relu")(bn1)
conv2 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu1)
bn2 = BatchNormalization()(conv2)
relu2 = Activation("relu")(bn2)
down1 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu2)
conv3 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(down1)
bn3 = BatchNormalization()(conv3)
relu3 = Activation("relu")(bn3)
conv4 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu3)
bn4 = BatchNormalization()(conv4)
relu4 = Activation("relu")(bn4)
down2 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu4)
conv5 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(down2)
bn5 = BatchNormalization()(conv5)
relu5 = Activation("relu")(bn5)
conv6 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu5)
bn6 = BatchNormalization()(conv6)
relu6 = Activation("relu")(bn6)
down3 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu6)
conv7 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(down3)
bn7 = BatchNormalization()(conv7)
relu7 = Activation("relu")(bn7)
conv8 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu7)
bn8 = BatchNormalization()(conv8)
relu8 = Activation("relu")(bn8)
# Middle
down4 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu8)
conv9 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(down4)
bn9 = BatchNormalization()(conv9)
relu9 = Activation("relu")(bn9)
conv10 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(relu9)
bn10 = BatchNormalization()(conv10)
relu10 = Activation("relu")(bn10)
up1 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu10)
# Decoder (Done)
concat1 = concatenate([up1, relu8], axis=-1) # , axis=3
conv11 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(concat1)
bn11 = BatchNormalization()(conv11)
relu11 = Activation("relu")(bn11)
conv12 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu11)
bn12 = BatchNormalization()(conv12)
relu12 = Activation("relu")(bn12)
up2 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu12)
concat2 = concatenate([up2, relu6], axis=-1) # , axis=3
conv13 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(concat2)
bn13 = BatchNormalization()(conv13)
relu13 = Activation("relu")(bn13)
conv14 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu13)
bn14 = BatchNormalization()(conv14)
relu14 = Activation("relu")(bn14)
up3 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu14)
concat3 = concatenate([up3, relu4], axis=-1) # , axis=3
conv15 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(concat3)
bn15 = BatchNormalization()(conv15)
relu15 = Activation("relu")(bn15)
conv16 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu15)
bn16 = BatchNormalization()(conv16)
relu16 = Activation("relu")(bn16)
up4 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu16)
concat4 = concatenate([up4, relu2], axis=-1) # , axis=3
conv17 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(concat4)
bn17 = BatchNormalization()(conv17)
relu17 = Activation("relu")(bn17)
conv18 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu17)
bn18 = BatchNormalization()(conv18)
relu18 = Activation("relu")(bn18)
# Segmentation branch
segmentation_output = Conv2D(1, 1, activation="sigmoid", name="segmentation_output")(relu18) # original
# Classification branch (Not done)
gap1 = GlobalAveragePooling2D()(relu8)
gap2 = GlobalAveragePooling2D()(relu10)
gap3 = GlobalAveragePooling2D()(relu12)
conv20 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(segmentation_output)
bn20 = BatchNormalization()(conv20)
relu20 = Activation("relu")(bn20)
down5 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu20)
conv21 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(down5)
bn21 = BatchNormalization()(conv21)
relu21 = Activation("relu")(bn21)
down6 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu21)
conv22 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(down6)
bn22 = BatchNormalization()(conv22)
relu22 = Activation("relu")(bn22)
down7 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu22)
flatten1 = Flatten()(down7)
concat5 = concatenate([gap1, gap2, gap3, flatten1], axis=-1)
# FC layers
fc1 = Dense(2048, activation="relu")(concat5)
dropout1 = Dropout(0.5)(fc1)
fc2 = Dense(1024, activation="relu")(dropout1)
dropout2 = Dropout(0.5)(fc2)
classification_output = Dense(num_classes, activation="softmax", name="classification_output")(dropout2)
# Define the model
model = Model(inputs=inputs, outputs=[classification_output, segmentation_output])
return model
def segmentation_loss(y_true, y_pred):
y_true = tf.cast(y_true, tf.float32)
y_pred = tf.cast(y_pred, tf.float32)
bce_loss = tf.keras.losses.binary_crossentropy(y_true, y_pred)
smooth = 1e-5
intersection = tf.reduce_sum(y_true * y_pred)
union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred)
dice_loss = 1.0 - 2.0 * (intersection + smooth) / (union + smooth)
segmentation_loss = bce_loss + 1 * dice_loss
return segmentation_loss
def train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs):
checkpoint = ModelCheckpoint(
"multitask_best_weights.h5",
monitor="val_classification_output_accuracy",
save_best_only=True,
mode="max",
verbose=1,)
reduce_lr = ReduceLROnPlateau(
monitor="val_classification_output_accuracy",
factor=0.3,
patience=2,
min_delta=0.001,
mode="auto",
verbose=1,)
tensorboard = TensorBoard(log_dir="logs")
model.compile(
optimizer=Adam(lr=0.000001),
loss={"classification_output": "categorical_crossentropy", "segmentation_output": segmentation_loss},
metrics={"classification_output": "accuracy", "segmentation_output": "accuracy"},
loss_weights={"classification_output": 1, "segmentation_output": 1},)
history = model.fit(
X_train,
{"classification_output": y_train_class, "segmentation_output": y_train_seg},
validation_data=(X_val, {"classification_output": y_val_class, "segmentation_output": y_val_seg}),
epochs=epochs,
verbose=1,
batch_size=batch_size,
callbacks=[checkpoint, reduce_lr, tensorboard],)
return history
def evaluate_model(model, X_test, y_test_class, y_test_seg):
with tf.keras.utils.custom_object_scope({"segmentation_loss": segmentation_loss}):
# Load the best model weights
best_model = load_model("multitask_best_weights.h5")
# Evaluate the model on test data
test_loss, test_class_loss, test_seg_loss, test_class_acc, test_seg_acc = best_model.evaluate(
X_test, {"classification_output": y_test_class, "segmentation_output": y_test_seg})
print("Test Classification Loss:", test_class_loss)
print("Test Segmentation Loss:", test_seg_loss)
print("Test Classification Accuracy:", test_class_acc)
print("Test Segmentation Accuracy:", test_seg_acc)
# Evaluate the model on validation data
val_loss, val_class_loss, val_seg_loss, val_class_acc, val_seg_acc = best_model.evaluate(
X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg})
print("Validation Classification Loss:", val_class_loss)
print("Validation Segmentation Loss:", val_seg_loss)
print("Validation Classification Accuracy:", val_class_acc)
print("Validation Segmentation Accuracy:", val_seg_acc)
# Evaluate the model on training data
train_loss, train_class_loss, train_seg_loss, train_class_acc, train_seg_acc = best_model.evaluate(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg})
print("Train Classification Loss:", train_class_loss)
print("Train Segmentation Loss:", train_seg_loss)
print("Train Classification Accuracy:", train_class_acc)
print("Train Segmentation Accuracy:", train_seg_acc)
# Return test classification accuracy
return test_class_acc
def plot_performance(history):
# Plot classification accuracy
classification_train_accuracy = history.history["classification_output_accuracy"]
classification_val_accuracy = history.history["val_classification_output_accuracy"]
plt.figure(figsize=(7, 3))
plt.plot(classification_train_accuracy, label="Training Accuracy")
plt.plot(classification_val_accuracy, label="Validation Accuracy")
plt.title("Classification Accuracy")
plt.xlabel("Epochs")
plt.ylabel("Accuracy")
plt.legend()
plt.show()
# Plot classification loss
classification_train_loss = history.history["classification_output_loss"]
classification_val_loss = history.history["val_classification_output_loss"]
plt.figure(figsize=(7, 3))
plt.plot(classification_train_loss, "b", label="Training Loss")
plt.plot(classification_val_loss, "r", label="Validation Loss")
plt.title("Classification Loss")
plt.xlabel("Epochs")
plt.ylabel("Loss")
plt.legend()
plt.show()
# Plot segmentation accuracy
segmentation_train_accuracy = history.history["segmentation_output_accuracy"]
segmentation_val_accuracy = history.history["val_segmentation_output_accuracy"]
plt.figure(figsize=(7, 3))
plt.plot(segmentation_train_accuracy, label="Training Accuracy")
plt.plot(segmentation_val_accuracy, label="Validation Accuracy")
plt.title("Segmentation Accuracy")
plt.xlabel("Epochs")
plt.ylabel("Accuracy")
plt.legend()
plt.show()
# Plot segmentation loss
segmentation_train_loss = history.history["segmentation_output_loss"]
segmentation_val_loss = history.history["val_segmentation_output_loss"]
plt.figure(figsize=(7, 3))
plt.plot(segmentation_train_loss, "b", label="Training Loss")
plt.plot(segmentation_val_loss, "r", label="Validation Loss")
plt.title("Segmentation Loss")
plt.xlabel("Epochs")
plt.ylabel("Loss")
plt.legend()
plt.show()
"
In my code ,why I adjusted the lr=0.000001 but the model training process still use 0.001 as initial learning rate?
|
65697c8354c51c2f090fc5a38455c5cb
|
{
"intermediate": 0.34155890345573425,
"beginner": 0.3308711647987366,
"expert": 0.3275699317455292
}
|
43,033
|
i have bunch on csv files
i want to rename 8th and 9th columns of them to volume_base and volume_target
give me proper python code
|
aca909f297990ed530679fa1cf35f55d
|
{
"intermediate": 0.4200171232223511,
"beginner": 0.3010055124759674,
"expert": 0.2789773941040039
}
|
43,034
|
import tensorflow
from tensorflow import keras
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.preprocessing.text import text_to_word_sequence
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from keras.layers import Input
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Embedding, LSTM, Concatenate
from keras.models import Model
# Séparer les images par langue
def separate_images_by_language(source_folder):
language_ranges = {
(1, 1000): "Arabic",
(1001, 2000): "English",
(2001, 3000): "French",
(3001, 4000): "Chinese",
(4001, 5000): "German",
(5001, 6000): "Korean",
(6001, 7000): "Japanese",
(7001, 8000): "Italian",
(8001, 9000): "Bangla",
(9001, 10000): "Hindi"
}
image_extensions = (".jpg", ".jpeg", ".png", ".gif", ".txt")
for filename in os.listdir(source_folder):
if filename.lower().endswith(image_extensions):
index = int(filename.split("_")[2].split(".")[0])
for range_, folder_name in language_ranges.items():
if range_[0] <= index <= range_[1]:
destination_folder = os.path.join(source_folder, folder_name)
break
os.makedirs(destination_folder, exist_ok=True)
source_path = os.path.join(source_folder, filename)
destination_path = os.path.join(destination_folder, filename)
os.rename(source_path, destination_path)
separate_images_by_language("ImagesPart1")
separate_images_by_language("AKRAPO7")
# Définir les paramètres
img_width, img_height = 224, 224
batch_size = 32
epochs = 10
# Charger les données d'images
train_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
'/content/ImagesPart1',
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode=None
)
# Charger les données de texte
def load_text_data(directory):
text_data = []
for root, dirs, files in os.walk(directory):
for file in sorted(files):
if file.endswith(".txt"):
file_path = os.path.join(root, file)
with open(file_path, "r") as f:
text = f.read()
text_data.append(text)
return text_data
text_data = load_text_data('/content/AKRAPO7')
# Tokeniser et encoder les textes
tokenizer = Tokenizer()
tokenizer.fit_on_texts(text_data)
sequences = tokenizer.texts_to_sequences(text_data)
max_length = max([len(seq) for seq in sequences])
padded_sequences = pad_sequences(sequences, maxlen=max_length, padding='post')
image_input = Input(shape=(img_width, img_height, 3))
text_input = Input(shape=(max_length,))
# Branche du modèle d'image
x = Conv2D(32, (3, 3), activation='relu')(image_input)
x = MaxPooling2D((2, 2))(x)
x = Conv2D(64, (3, 3), activation='relu')(x)
x = MaxPooling2D((2, 2))(x)
x = Conv2D(64, (3, 3), activation='relu')(x)
x = Flatten()(x)
x = Dense(64, activation='relu')(x)
# Branche du modèle de texte
y = Embedding(len(tokenizer.word_index) + 1, 128)(text_input)
y = LSTM(64)(y)
# Fusionner les branches d'image et de texte
merged = Concatenate()([x, y])
output = Dense(len(tokenizer.word_index) + 1, activation='softmax')(merged)
# Créer le modèle
model = Model(inputs=[image_input, text_input], outputs=output)
# Compiler le modèle
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# Entraîner le modèle
model.fit(
[train_generator, padded_sequences],
np.expand_dims(padded_sequences, -1),
epochs=epochs,
steps_per_epoch=train_generator.samples // batch_size
)
# Sauvegarder le modèle
model.save('model.h5')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-31-37f17f3d180f> in <cell line: 99>()
97
98 # Entraîner le modèle
---> 99 model.fit(
100 [train_generator, padded_sequences],
101 np.expand_dims(padded_sequences, -1),
1 frames
/usr/local/lib/python3.10/dist-packages/keras/src/utils/traceback_utils.py in error_handler(*args, **kwargs)
68 # To get the full stack trace, call:
69 # `tf.debugging.disable_traceback_filtering()`
---> 70 raise e.with_traceback(filtered_tb) from None
71 finally:
72 del filtered_tb
/usr/local/lib/python3.10/dist-packages/keras/src/engine/data_adapter.py in select_data_adapter(x, y)
1103 if not adapter_cls:
1104 # TODO(scottzhu): This should be a less implementation-specific error.
-> 1105 raise ValueError(
1106 "Failed to find data adapter that can handle input: {}, {}".format(
1107 _type_name(x), _type_name(y)
ValueError: Failed to find data adapter that can handle input: (<class 'list'> containing values of types {"<class 'numpy.ndarray'>", "<class 'keras.src.preprocessing.image.DirectoryIterator'>"}), <class 'numpy.ndarray'>
|
46942030092000555b51f4789c6f76fe
|
{
"intermediate": 0.37637344002723694,
"beginner": 0.5002302527427673,
"expert": 0.12339635193347931
}
|
43,035
|
import tensorflow
from tensorflow import keras
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.preprocessing.text import text_to_word_sequence
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from keras.layers import Input
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Embedding, LSTM, Concatenate
from keras.models import Model
import os
from google.colab import drive
drive.mount('/content/drive')
!unzip /content/drive/MyDrive/DATACOLAB/ImagesPart1.zip
!unzip -q /content/drive/MyDrive/DATACOLAB/ImagesPart2.zip -d ImagesPart1
!mkdir AKRAPO7
!unzip -q /content/drive/MyDrive/DATACOLAB/train_gt_t13.zip -d AKRAPO7
os.system("clear")
import os
import shutil
dossier_source = '/content/ImagesPart1/ImagesPart2'
dossier_destination = '/content/ImagesPart1'
if os.path.exists(dossier_source):
for fichier in os.listdir(dossier_source):
chemin_source = os.path.join(dossier_source, fichier)
chemin_destination = os.path.join(dossier_destination, fichier)
try:
shutil.move(chemin_source, chemin_destination)
except FileNotFoundError:
print(f"Le fichier {chemin_source} n'a pas été trouvé.")
except shutil.Error as e:
print(f"Erreur lors du déplacement du fichier {chemin_source} : {str(e)}")
except Exception as e:
print(f"Une erreur inattendue s'est produite lors du déplacement du fichier {chemin_source} : {str(e)}")
try:
os.rmdir(dossier_source)
except OSError as e:
print(f"Erreur lors de la suppression du dossier {dossier_source} : {str(e)}")
except Exception as e:
print(f"Une erreur inattendue s'est produite lors de la suppression du dossier {dossier_source} : {str(e)}")
else:
print(f"Le dossier source {dossier_source} n'existe pas.")
import os
import shutil
def separate_images_by_language(source_folder):
# Dictionnaire des plages d'index et des noms de dossiers correspondants
language_ranges = {
(1, 1000): "Arabic",
(1001, 2000): "English",
(2001, 3000): "French",
(3001, 4000): "Chinese",
(4001, 5000): "German",
(5001, 6000): "Korean",
(6001, 7000): "Japanese",
(7001, 8000): "Italian",
(8001, 9000): "Bangla",
(9001, 10000): "Hindi"
}
# Extensions de fichiers d'images prises en charge
image_extensions = (".jpg", ".jpeg", ".png", ".gif",".txt")
# Parcourir les fichiers dans le dossier source
for filename in os.listdir(source_folder):
if filename.lower().endswith(image_extensions):
# Extraire le numéro d'index de l'image à partir du nom de fichier
index = int(filename.split("_")[2].split(".")[0])
# Trouver le dossier de destination correspondant à l'index
for range_, folder_name in language_ranges.items():
if range_[0] <= index <= range_[1]:
destination_folder = os.path.join(source_folder, folder_name)
break
# Créer le dossier de destination s'il n'existe pas
os.makedirs(destination_folder, exist_ok=True)
# Déplacer l'image vers le dossier de destination
source_path = os.path.join(source_folder, filename)
destination_path = os.path.join(destination_folder, filename)
shutil.move(source_path, destination_path)
# Exemple d'utilisation
source_folder = "ImagesPart1"
separate_images_by_language(source_folder)
source_folder = "AKRAPO7"
separate_images_by_language(source_folder)
from keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.utils import to_categorical
import os
# Définition de la taille du batch
batch_size = 32
# Chargement des données d'images
train_datagen = ImageDataGenerator(rescale=1./255)
x_train = train_datagen.flow_from_directory(
"/content/ImagesPart1/French",
target_size=(224, 224),
batch_size=batch_size,
class_mode=None,
shuffle=False # Ajout de shuffle=False pour garder l'ordre des fichiers
)
# Chargement des données de texte
y_train = []
for root, dirs, files in os.walk("/content/AKRAPO7/French/"):
for file in sorted(files): # Tri des fichiers pour correspondre à l'ordre des images
if file.endswith(".txt"):
file_path = os.path.join(root, file)
with open(file_path, "r") as f:
text = f.read()
y_train.append(text)
# Tokenisation et encodage des textes de sortie
tokenizer = Tokenizer()
tokenizer.fit_on_texts(y_train)
y_train_sequences = tokenizer.texts_to_sequences(y_train)
y_train_padded = pad_sequences(y_train_sequences)
y_train_categorical = to_categorical(y_train_padded, num_classes=len(tokenizer.word_index) + 1)
from keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.utils import to_categorical
import os
# Définition de la taille du batch
batch_size = 32
# Langue sélectionnée
language = "French"
# Chargement des données d'images
image_dir = f"/content/ImagesPart1/{language}"
if not os.path.exists(image_dir):
print(f"Le dossier d'images pour la langue {language} n'existe pas : {image_dir}")
exit()
train_datagen = ImageDataGenerator(rescale=1./255)
x_train = train_datagen.flow_from_directory(
image_dir,
target_size=(224, 224),
batch_size=batch_size,
class_mode=None,
shuffle=False # Ajout de shuffle=False pour garder l'ordre des fichiers
)
# Chargement des données de texte
text_dir = f"/content/AKRAPO7/{language}/"
if not os.path.exists(text_dir):
print(f"Le dossier de textes pour la langue {language} n'existe pas : {text_dir}")
exit()
y_train = []
for root, dirs, files in os.walk(text_dir):
for file in sorted(files): # Tri des fichiers pour correspondre à l'ordre des images
if file.endswith(".txt"):
file_path = os.path.join(root, file)
with open(file_path, "r") as f:
text = f.read()
y_train.append(text)
# Tokenisation et encodage des textes de sortie
tokenizer = Tokenizer()
tokenizer.fit_on_texts(y_train)
y_train_sequences = tokenizer.texts_to_sequences(y_train)
y_train_padded = pad_sequences(y_train_sequences)
y_train_categorical = to_categorical(y_train_padded, num_classes=len(tokenizer.word_index) + 1)
# Séparer les images par langue
def separate_images_by_language(source_folder):
language_ranges = {
(1, 1000): "Arabic",
(1001, 2000): "English",
(2001, 3000): "French",
(3001, 4000): "Chinese",
(4001, 5000): "German",
(5001, 6000): "Korean",
(6001, 7000): "Japanese",
(7001, 8000): "Italian",
(8001, 9000): "Bangla",
(9001, 10000): "Hindi"
}
image_extensions = (".jpg", ".jpeg", ".png", ".gif", ".txt")
for filename in os.listdir(source_folder):
if filename.lower().endswith(image_extensions):
index = int(filename.split("_")[2].split(".")[0])
for range_, folder_name in language_ranges.items():
if range_[0] <= index <= range_[1]:
destination_folder = os.path.join(source_folder, folder_name)
break
os.makedirs(destination_folder, exist_ok=True)
source_path = os.path.join(source_folder, filename)
destination_path = os.path.join(destination_folder, filename)
os.rename(source_path, destination_path)
separate_images_by_language("ImagesPart1")
separate_images_by_language("AKRAPO7")
# Définir les paramètres
img_width, img_height = 224, 224
batch_size = 32
epochs = 10
# Charger les données d'images
train_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
'/content/ImagesPart1',
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode=None
)
# Charger les données de texte
def load_text_data(directory):
text_data = []
for root, dirs, files in os.walk(directory):
for file in sorted(files):
if file.endswith(".txt"):
file_path = os.path.join(root, file)
with open(file_path, "r") as f:
text = f.read()
text_data.append(text)
return text_data
text_data = load_text_data('/content/AKRAPO7')
# Tokeniser et encoder les textes
tokenizer = Tokenizer()
tokenizer.fit_on_texts(text_data)
sequences = tokenizer.texts_to_sequences(text_data)
max_length = max([len(seq) for seq in sequences])
padded_sequences = pad_sequences(sequences, maxlen=max_length, padding='post')
image_input = Input(shape=(img_width, img_height, 3))
text_input = Input(shape=(max_length,))
# Branche du modèle d'image
x = Conv2D(32, (3, 3), activation='relu')(image_input)
x = MaxPooling2D((2, 2))(x)
x = Conv2D(64, (3, 3), activation='relu')(x)
x = MaxPooling2D((2, 2))(x)
x = Conv2D(64, (3, 3), activation='relu')(x)
x = Flatten()(x)
x = Dense(64, activation='relu')(x)
# Branche du modèle de texte
y = Embedding(len(tokenizer.word_index) + 1, 128)(text_input)
y = LSTM(64)(y)
# Fusionner les branches d'image et de texte
merged = Concatenate()([x, y])
output = Dense(len(tokenizer.word_index) + 1, activation='softmax')(merged)
# Créer le modèle
model = Model(inputs=[image_input, text_input], outputs=output)
# Compiler le modèle
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# Entraîner le modèle
model.fit(
[train_generator, padded_sequences],
np.expand_dims(padded_sequences, -1),
epochs=epochs,
steps_per_epoch=train_generator.samples // batch_size
)
# Sauvegarder le modèle
model.save('model.h5')
Found 9996 images belonging to 10 classes.
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-31-37f17f3d180f> in <cell line: 99>()
97
98 # Entraîner le modèle
---> 99 model.fit(
100 [train_generator, padded_sequences],
101 np.expand_dims(padded_sequences, -1),
1 frames
/usr/local/lib/python3.10/dist-packages/keras/src/utils/traceback_utils.py in error_handler(*args, **kwargs)
68 # To get the full stack trace, call:
69 # `tf.debugging.disable_traceback_filtering()`
---> 70 raise e.with_traceback(filtered_tb) from None
71 finally:
72 del filtered_tb
/usr/local/lib/python3.10/dist-packages/keras/src/engine/data_adapter.py in select_data_adapter(x, y)
1103 if not adapter_cls:
1104 # TODO(scottzhu): This should be a less implementation-specific error.
-> 1105 raise ValueError(
1106 "Failed to find data adapter that can handle input: {}, {}".format(
1107 _type_name(x), _type_name(y)
ValueError: Failed to find data adapter that can handle input: (<class 'list'> containing values of types {"<class 'numpy.ndarray'>", "<class 'keras.src.preprocessing.image.DirectoryIterator'>"}), <class 'numpy.ndarray'>
|
c821bcc84a766aaba9201b2801faabeb
|
{
"intermediate": 0.36758723855018616,
"beginner": 0.4035554826259613,
"expert": 0.22885727882385254
}
|
43,036
|
i have bunch of csv files that contain Date column
i want to sort their value based on Date descending (most latest placed at last row)
give me proper python code
|
5c728c9dbcc988a44a3e5ac65523f4a2
|
{
"intermediate": 0.5461299419403076,
"beginner": 0.18590641021728516,
"expert": 0.2679636478424072
}
|
43,037
|
DROP TABLE rgr_сruises;
DROP TABLE rgr_ports;
drop sequence rgr_seq_p;
drop sequence rgr_seq_c;
create sequence rgr_seq_p start with 1 increment by 1;
create sequence rgr_seq_c start with 1 increment by 1;
CREATE TABLE rgr_cruises
(
cr_id INTEGER NOT NULL,
c_name VARCHAR2(50) NOT NULL,
c_ship VARCHAR2(20) NOT NULL,
c_departure_date DATE NOT NULL,
c_return_date DATE NOT NULL,
--p_id INTEGER NOT NULL,
--dest_port_id INTEGER NOT NULL
CONSTRAINT rgr_cr_id_pk PRIMARY KEY(cr_id)
);
CREATE TABLE rgr_ports
(
p_id INTEGER NOT NULL,
p_name VARCHAR2(20) NOT NULL,
p_country VARCHAR2(20) NOT NULL,
p_capacity INTEGER(30) NOT NULL,
p_dest INTEGER NOT NULL,
CONSTRAINT rgr_p_id_pk PRIMARY KEY(p_id),
CONSTRAINT rgr_p_dest_fk FOREIGN KEY(p_dest) REFERENCES rgr_ports
(cr_id) ON DELETE CASCADE
);
CREATE OR REPLACE PACKAGE dataPack AS
PROCEDURE filling;
PROCEDURE cleaning;
END;
/
CREATE OR REPLACE PACKAGE BODY dataPack AS
PROCEDURE filling IS
BEGIN
dataPack.cleaning;
INSERT INTO rgr_cruises
VALUES(rgr_seq_c.NEXTVAL, 'Средиземноморские жемчужины', 'Costa Diadema', to_date('15.06.2022', 'dd.mm.yyyy'), to_date('30.06.2022', 'dd.mm.yyyy'));
INSERT INTO rgr_ports VALUES(rgr_seq_p.NEXTVAL, 'Барселона', 'Испания', '20000', rgr_seq_c.CURRVAL);
INSERT INTO rgr_ports VALUES(rgr_seq_p.NEXTVAL, 'Рим', 'Италия', '40000', rgr_seq_c.CURRVAL);
INSERT INTO rgr_ports VALUES(rgr_seq_p.NEXTVAL, 'Неаполь', 'Италия', '30000', rgr_seq_c.CURRVAL);
INSERT INTO rgr_cruises
VALUES(rgr_seq_c.NEXTVAL, 'Карибские приключения', 'Harmony of the Seas', to_date('01.06.2023', 'dd.mm.yyyy'), to_date('10.06.2023', 'dd.mm.yyyy'));
INSERT INTO rgr_ports VALUES(rgr_seq_p.NEXTVAL, 'Майями', 'США', '20000', rgr_seq_c.CURRVAL);
INSERT INTO rgr_ports VALUES(rgr_seq_p.NEXTVAL, 'Ямайка', 'Ямайка', '10000', rgr_seq_c.CURRVAL);
INSERT INTO rgr_cruises
VALUES(rgr_seq_c.NEXTVAL, 'Северное сияние', 'Hurtigruten MS Roald Amundsen', to_date('20.09.2023', 'dd.mm.yyyy'), to_date('05.10.2023', 'dd.mm.yyyy'));
INSERT INTO rgr_ports VALUES(rgr_seq_p.NEXTVAL, 'Осло', 'Норвегия', '20000', rgr_seq_c.CURRVAL);
INSERT INTO rgr_ports VALUES(rgr_seq_p.NEXTVAL, 'Тромсе', 'Норвегия', '15000', rgr_seq_c.CURRVAL);
INSERT INTO rgr_cruises
VALUES(rgr_seq_c.NEXTVAL, 'Австралийские просторы', 'Pacific Explorer', to_date('10.10.2023', 'dd.mm.yyyy'), to_date('25.10.2023', 'dd.mm.yyyy'));
INSERT INTO rgr_ports VALUES(rgr_seq_p.NEXTVAL, 'Сидней', 'Австралия', '50000', rgr_seq_c.CURRVAL);
INSERT INTO rgr_ports VALUES(rgr_seq_p.NEXTVAL, 'Мельбурн', 'Австралия', '15000', rgr_seq_c.CURRVAL)
INSERT INTO rgr_cruises
VALUES(rgr_seq_c.NEXTVAL, 'Южная Америка', 'Empress of the Seas', to_date('01.02.2024', 'dd.mm.yyyy'), to_date('15.02.2024', 'dd.mm.yyyy'));
INSERT INTO rgr_ports VALUES(rgr_seq_p.NEXTVAL, 'Рио-де-Жанейро', 'Бразилия', '40000', rgr_seq_c.CURRVAL);
INSERT INTO rgr_ports VALUES(rgr_seq_p.NEXTVAL, 'Буэнос-Айрес', 'Аргентина', '25000', rgr_seq_c.CURRVAL)
INSERT INTO rgr_cruises
VALUES(rgr_seq_c.NEXTVAL, 'Азиатские тайны', 'Diamond Princess', to_date('10.05.2024', 'dd.mm.yyyy'), to_date('25.05.2024', 'dd.mm.yyyy'));
INSERT INTO rgr_ports VALUES(rgr_seq_p.NEXTVAL, 'Токио', 'Япония', '25000', rgr_seq_c.CURRVAL);
INSERT INTO rgr_ports VALUES(rgr_seq_p.NEXTVAL, 'Шанхай', 'Китай', '40000', rgr_seq_c.CURRVAL);
INSERT INTO rgr_ports VALUES(rgr_seq_p.NEXTVAL, 'Сингапур', 'Сингапур', '30000', rgr_seq_c.CURRVAL);
INSERT INTO rgr_cruises
VALUES(rgr_seq_c.NEXTVAL, 'Полярное сияние', 'MS Spitsbergen', to_date('15.08.2024', 'dd.mm.yyyy'), to_date('30.08.2024', 'dd.mm.yyyy'));
INSERT INTO rgr_ports VALUES(rgr_seq_p.NEXTVAL, 'Лонгйир', 'Норвегия', '25000', rgr_seq_c.CURRVAL);
INSERT INTO rgr_ports VALUES(rgr_seq_p.NEXTVAL, 'Свальбард', 'Норвегия', '40000', rgr_seq_c.CURRVAL);
INSERT INTO rgr_ports VALUES(rgr_seq_p.NEXTVAL, 'Хоннинсгвог', 'Норвегия', '30000', rgr_seq_c.CURRVAL);
EXCEPTION WHEN OTHERS THEN
ROLLBACK;
RAISE_APPLICATION_ERROR(-20001, 'Не удалось заполнить таблицы данными', TRUE);
END filling; Error at line 1/14: ORA-00955: name is already used by an existing object В чем ошибка в данном коде?
|
ab8af64309050b047ae79f24f918db0d
|
{
"intermediate": 0.315131813287735,
"beginner": 0.4252042770385742,
"expert": 0.25966382026672363
}
|
43,038
|
You are a Python expert who can provide clear, concise, high-quality code.
"
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import cv2
import random
import tensorflow as tf
import tkinter as tk
from tkinter import filedialog
from PIL import ImageTk, Image
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
from IPython.display import display, clear_output
from tensorflow.keras.preprocessing import image
from tensorflow.keras.optimizers import Adam, SGD, RMSprop, AdamW, Adadelta, Adagrad, Adamax, Adafactor, Nadam, Ftrl
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tqdm import tqdm
import os
from sklearn.utils import shuffle
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential, Model, load_model
from tensorflow.keras.layers import (
GlobalAveragePooling2D,
Dropout,
Dense,
Conv2D,
MaxPooling2D,
Flatten,
Dropout,
BatchNormalization,
Activation,
concatenate,
Conv2DTranspose,
Input,
Reshape,
UpSampling2D,
)
from tensorflow.keras.applications import (
EfficientNetV2B0,
EfficientNetV2B1,
EfficientNetV2B2,
EfficientNetV2B3,
EfficientNetV2L,
EfficientNetV2M,
EfficientNetV2S,
)
from tensorflow.keras.applications import Xception
from tensorflow.keras.applications import VGG16, VGG19
from tensorflow.keras.applications import ResNet50, ResNet101, ResNet152, ResNetRS50, ResNetRS101
from tensorflow.keras.applications import InceptionResNetV2, ConvNeXtXLarge, ConvNeXtBase, DenseNet121, MobileNetV2, NASNetLarge, NASNetMobile
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, TensorBoard, ModelCheckpoint
from sklearn.metrics import classification_report, confusion_matrix
import ipywidgets as widgets
import io
from PIL import Image
from IPython.display import display, clear_output
from warnings import filterwarnings
from google.colab import drive
drive.mount("/content/gdrive")
def load_data(data_folders):
X_data = [] # Combined data
y_class_labels = [] # Combined classification labels
y_seg_labels = [] # Combined segmentation labels
for folderPath in data_folders:
for label in labels:
label_folder_path = os.path.join(folderPath, label)
for filename in tqdm(os.listdir(label_folder_path)):
if filename.endswith(".jpg"):
img = cv2.imread(os.path.join(label_folder_path, filename))
img = cv2.resize(img, (image_size, image_size))
X_data.append(img)
y_class_labels.append(label)
seg_filename = filename.split(".")[0] + ".png"
seg_img = cv2.imread(os.path.join(label_folder_path, seg_filename), 0)
seg_img = cv2.resize(seg_img, (image_size, image_size))
seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary
y_seg_labels.append(seg_img)
X_data = np.array(X_data)
y_class_labels = np.array(y_class_labels)
y_seg_labels = np.array(y_seg_labels)
X_data, y_class_labels, y_seg_labels = shuffle(X_data, y_class_labels, y_seg_labels, random_state=101)
return X_data, y_class_labels, y_seg_labels
def split_data(X_data, y_class_labels, y_seg_labels, class_data_counts):
X_train = []
y_train_class = []
y_train_seg = []
X_val = []
y_val_class = []
y_val_seg = []
X_test = []
y_test_class = []
y_test_seg = []
for label, count in class_data_counts.items():
label_indices = np.where(y_class_labels == label)[0]
class_X_data = X_data[label_indices]
class_y_class_labels = y_class_labels[label_indices]
class_y_seg_labels = y_seg_labels[label_indices]
train_count = count[0]
val_count = count[1]
test_count = count[2]
class_X_train = class_X_data[:train_count]
class_y_train_class = class_y_class_labels[:train_count]
class_y_train_seg = class_y_seg_labels[:train_count]
class_X_val = class_X_data[train_count: train_count + val_count]
class_y_val_class = class_y_class_labels[train_count: train_count + val_count]
class_y_val_seg = class_y_seg_labels[train_count: train_count + val_count]
class_X_test = class_X_data[train_count + val_count: train_count + val_count + test_count]
class_y_test_class = class_y_class_labels[train_count + val_count: train_count + val_count + test_count]
class_y_test_seg = class_y_seg_labels[train_count + val_count: train_count + val_count + test_count]
X_train.extend(class_X_train)
y_train_class.extend(class_y_train_class)
y_train_seg.extend(class_y_train_seg)
X_val.extend(class_X_val)
y_val_class.extend(class_y_val_class)
y_val_seg.extend(class_y_val_seg)
X_test.extend(class_X_test)
y_test_class.extend(class_y_test_class)
y_test_seg.extend(class_y_test_seg)
# Convert class labels to categorical
label_encoder = LabelEncoder()
y_train_class_encoded = label_encoder.fit_transform(y_train_class)
y_train_class_categorical = to_categorical(y_train_class_encoded)
y_val_class_encoded = label_encoder.transform(y_val_class)
y_val_class_categorical = to_categorical(y_val_class_encoded)
y_test_class_encoded = label_encoder.transform(y_test_class)
y_test_class_categorical = to_categorical(y_test_class_encoded)
return (
np.array(X_train),
np.array(y_train_class_categorical),
np.array(y_train_seg),
np.array(X_val),
np.array(y_val_class_categorical),
np.array(y_val_seg),
np.array(X_test),
np.array(y_test_class_categorical),
np.array(y_test_seg),
)
def count_labels(y_class_categorical, label_encoder):
# Convert one-hot encoded labels back to label encoded
y_class_labels = np.argmax(y_class_categorical, axis=1)
# Convert label encoded labels back to original class names
y_class_names = label_encoder.inverse_transform(y_class_labels)
unique, counts = np.unique(y_class_names, return_counts=True)
return dict(zip(unique, counts))
def build_model(input_shape, num_classes):
num_filter = 32 # 16/32 best, 8: best classification but no segment
# Encoder (Done)
inputs = Input(input_shape)
conv1 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(inputs)
bn1 = BatchNormalization()(conv1)
relu1 = Activation("relu")(bn1)
conv2 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu1)
bn2 = BatchNormalization()(conv2)
relu2 = Activation("relu")(bn2)
down1 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu2)
conv3 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(down1)
bn3 = BatchNormalization()(conv3)
relu3 = Activation("relu")(bn3)
conv4 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu3)
bn4 = BatchNormalization()(conv4)
relu4 = Activation("relu")(bn4)
down2 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu4)
conv5 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(down2)
bn5 = BatchNormalization()(conv5)
relu5 = Activation("relu")(bn5)
conv6 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu5)
bn6 = BatchNormalization()(conv6)
relu6 = Activation("relu")(bn6)
down3 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu6)
conv7 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(down3)
bn7 = BatchNormalization()(conv7)
relu7 = Activation("relu")(bn7)
conv8 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu7)
bn8 = BatchNormalization()(conv8)
relu8 = Activation("relu")(bn8)
# Middle
down4 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu8)
conv9 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(down4)
bn9 = BatchNormalization()(conv9)
relu9 = Activation("relu")(bn9)
conv10 = Conv2D(num_filter * 16, 3, activation="linear", padding="same", strides=1)(relu9)
bn10 = BatchNormalization()(conv10)
relu10 = Activation("relu")(bn10)
up1 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu10)
# Decoder (Done)
concat1 = concatenate([up1, relu8], axis=-1) # , axis=3
conv11 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(concat1)
bn11 = BatchNormalization()(conv11)
relu11 = Activation("relu")(bn11)
conv12 = Conv2D(num_filter * 8, 3, activation="linear", padding="same", strides=1)(relu11)
bn12 = BatchNormalization()(conv12)
relu12 = Activation("relu")(bn12)
up2 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu12)
concat2 = concatenate([up2, relu6], axis=-1) # , axis=3
conv13 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(concat2)
bn13 = BatchNormalization()(conv13)
relu13 = Activation("relu")(bn13)
conv14 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(relu13)
bn14 = BatchNormalization()(conv14)
relu14 = Activation("relu")(bn14)
up3 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu14)
concat3 = concatenate([up3, relu4], axis=-1) # , axis=3
conv15 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(concat3)
bn15 = BatchNormalization()(conv15)
relu15 = Activation("relu")(bn15)
conv16 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(relu15)
bn16 = BatchNormalization()(conv16)
relu16 = Activation("relu")(bn16)
up4 = UpSampling2D(size=(2, 2), interpolation="bilinear")(relu16)
concat4 = concatenate([up4, relu2], axis=-1) # , axis=3
conv17 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(concat4)
bn17 = BatchNormalization()(conv17)
relu17 = Activation("relu")(bn17)
conv18 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(relu17)
bn18 = BatchNormalization()(conv18)
relu18 = Activation("relu")(bn18)
# Segmentation branch
segmentation_output = Conv2D(1, 1, activation="sigmoid", name="segmentation_output")(relu18) # original
# Classification branch (Not done)
gap1 = GlobalAveragePooling2D()(relu8)
gap2 = GlobalAveragePooling2D()(relu10)
gap3 = GlobalAveragePooling2D()(relu12)
conv20 = Conv2D(num_filter * 1, 3, activation="linear", padding="same", strides=1)(segmentation_output)
bn20 = BatchNormalization()(conv20)
relu20 = Activation("relu")(bn20)
down5 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu20)
conv21 = Conv2D(num_filter * 2, 3, activation="linear", padding="same", strides=1)(down5)
bn21 = BatchNormalization()(conv21)
relu21 = Activation("relu")(bn21)
down6 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu21)
conv22 = Conv2D(num_filter * 4, 3, activation="linear", padding="same", strides=1)(down6)
bn22 = BatchNormalization()(conv22)
relu22 = Activation("relu")(bn22)
down7 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu22)
flatten1 = Flatten()(down7)
concat5 = concatenate([gap1, gap2, gap3, flatten1], axis=-1)
# FC layers
fc1 = Dense(1024, activation="relu")(concat5)
dropout1 = Dropout(0.5)(fc1)
fc2 = Dense(1024, activation="relu")(dropout1)
dropout2 = Dropout(0.5)(fc2)
classification_output = Dense(num_classes, activation="softmax", name="classification_output")(dropout2)
# Define the model
model = Model(inputs=inputs, outputs=[classification_output, segmentation_output])
return model
def segmentation_loss(y_true, y_pred):
y_true = tf.cast(y_true, tf.float32)
y_pred = tf.cast(y_pred, tf.float32)
bce_loss = tf.keras.losses.binary_crossentropy(y_true, y_pred)
smooth = 1e-5
intersection = tf.reduce_sum(y_true * y_pred)
union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred)
dice_loss = 1.0 - 2.0 * (intersection + smooth) / (union + smooth)
segmentation_loss = bce_loss + 1 * dice_loss
return segmentation_loss
def train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs):
checkpoint = ModelCheckpoint(
"multitask_best_weights.h5",
monitor="val_classification_output_accuracy",
save_best_only=True,
mode="max",
verbose=1,)
reduce_lr = ReduceLROnPlateau(
monitor="val_classification_output_accuracy",
factor=0.3,
patience=2,
min_delta=0.001,
mode="auto",
verbose=1,)
tensorboard = TensorBoard(log_dir="logs")
model.compile(
optimizer=Adam(learning_rate=0.001),
loss={"classification_output": "categorical_crossentropy", "segmentation_output": segmentation_loss},
metrics={"classification_output": "accuracy", "segmentation_output": "accuracy"},
loss_weights={"classification_output": 1, "segmentation_output": 1},)
history = model.fit(
X_train,
{"classification_output": y_train_class, "segmentation_output": y_train_seg},
validation_data=(X_val, {"classification_output": y_val_class, "segmentation_output": y_val_seg}),
epochs=epochs,
verbose=1,
batch_size=batch_size,
callbacks=[checkpoint, reduce_lr, tensorboard],)
return history
def evaluate_model(model, X_test, y_test_class, y_test_seg):
with tf.keras.utils.custom_object_scope({"segmentation_loss": segmentation_loss}):
# Load the best model weights
best_model = load_model("multitask_best_weights.h5")
# Evaluate the model on test data
test_loss, test_class_loss, test_seg_loss, test_class_acc, test_seg_acc = best_model.evaluate(
X_test, {"classification_output": y_test_class, "segmentation_output": y_test_seg})
print("Test Classification Loss:", test_class_loss)
print("Test Segmentation Loss:", test_seg_loss)
print("Test Classification Accuracy:", test_class_acc)
print("Test Segmentation Accuracy:", test_seg_acc)
# Evaluate the model on validation data
val_loss, val_class_loss, val_seg_loss, val_class_acc, val_seg_acc = best_model.evaluate(
X_val, {'classification_output': y_val_class, 'segmentation_output': y_val_seg})
print("Validation Classification Loss:", val_class_loss)
print("Validation Segmentation Loss:", val_seg_loss)
print("Validation Classification Accuracy:", val_class_acc)
print("Validation Segmentation Accuracy:", val_seg_acc)
# Evaluate the model on training data
train_loss, train_class_loss, train_seg_loss, train_class_acc, train_seg_acc = best_model.evaluate(X_train, {'classification_output': y_train_class, 'segmentation_output': y_train_seg})
print("Train Classification Loss:", train_class_loss)
print("Train Segmentation Loss:", train_seg_loss)
print("Train Classification Accuracy:", train_class_acc)
print("Train Segmentation Accuracy:", train_seg_acc)
# Return test classification accuracy
return test_class_acc
def plot_performance(history):
# Plot classification accuracy
classification_train_accuracy = history.history["classification_output_accuracy"]
classification_val_accuracy = history.history["val_classification_output_accuracy"]
plt.figure(figsize=(7, 3))
plt.plot(classification_train_accuracy, label="Training Accuracy")
plt.plot(classification_val_accuracy, label="Validation Accuracy")
plt.title("Classification Accuracy")
plt.xlabel("Epochs")
plt.ylabel("Accuracy")
plt.legend()
plt.show()
# Plot classification loss
classification_train_loss = history.history["classification_output_loss"]
classification_val_loss = history.history["val_classification_output_loss"]
plt.figure(figsize=(7, 3))
plt.plot(classification_train_loss, "b", label="Training Loss")
plt.plot(classification_val_loss, "r", label="Validation Loss")
plt.title("Classification Loss")
plt.xlabel("Epochs")
plt.ylabel("Loss")
plt.legend()
plt.show()
# Plot segmentation accuracy
segmentation_train_accuracy = history.history["segmentation_output_accuracy"]
segmentation_val_accuracy = history.history["val_segmentation_output_accuracy"]
plt.figure(figsize=(7, 3))
plt.plot(segmentation_train_accuracy, label="Training Accuracy")
plt.plot(segmentation_val_accuracy, label="Validation Accuracy")
plt.title("Segmentation Accuracy")
plt.xlabel("Epochs")
plt.ylabel("Accuracy")
plt.legend()
plt.show()
# Plot segmentation loss
segmentation_train_loss = history.history["segmentation_output_loss"]
segmentation_val_loss = history.history["val_segmentation_output_loss"]
plt.figure(figsize=(7, 3))
plt.plot(segmentation_train_loss, "b", label="Training Loss")
plt.plot(segmentation_val_loss, "r", label="Validation Loss")
plt.title("Segmentation Loss")
plt.xlabel("Epochs")
plt.ylabel("Loss")
plt.legend()
plt.show()
# Set image size
image_size = 224
# Define labels
labels = ["bridge", "excess", "good", "insuff", "no"]
# Set data folders
data_folders = [
"/content/gdrive/MyDrive/Deep learning/FYP_3/4 Dataset Ratio 60 20 20/jit0/b_dip/train",
"/content/gdrive/MyDrive/Deep learning/FYP_3/4 Dataset Ratio 60 20 20/jit0/b_dip/val",
"/content/gdrive/MyDrive/Deep learning/FYP_3/4 Dataset Ratio 60 20 20/jit0/b_dip/test",]
# Load data
X_data, y_class_labels, y_seg_labels = load_data(data_folders)
# Define train:val:test ratio for each class (ratio x4 = exact)
class_data_counts = {
"bridge": [40, 80, 80],
"excess": [40, 80, 80],
"good": [40, 80, 80],
"insuff": [40, 80, 80],
"no": [40, 80, 80]
}
# Split data
X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, X_test, y_test_class, y_test_seg = split_data(
X_data, y_class_labels, y_seg_labels, class_data_counts)
'''
print("Number of train images:", len(X_train))
print("Number of train binary masks:", len(y_train_seg))
print("Number of validation images:", len(X_val))
print("Number of validation binary masks:", len(y_val_seg))
print("Number of test images:", len(X_test))
print("Number of test binary masks:", len(y_test_seg))
'''
# Initialize the label encoder
label_encoder = LabelEncoder()
label_encoder.fit(y_class_labels)
# Count the number of images of each class in the train, validation, and test sets
train_counts = count_labels(y_train_class, label_encoder)
val_counts = count_labels(y_val_class, label_encoder)
test_counts = count_labels(y_test_class, label_encoder)
print("Train counts: ", train_counts," Total in train set:", sum(train_counts.values()))
print("Validation counts:", val_counts, " Total in validation set:", sum(val_counts.values()))
print("Test counts: ", test_counts," Total in test set:", sum(test_counts.values()))
# Build model
input_shape = (image_size, image_size, 3)
num_classes = len(labels)
model = build_model(input_shape, num_classes)
model.summary()
# Train model n times
test_class_acc_list = []
for i in range(5):
print(f"\nTrain {i+1}:\n")
model = build_model(input_shape, num_classes)
batch_size = 16
epochs = 50
history = train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs)
# Evaluate model on test data
test_class_acc = evaluate_model(model, X_test, y_test_class, y_test_seg)
plot_performance(history)
test_class_acc_list.append(test_class_acc)
# Calculate average test classification accuracy
average_test_class_acc = sum(test_class_acc_list) / len(test_class_acc_list)
print("Test Classification Accuracy List:", test_class_acc_list)
print("Average Test Classification Accuracy:", average_test_class_acc)
"
The above is the Python code with Keras to do multi-task learning with binary segmentation and classification using one mult-task learning model. Specifically for the small dataset. But the Test Classification Loss: 1.4311378002166748,
Test Segmentation Loss: 1.0658704042434692, Test Classification Accuracy: 0.3474999964237213, Test Segmentation Accuracy: 0.7845422625541687. How to improve the classification accuracy?
|
c1f178d85dc93467ebfe1065777122da
|
{
"intermediate": 0.3006076216697693,
"beginner": 0.3237382769584656,
"expert": 0.3756541907787323
}
|
43,039
|
import pandas as pd
import os
from pathlib import Path
# Set the directory where your CSV files are located
base_directory_path = r"..\downloaded_files\Binance\test"
# List of folders to iterate through
folders = [d for d in Path(base_directory_path).iterdir() if d.is_dir()]
# Loop through each folder and then through each CSV file within them
for folder in folders:
folder_path = Path(base_directory_path)/folder
# Iterate over each file in the directory
for filename in os.listdir(folder_path):
if filename.endswith('.csv'): # Make sure to process only CSV files
file_path = os.path.join(folder_path, filename)
# Read the CSV file
df = pd.read_csv(file_path, skiprows=1)
# Rename the 8th and 9th columns
# Note: Python is zero-indexed, so the 8th column is at index 7, and the 9th is at index 8.
columns = df.columns.tolist()
if len(columns) >= 9: # Check if there are enough columns
columns[7] = 'volume_base'
columns[8] = 'volume_target'
df.columns = columns
# Save the modified DataFrame back to CSV
df.to_csv(file_path, index=False) # index=False to prevent adding an unnamed index column
error:
Traceback (most recent call last):
File "C:\Users\Fazel\PycharmProjects\indicators_calculate\01_rename_columns.py", line 15, in <module>
for filename in os.listdir(folder_path):
FileNotFoundError: [WinError 3] The system cannot find the path specified: '..\\downloaded_files\\Binance\\test\\..\\downloaded_files\\Binance\\test\\New folder'
|
e80f2070aaac5d7baad0fe350de40e7a
|
{
"intermediate": 0.7263978719711304,
"beginner": 0.15279991924762726,
"expert": 0.12080228328704834
}
|
43,040
|
In the else statement in this javascript I want to fit the mapbounds to the extent of all the streetDetails.Points fetched from the json file 'let streetLatitude; // Define streetLatitude globally
let streetLongitude; // Define streetLongitude globally
let marker; // Define marker globally to make it accessible across functions
let data; // Declare data globally
let currentIndex = 0; // Initialize index globally
let totalScore = 0; // Initialize total points variable
function fetchStreetDetails() {
fetch("main.json")
.then((response) => response.json())
.then((jsonData) => {
data = jsonData; // Store the data globally
const entryCount = data.length; // data is already an array of objects
const streetDetails = data[0];
// Extract street details
streetLatitude = streetDetails.StreetLatitude;
streetLongitude = streetDetails.StreetLongitude;
streetHeading = streetDetails.StreetHeading;
streetPitch = streetDetails.StreetPitch;
streetPanoID = streetDetails.StreetPanoID;
const StreetPoints = streetDetails.Points;
const panorama = new google.maps.StreetViewPanorama(
document.getElementById("streetview"),
{
position: { lat: streetLatitude, lng: streetLongitude },
addressControl: false,
pano: streetPanoID,
heading: streetHeading,
pitch: streetPitch,
}
);
console.log("Street Latitude: " + streetLatitude);
console.log("Street Longitude: " + streetLongitude);
console.log("Street Heading: " + streetHeading);
console.log("Street Pitch: " + streetPitch);
console.log("Street PanoID: " + streetPanoID);
console.log("Street Location: " + StreetPoints);
// Update numberoffeeds div
const numberoffeedsElement =
document.getElementById("numberoffeeds");
numberoffeedsElement.textContent = `There are ${entryCount} questions in this game.`;
})
.catch((error) => console.error("Error fetching data: ", error));
}
fetchStreetDetails();
function initMap() {
const mapStyles = [
{
featureType: "poi",
stylers: [
{
visibility: "off",
},
],
},
{
featureType: "poi.park",
stylers: [
{
visibility: "off",
},
],
},
{
"featureType": "transit",
"stylers": [
{
"visibility": "off"
}
]
}
];
const mapOptions = {
center: { lat: 21.382325, lng: -8.170154652 },
zoom: 3,
styles: mapStyles,
};
const map = new google.maps.Map(
document.getElementById("map"),
mapOptions
);
// Function to add marker on click
function addMarker(event) {
const clickLocation = event.latLng;
marker = new google.maps.Marker({
position: clickLocation,
map: map,
draggable: true, // Set draggable to true
});
// Remove the click listener after adding a marker
google.maps.event.removeListener(clickListener);
// Add functionality after clicking the map
createSubmitButton(clickLocation);
}
// Define the CSS animation style separately (outside the button creation)
document.head.insertAdjacentHTML(
"beforeend",
`
<style>
.nextButtonAnimation {
animation: flip 1s ease-in-out 1 alternate forwards;
perspective: 1000px; /* Set perspective for 3D effect */
}
@keyframes flip {
0% { transform: rotateY(0deg); }
50% { transform: rotateY(-180deg); }
100% { transform: rotateY(0deg); }
}
</style>
`
);
// Create a function to add the submit button
function createSubmitButton(distance, clickLocation) {
const buttonsDiv = document.getElementById("buttons");
// Check if the button already exists before creating a new one
if (!document.getElementById("submit")) {
const submitButton = document.createElement("button");
submitButton.id = "submit";
submitButton.textContent = `Submit`;
submitButton.className = "button";
// Add event listener for the submit button (you can define the functionality here)
submitButton.addEventListener("click", () => {
console.log("Submit button clicked!");
// Create the new button
const nextButton = document.createElement("button");
nextButton.id = "nextButton";
nextButton.textContent = "Next"; // Customize button text as needed
nextButton.className = "nextbutton";
// Apply CSS animation class for easy management
nextButton.classList.add("nextButtonAnimation");
// Add event listener for the new button (optional, if needed)
nextButton.addEventListener("click", () => {
// Create a LatLng object representing the new position
const newLatLng = new google.maps.LatLng(21.382325, -8.170154652);
// Set the map center and zoom level
map.setCenter(newLatLng);
map.setZoom(3);
// Handle ‘nextButton’ click here
console.log("Next button clicked!");
buttons.removeChild(nextButton);
const wheremessage = "Next location. Where is this?";
// Update the 'results' div using DOM manipulation
const resultsDiv = document.getElementById("results");
resultsDiv.textContent = wheremessage;
// Check if there is next entry in the data
if (data && currentIndex < data.length - 1) {
currentIndex++; // Update the index to get the next street view details
const nextStreetDetails = data[currentIndex];
streetLatitude = nextStreetDetails.StreetLatitude;
streetLongitude = nextStreetDetails.StreetLongitude;
streetHeading = nextStreetDetails.StreetHeading;
streetPitch = nextStreetDetails.StreetPitch;
streetPanoID = nextStreetDetails.StreetPanoID;
const StreetPoints = nextStreetDetails.Points;
const panorama = new google.maps.StreetViewPanorama(
document.getElementById("streetview"),
{
position: { lat: streetLatitude, lng: streetLongitude },
addressControl: false,
pano: streetPanoID,
heading: streetHeading,
pitch: streetPitch,
}
);
console.log("Street Latitude: " + streetLatitude);
console.log("Street Longitude: " + streetLongitude);
console.log("Street Heading: " + streetHeading);
console.log("Street Pitch: " + streetPitch);
console.log("Street PanoID: " + streetPanoID);
console.log("Street Location: " + StreetPoints);
// Add click listener to the map to allow marker placement
const nextClickListener = map.addListener("click", addMarker);
} else {
console.log("No next entry in the data.");
// Calculate total points
const finalScores = `Total Score: ${totalScore}`;
// Update the 'streetview' div with final scores
const streetviewDiv = document.getElementById("streetview");
streetviewDiv.innerHTML = finalScores; // Update content with innerHTML
const overmessage = "Game Over";
const resultsDiv = document.getElementById("results");
resultsDiv.textContent = overmessage;
}
});
// Replace the buttons
buttonsDiv.replaceChild(nextButton, submitButton);
// Get the current marker position when the button is pressed
const markerPosition = marker.getPosition();
// Calculate distance using marker position and street coordinates
const distance = calculateDistance(
markerPosition.lat(),
markerPosition.lng(),
streetLatitude,
streetLongitude
);
// Adjust points based on distance
let score = 5000 - distance;
if (score < 0) {
score = 0;
}
console.log(
"Distance from marker to street: " + distance + " meters. You scored: " + score
);
totalScore += score; // Add current points to total
const message =
"You scored " + score;
// Update the 'results' div using DOM manipulation
const resultsDiv = document.getElementById("results");
resultsDiv.textContent = message;
// Createpolyline on marker add
drawPolyline(clickLocation);
// Set the marker as non-draggable
marker.setDraggable(false);
});
buttonsDiv.appendChild(submitButton);
}
} // Add click listener to the map
const clickListener = map.addListener("click", addMarker);
function calculateDistance(lat1, lng1, lat2, lng2) {
const deltaLat = ((lat2 - lat1) * Math.PI) / 180;
const deltaLng = ((lng2 - lng1) * Math.PI) / 180;
const earthRadius = 6371e3; // meters
const a = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2);
const b =
Math.cos((lat1 * Math.PI) / 180) *
Math.cos((lat2 * Math.PI) / 180) *
Math.sin(deltaLng / 2) *
Math.sin(deltaLng / 2);
const c = 2 * Math.atan2(Math.sqrt(a + b), Math.sqrt(1 - a - b)); // Calculate distance using Pythagorean theorem
const distance = earthRadius * c; // Round the distance to nearest meter using Math.round()
const roundedDistance = Math.round(distance);
return roundedDistance;
} // Function to draw polyline between marker and street location
function drawPolyline() {
const markerPosition = marker.getPosition(); // Get the current position of the marker
const polyline = new google.maps.Polyline({
path: [
markerPosition.toJSON(),
{ lat: streetLatitude, lng: streetLongitude },
],
strokeColor: "#FF0000", // red color
strokeWeight: 2,
map: map,
});
// Set map bounds to encompass marker and polyline
const bounds = new google.maps.LatLngBounds(); // Use google.maps here
bounds.extend(markerPosition);
bounds.extend(polyline.getPath().getAt(1));
map.fitBounds(bounds);
}
}
'
|
0e873ec6832f5ea6a9d92b3c4bbbcbfb
|
{
"intermediate": 0.32889288663864136,
"beginner": 0.4903547465801239,
"expert": 0.18075235188007355
}
|
43,041
|
import pandas as pd
from pathlib import Path
def sort_csv_by_date(file_path):
# Load the CSV file into a DataFrame
df = pd.read_csv(file_path)
# Convert the 'Date' column to datetime format (adjust the format as per your CSVs)
df['Date'] = pd.to_datetime(df['Date'], format ='%Y-%m-%d') # Adjust format as needed
# Sort the DataFrame based on the 'Date' in ascending order to get the latest at the bottom
df = df.sort_values(by='Date', ascending = True)
# Save the sorted DataFrame back to the same CSV (overwrites)
df.to_csv(file_path, index=False)
print(f"Sorted {file_path}")
# Path to the base directory containing your 4 separate folders with CSV files
base_directory_path = r"..\downloaded_files\Binance\test"
# List of folders to iterate through
folders = [d for d in Path(base_directory_path).iterdir() if d.is_dir()]
# Loop through each folder and then through each CSV file within them
for folder in folders:
for file_path in folder.glob('*.csv'):
sort_csv_by_date(file_path)
Traceback (most recent call last):
File "C:\Users\Fazel\PycharmProjects\indicators_calculate\02_sort_descending_date.py", line 29, in <module>
sort_csv_by_date(file_path)
File "C:\Users\Fazel\PycharmProjects\indicators_calculate\02_sort_descending_date.py", line 10, in sort_csv_by_date
df['Date'] = pd.to_datetime(df['Date'], format ='%Y-%m-%d') # Adjust format as needed
File "C:\Users\Fazel\PycharmProjects\indicators_calculate\venv\lib\site-packages\pandas\core\tools\datetimes.py", line 1067, in to_datetime
values = convert_listlike(arg._values, format)
File "C:\Users\Fazel\PycharmProjects\indicators_calculate\venv\lib\site-packages\pandas\core\tools\datetimes.py", line 433, in _convert_listlike_datetimes
return _array_strptime_with_fallback(arg, name, utc, format, exact, errors)
File "C:\Users\Fazel\PycharmProjects\indicators_calculate\venv\lib\site-packages\pandas\core\tools\datetimes.py", line 467, in _array_strptime_with_fallback
result, tz_out = array_strptime(arg, fmt, exact=exact, errors=errors, utc=utc)
File "strptime.pyx", line 501, in pandas._libs.tslibs.strptime.array_strptime
File "strptime.pyx", line 451, in pandas._libs.tslibs.strptime.array_strptime
File "strptime.pyx", line 587, in pandas._libs.tslibs.strptime._parse_with_format
ValueError: unconverted data remains when parsing with format "%Y-%m-%d": " 23:00:00", at position 0. You might want to try:
- passing `format` if your strings have a consistent format;
- passing `format='ISO8601'` if your strings are all ISO8601 but not necessarily in exactly the same format;
- passing `format='mixed'`, and the format will be inferred for each element individually. You might want to use `dayfirst` alongside this.
Process finished with exit code 1
|
b0d86eaf290ea910b3bbab72d2b70f24
|
{
"intermediate": 0.36755678057670593,
"beginner": 0.40841421484947205,
"expert": 0.2240290343761444
}
|
43,042
|
For neovim select lines and comment them
|
2735f8c021b5fb650a48452672e30213
|
{
"intermediate": 0.25322824716567993,
"beginner": 0.2182946801185608,
"expert": 0.5284770727157593
}
|
43,043
|
hi
|
2557dd9ea551ffe5f65f4b27f0b446f7
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
43,044
|
You are a Python expert who can provide clear, concise, high-quality code.
“
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import cv2
import random
import tensorflow as tf
import tkinter as tk
from tkinter import filedialog
from PIL import ImageTk, Image
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
from IPython.display import display, clear_output
from tensorflow.keras.preprocessing import image
from tensorflow.keras.optimizers import Adam, SGD, RMSprop, AdamW, Adadelta, Adagrad, Adamax, Adafactor, Nadam, Ftrl
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tqdm import tqdm
import os
from sklearn.utils import shuffle
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential, Model, load_model
from tensorflow.keras.layers import (
GlobalAveragePooling2D,
Dropout,
Dense,
Conv2D,
MaxPooling2D,
Flatten,
Dropout,
BatchNormalization,
Activation,
concatenate,
Conv2DTranspose,
Input,
Reshape,
UpSampling2D,
)
from tensorflow.keras.applications import (
EfficientNetV2B0,
EfficientNetV2B1,
EfficientNetV2B2,
EfficientNetV2B3,
EfficientNetV2L,
EfficientNetV2M,
EfficientNetV2S,
)
from tensorflow.keras.applications import Xception
from tensorflow.keras.applications import VGG16, VGG19
from tensorflow.keras.applications import ResNet50, ResNet101, ResNet152, ResNetRS50, ResNetRS101
from tensorflow.keras.applications import InceptionResNetV2, ConvNeXtXLarge, ConvNeXtBase, DenseNet121, MobileNetV2, NASNetLarge, NASNetMobile
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, TensorBoard, ModelCheckpoint
from sklearn.metrics import classification_report, confusion_matrix
import ipywidgets as widgets
import io
from PIL import Image
from IPython.display import display, clear_output
from warnings import filterwarnings
from google.colab import drive
drive.mount(”/content/gdrive")
def load_data(data_folders):
X_data = [] # Combined data
y_class_labels = [] # Combined classification labels
y_seg_labels = [] # Combined segmentation labels
for folderPath in data_folders:
for label in labels:
label_folder_path = os.path.join(folderPath, label)
for filename in tqdm(os.listdir(label_folder_path)):
if filename.endswith(“.jpg”):
img = cv2.imread(os.path.join(label_folder_path, filename))
img = cv2.resize(img, (image_size, image_size))
X_data.append(img)
y_class_labels.append(label)
seg_filename = filename.split(“.”)[0] + “.png”
seg_img = cv2.imread(os.path.join(label_folder_path, seg_filename), 0)
seg_img = cv2.resize(seg_img, (image_size, image_size))
seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary
y_seg_labels.append(seg_img)
X_data = np.array(X_data)
y_class_labels = np.array(y_class_labels)
y_seg_labels = np.array(y_seg_labels)
X_data, y_class_labels, y_seg_labels = shuffle(X_data, y_class_labels, y_seg_labels, random_state=101)
return X_data, y_class_labels, y_seg_labels
def split_data(X_data, y_class_labels, y_seg_labels, class_data_counts):
X_train = []
y_train_class = []
y_train_seg = []
X_val = []
y_val_class = []
y_val_seg = []
X_test = []
y_test_class = []
y_test_seg = []
for label, count in class_data_counts.items():
label_indices = np.where(y_class_labels == label)[0]
class_X_data = X_data[label_indices]
class_y_class_labels = y_class_labels[label_indices]
class_y_seg_labels = y_seg_labels[label_indices]
train_count = count[0]
val_count = count[1]
test_count = count[2]
class_X_train = class_X_data[:train_count]
class_y_train_class = class_y_class_labels[:train_count]
class_y_train_seg = class_y_seg_labels[:train_count]
class_X_val = class_X_data[train_count: train_count + val_count]
class_y_val_class = class_y_class_labels[train_count: train_count + val_count]
class_y_val_seg = class_y_seg_labels[train_count: train_count + val_count]
class_X_test = class_X_data[train_count + val_count: train_count + val_count + test_count]
class_y_test_class = class_y_class_labels[train_count + val_count: train_count + val_count + test_count]
class_y_test_seg = class_y_seg_labels[train_count + val_count: train_count + val_count + test_count]
X_train.extend(class_X_train)
y_train_class.extend(class_y_train_class)
y_train_seg.extend(class_y_train_seg)
X_val.extend(class_X_val)
y_val_class.extend(class_y_val_class)
y_val_seg.extend(class_y_val_seg)
X_test.extend(class_X_test)
y_test_class.extend(class_y_test_class)
y_test_seg.extend(class_y_test_seg)
# Convert class labels to categorical
label_encoder = LabelEncoder()
y_train_class_encoded = label_encoder.fit_transform(y_train_class)
y_train_class_categorical = to_categorical(y_train_class_encoded)
y_val_class_encoded = label_encoder.transform(y_val_class)
y_val_class_categorical = to_categorical(y_val_class_encoded)
y_test_class_encoded = label_encoder.transform(y_test_class)
y_test_class_categorical = to_categorical(y_test_class_encoded)
return (
np.array(X_train),
np.array(y_train_class_categorical),
np.array(y_train_seg),
np.array(X_val),
np.array(y_val_class_categorical),
np.array(y_val_seg),
np.array(X_test),
np.array(y_test_class_categorical),
np.array(y_test_seg),
)
def count_labels(y_class_categorical, label_encoder):
# Convert one-hot encoded labels back to label encoded
y_class_labels = np.argmax(y_class_categorical, axis=1)
# Convert label encoded labels back to original class names
y_class_names = label_encoder.inverse_transform(y_class_labels)
unique, counts = np.unique(y_class_names, return_counts=True)
return dict(zip(unique, counts))
def build_model(input_shape, num_classes):
num_filter = 32 # 16/32 best, 8: best classification but no segment
# Encoder (Done)
inputs = Input(input_shape)
conv1 = Conv2D(num_filter * 1, 3, activation=“linear”, padding=“same”, strides=1)(inputs)
bn1 = BatchNormalization()(conv1)
relu1 = Activation(“relu”)(bn1)
conv2 = Conv2D(num_filter * 1, 3, activation=“linear”, padding=“same”, strides=1)(relu1)
bn2 = BatchNormalization()(conv2)
relu2 = Activation(“relu”)(bn2)
down1 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu2)
conv3 = Conv2D(num_filter * 2, 3, activation=“linear”, padding=“same”, strides=1)(down1)
bn3 = BatchNormalization()(conv3)
relu3 = Activation(“relu”)(bn3)
conv4 = Conv2D(num_filter * 2, 3, activation=“linear”, padding=“same”, strides=1)(relu3)
bn4 = BatchNormalization()(conv4)
relu4 = Activation(“relu”)(bn4)
down2 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu4)
conv5 = Conv2D(num_filter * 4, 3, activation=“linear”, padding=“same”, strides=1)(down2)
bn5 = BatchNormalization()(conv5)
relu5 = Activation(“relu”)(bn5)
conv6 = Conv2D(num_filter * 4, 3, activation=“linear”, padding=“same”, strides=1)(relu5)
bn6 = BatchNormalization()(conv6)
relu6 = Activation(“relu”)(bn6)
down3 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu6)
conv7 = Conv2D(num_filter * 8, 3, activation=“linear”, padding=“same”, strides=1)(down3)
bn7 = BatchNormalization()(conv7)
relu7 = Activation(“relu”)(bn7)
conv8 = Conv2D(num_filter * 8, 3, activation=“linear”, padding=“same”, strides=1)(relu7)
bn8 = BatchNormalization()(conv8)
relu8 = Activation(“relu”)(bn8)
# Middle
down4 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu8)
conv9 = Conv2D(num_filter * 16, 3, activation=“linear”, padding=“same”, strides=1)(down4)
bn9 = BatchNormalization()(conv9)
relu9 = Activation(“relu”)(bn9)
conv10 = Conv2D(num_filter * 16, 3, activation=“linear”, padding=“same”, strides=1)(relu9)
bn10 = BatchNormalization()(conv10)
relu10 = Activation(“relu”)(bn10)
up1 = UpSampling2D(size=(2, 2), interpolation=“bilinear”)(relu10)
# Decoder (Done)
concat1 = concatenate([up1, relu8], axis=-1) # , axis=3
conv11 = Conv2D(num_filter * 8, 3, activation=“linear”, padding=“same”, strides=1)(concat1)
bn11 = BatchNormalization()(conv11)
relu11 = Activation(“relu”)(bn11)
conv12 = Conv2D(num_filter * 8, 3, activation=“linear”, padding=“same”, strides=1)(relu11)
bn12 = BatchNormalization()(conv12)
relu12 = Activation(“relu”)(bn12)
up2 = UpSampling2D(size=(2, 2), interpolation=“bilinear”)(relu12)
concat2 = concatenate([up2, relu6], axis=-1) # , axis=3
conv13 = Conv2D(num_filter * 4, 3, activation=“linear”, padding=“same”, strides=1)(concat2)
bn13 = BatchNormalization()(conv13)
relu13 = Activation(“relu”)(bn13)
conv14 = Conv2D(num_filter * 4, 3, activation=“linear”, padding=“same”, strides=1)(relu13)
bn14 = BatchNormalization()(conv14)
relu14 = Activation(“relu”)(bn14)
up3 = UpSampling2D(size=(2, 2), interpolation=“bilinear”)(relu14)
concat3 = concatenate([up3, relu4], axis=-1) # , axis=3
conv15 = Conv2D(num_filter * 2, 3, activation=“linear”, padding=“same”, strides=1)(concat3)
bn15 = BatchNormalization()(conv15)
relu15 = Activation(“relu”)(bn15)
conv16 = Conv2D(num_filter * 2, 3, activation=“linear”, padding=“same”, strides=1)(relu15)
bn16 = BatchNormalization()(conv16)
relu16 = Activation(“relu”)(bn16)
up4 = UpSampling2D(size=(2, 2), interpolation=“bilinear”)(relu16)
concat4 = concatenate([up4, relu2], axis=-1) # , axis=3
conv17 = Conv2D(num_filter * 1, 3, activation=“linear”, padding=“same”, strides=1)(concat4)
bn17 = BatchNormalization()(conv17)
relu17 = Activation(“relu”)(bn17)
conv18 = Conv2D(num_filter * 1, 3, activation=“linear”, padding=“same”, strides=1)(relu17)
bn18 = BatchNormalization()(conv18)
relu18 = Activation(“relu”)(bn18)
# Segmentation branch
segmentation_output = Conv2D(1, 1, activation=“sigmoid”, name=“segmentation_output”)(relu18) # original
# Classification branch (Not done)
gap1 = GlobalAveragePooling2D()(relu8)
gap2 = GlobalAveragePooling2D()(relu10)
gap3 = GlobalAveragePooling2D()(relu12)
conv20 = Conv2D(num_filter * 1, 3, activation=“linear”, padding=“same”, strides=1)(segmentation_output)
bn20 = BatchNormalization()(conv20)
relu20 = Activation(“relu”)(bn20)
down5 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu20)
conv21 = Conv2D(num_filter * 2, 3, activation=“linear”, padding=“same”, strides=1)(down5)
bn21 = BatchNormalization()(conv21)
relu21 = Activation(“relu”)(bn21)
down6 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu21)
conv22 = Conv2D(num_filter * 4, 3, activation=“linear”, padding=“same”, strides=1)(down6)
bn22 = BatchNormalization()(conv22)
relu22 = Activation(“relu”)(bn22)
down7 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu22)
flatten1 = Flatten()(down7)
concat5 = concatenate([gap1, gap2, gap3, flatten1], axis=-1)
# FC layers
fc1 = Dense(1024, activation=“relu”)(concat5)
dropout1 = Dropout(0.5)(fc1)
fc2 = Dense(1024, activation=“relu”)(dropout1)
dropout2 = Dropout(0.5)(fc2)
classification_output = Dense(num_classes, activation=“softmax”, name=“classification_output”)(dropout2)
# Define the model
model = Model(inputs=inputs, outputs=[classification_output, segmentation_output])
return model
def segmentation_loss(y_true, y_pred):
y_true = tf.cast(y_true, tf.float32)
y_pred = tf.cast(y_pred, tf.float32)
bce_loss = tf.keras.losses.binary_crossentropy(y_true, y_pred)
smooth = 1e-5
intersection = tf.reduce_sum(y_true * y_pred)
union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred)
dice_loss = 1.0 - 2.0 * (intersection + smooth) / (union + smooth)
segmentation_loss = bce_loss + 1 * dice_loss
return segmentation_loss
def train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs):
checkpoint = ModelCheckpoint(
“multitask_best_weights.h5”,
monitor=“val_classification_output_accuracy”,
save_best_only=True,
mode=“max”,
verbose=1,)
reduce_lr = ReduceLROnPlateau(
monitor=“val_classification_output_accuracy”,
factor=0.3,
patience=2,
min_delta=0.001,
mode=“auto”,
verbose=1,)
tensorboard = TensorBoard(log_dir=“logs”)
model.compile(
optimizer=Adam(learning_rate=0.001),
loss={“classification_output”: “categorical_crossentropy”, “segmentation_output”: segmentation_loss},
metrics={“classification_output”: “accuracy”, “segmentation_output”: “accuracy”},
loss_weights={“classification_output”: 1, “segmentation_output”: 1},)
history = model.fit(
X_train,
{“classification_output”: y_train_class, “segmentation_output”: y_train_seg},
validation_data=(X_val, {“classification_output”: y_val_class, “segmentation_output”: y_val_seg}),
epochs=epochs,
verbose=1,
batch_size=batch_size,
callbacks=[checkpoint, reduce_lr, tensorboard],)
return history
def evaluate_model(model, X_test, y_test_class, y_test_seg):
with tf.keras.utils.custom_object_scope({“segmentation_loss”: segmentation_loss}):
# Load the best model weights
best_model = load_model(“multitask_best_weights.h5”)
# Evaluate the model on test data
test_loss, test_class_loss, test_seg_loss, test_class_acc, test_seg_acc = best_model.evaluate(
X_test, {“classification_output”: y_test_class, “segmentation_output”: y_test_seg})
print(“Test Classification Loss:”, test_class_loss)
print(“Test Segmentation Loss:”, test_seg_loss)
print(“Test Classification Accuracy:”, test_class_acc)
print(“Test Segmentation Accuracy:”, test_seg_acc)
# Evaluate the model on validation data
val_loss, val_class_loss, val_seg_loss, val_class_acc, val_seg_acc = best_model.evaluate(
X_val, {‘classification_output’: y_val_class, ‘segmentation_output’: y_val_seg})
print(“Validation Classification Loss:”, val_class_loss)
print(“Validation Segmentation Loss:”, val_seg_loss)
print(“Validation Classification Accuracy:”, val_class_acc)
print(“Validation Segmentation Accuracy:”, val_seg_acc)
# Evaluate the model on training data
train_loss, train_class_loss, train_seg_loss, train_class_acc, train_seg_acc = best_model.evaluate(X_train, {‘classification_output’: y_train_class, ‘segmentation_output’: y_train_seg})
print(“Train Classification Loss:”, train_class_loss)
print(“Train Segmentation Loss:”, train_seg_loss)
print(“Train Classification Accuracy:”, train_class_acc)
print(“Train Segmentation Accuracy:”, train_seg_acc)
# Return test classification accuracy
return test_class_acc
def plot_performance(history):
# Plot classification accuracy
classification_train_accuracy = history.history[“classification_output_accuracy”]
classification_val_accuracy = history.history[“val_classification_output_accuracy”]
plt.figure(figsize=(7, 3))
plt.plot(classification_train_accuracy, label=“Training Accuracy”)
plt.plot(classification_val_accuracy, label=“Validation Accuracy”)
plt.title(“Classification Accuracy”)
plt.xlabel(“Epochs”)
plt.ylabel(“Accuracy”)
plt.legend()
plt.show()
# Plot classification loss
classification_train_loss = history.history[“classification_output_loss”]
classification_val_loss = history.history[“val_classification_output_loss”]
plt.figure(figsize=(7, 3))
plt.plot(classification_train_loss, “b”, label=“Training Loss”)
plt.plot(classification_val_loss, “r”, label=“Validation Loss”)
plt.title(“Classification Loss”)
plt.xlabel(“Epochs”)
plt.ylabel(“Loss”)
plt.legend()
plt.show()
# Plot segmentation accuracy
segmentation_train_accuracy = history.history[“segmentation_output_accuracy”]
segmentation_val_accuracy = history.history[“val_segmentation_output_accuracy”]
plt.figure(figsize=(7, 3))
plt.plot(segmentation_train_accuracy, label=“Training Accuracy”)
plt.plot(segmentation_val_accuracy, label=“Validation Accuracy”)
plt.title(“Segmentation Accuracy”)
plt.xlabel(“Epochs”)
plt.ylabel(“Accuracy”)
plt.legend()
plt.show()
# Plot segmentation loss
segmentation_train_loss = history.history[“segmentation_output_loss”]
segmentation_val_loss = history.history[“val_segmentation_output_loss”]
plt.figure(figsize=(7, 3))
plt.plot(segmentation_train_loss, “b”, label=“Training Loss”)
plt.plot(segmentation_val_loss, “r”, label=“Validation Loss”)
plt.title(“Segmentation Loss”)
plt.xlabel(“Epochs”)
plt.ylabel(“Loss”)
plt.legend()
plt.show()
# Set image size
image_size = 224
# Define labels
labels = [“bridge”, “excess”, “good”, “insuff”, “no”]
# Set data folders
data_folders = [
“/content/gdrive/MyDrive/Deep learning/FYP_3/4 Dataset Ratio 60 20 20/jit0/b_dip/train”,
“/content/gdrive/MyDrive/Deep learning/FYP_3/4 Dataset Ratio 60 20 20/jit0/b_dip/val”,
“/content/gdrive/MyDrive/Deep learning/FYP_3/4 Dataset Ratio 60 20 20/jit0/b_dip/test”,]
# Load data
X_data, y_class_labels, y_seg_labels = load_data(data_folders)
# Define train:val:test ratio for each class (ratio x4 = exact)
class_data_counts = {
“bridge”: [40, 80, 80],
“excess”: [40, 80, 80],
“good”: [40, 80, 80],
“insuff”: [40, 80, 80],
“no”: [40, 80, 80]
}
# Split data
X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, X_test, y_test_class, y_test_seg = split_data(
X_data, y_class_labels, y_seg_labels, class_data_counts)
‘’‘
print(“Number of train images:”, len(X_train))
print(“Number of train binary masks:”, len(y_train_seg))
print(“Number of validation images:”, len(X_val))
print(“Number of validation binary masks:”, len(y_val_seg))
print(“Number of test images:”, len(X_test))
print(“Number of test binary masks:”, len(y_test_seg))
’‘’
# Initialize the label encoder
label_encoder = LabelEncoder()
label_encoder.fit(y_class_labels)
# Count the number of images of each class in the train, validation, and test sets
train_counts = count_labels(y_train_class, label_encoder)
val_counts = count_labels(y_val_class, label_encoder)
test_counts = count_labels(y_test_class, label_encoder)
print(“Train counts: “, train_counts,” Total in train set:”, sum(train_counts.values()))
print(“Validation counts:”, val_counts, " Total in validation set:“, sum(val_counts.values()))
print(“Test counts: “, test_counts,” Total in test set:”, sum(test_counts.values()))
# Build model
input_shape = (image_size, image_size, 3)
num_classes = len(labels)
model = build_model(input_shape, num_classes)
model.summary()
# Train model n times
test_class_acc_list = []
for i in range(5):
print(f”\nTrain {i+1}:\n")
model = build_model(input_shape, num_classes)
batch_size = 16
epochs = 50
history = train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs)
# Evaluate model on test data
test_class_acc = evaluate_model(model, X_test, y_test_class, y_test_seg)
plot_performance(history)
test_class_acc_list.append(test_class_acc)
# Calculate average test classification accuracy
average_test_class_acc = sum(test_class_acc_list) / len(test_class_acc_list)
print(“Test Classification Accuracy List:”, test_class_acc_list)
print(“Average Test Classification Accuracy:”, average_test_class_acc)
"
The above is the Python code with Keras to do multi-task learning with binary segmentation and classification using one mult-task learning model. Specifically for the small dataset. Check my code. The Test Classification Loss: 1.4311378002166748,
Test Segmentation Loss: 1.0658704042434692, Test Classification Accuracy: 0.3474999964237213, Test Segmentation Accuracy: 0.7845422625541687. How to improve the classification accuracy?
|
39e60bbdb5cbb64a60ff1db0e3a51f27
|
{
"intermediate": 0.3238913416862488,
"beginner": 0.4471043050289154,
"expert": 0.22900435328483582
}
|
43,045
|
how can i make my following code run faster:
|import pandas as pd
import os
from pathlib import Path
# Set the directory where your CSV files are located
base_directory_path = r"..\downloaded_files\Binance\00_rename_columns_sort"
# List of folders to iterate through
folders = [d for d in Path(base_directory_path).iterdir() if d.is_dir()]
# Loop through each folder and then through each CSV file within them
for folder in folders:
# Iterate over each file in the directory
for filename in os.listdir(folder):
if filename.endswith('.csv'): # Make sure to process only CSV files
file_path = os.path.join(folder, filename)
# Read the CSV file
df = pd.read_csv(file_path, skiprows=1)
# Rename the 8th and 9th columns
# Note: Python is zero-indexed, so the 8th column is at index 7, and the 9th is at index 8.
columns = df.columns.tolist()
if len(columns) >= 9: # Check if there are enough columns
columns[7] = 'volume_crypto'
columns[8] = 'volume_base'
df.columns = columns
# Save the modified DataFrame back to CSV
df.to_csv(file_path, index=False) # index=False to prevent adding an unnamed index column
print(f"Renamed {file_path}")
|
61922c10d4dd466734cd7be72cc884a4
|
{
"intermediate": 0.766438364982605,
"beginner": 0.16855348646640778,
"expert": 0.06500814110040665
}
|
43,046
|
scape webpage for pdf files and download
|
9cec3c205ca1b2c8fda98825cc93e62c
|
{
"intermediate": 0.36668577790260315,
"beginner": 0.26391828060150146,
"expert": 0.3693959414958954
}
|
43,047
|
hi
|
a890131e933fa151f82c89533aef3ec8
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
43,048
|
User
write a python program
ask for the location of a file
read all the csv files in the folder and save each individual csv file as sheets in new csv file named IQOQPQ_Summary
make sure the sheet names do not have any invalid characters and the characters do not exceed 31 characters.
from the 7 columns only read 4 columns stated below.
read data from the 1st column starting from row 162
read data from the 5th column starting from row 162
read data from the 6th column starting from row 0
read data from the 7th column starting from row 0.
for every value of column 6 pick from column 1 the values that are closest to it
also save the values from the 5th column that accompany the closest values
save the file
|
c6d4f44fea676e7b2573a336ebfd7737
|
{
"intermediate": 0.4044376611709595,
"beginner": 0.27959364652633667,
"expert": 0.31596872210502625
}
|
43,049
|
bottom overflowed by 39px entre chaque cardannonce:
parent:
Padding(
padding: EdgeInsets.only(bottom: 0), // adjust this value to fit your needs
child: SingleChildScrollView(
child: Container(
height: 480 ,
decoration: BoxDecoration(),
child: GridView.builder(
padding: EdgeInsets.fromLTRB(10,0,10,0),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2, // number of items per row
childAspectRatio: 1,
mainAxisSpacing: 45 // adjust this value to fit your needs
),
itemCount: annonces.length,
itemBuilder: (context, index) {
Annonce annonce = annonces[index];
return Padding(
padding: EdgeInsets.only(right: 12, left:12), // adjust this padding to fit your needs
child: CardAnnonce(
titre: annonce.titre,
imagePath: annonce.imageLink,
isSaved: annonce.isSaved,
prix: annonce.prix,
niveauUrgence: annonce.niveauUrgence,
),
);
},
),
),
),
),
enfant:
import 'dart:ffi';
import 'package:allo/constants/app_colors.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart'; // Import your color file
class CardAnnonce extends StatelessWidget {
final String titre;
final String imagePath;
final bool isSaved;
final double prix;
final int niveauUrgence;
CardAnnonce(
{required this.titre,
required this.imagePath,
required this.isSaved,
required this.prix,
required this.niveauUrgence});
@override
Widget build(BuildContext context) {
return Card(
color: Colors.transparent,
elevation: 0,
child: IntrinsicWidth(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Stack(
children: <Widget>[
Container(
width: 150, // définir la largeur
height: 150, // définir la hauteur
decoration: BoxDecoration(
borderRadius:
BorderRadius.circular(15), // arrondir les bords
image: DecorationImage(
image: AssetImage(imagePath),
fit: BoxFit
.cover, // pour s'assurer que l'image couvre tout le rectangle
),
),
),
Positioned(
right: 10,
bottom: 10,
child: Container(
padding: EdgeInsets.symmetric(horizontal: 15, vertical: 7),
decoration: BoxDecoration(
color: AppColors.danger,
borderRadius: BorderRadius.circular(500000),
),
child: Text(
'Urgence: $niveauUrgence',
style: TextStyle(
color: AppColors.dark,
fontFamily: "NeueRegrade",
fontWeight: FontWeight.w600,
fontSize: 14),
),
),
),
],
),
Padding(
padding: EdgeInsets.fromLTRB(0,6,0,0),
child: Text(titre, style: TextStyle(
fontSize: 16,
fontFamily: "NeueRegrade",
fontWeight: FontWeight.w600
)),
),
Padding(
padding: EdgeInsets.fromLTRB(0,8,0,0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
SvgPicture.asset('assets/icons/bookmark.svg', width: 18, height: 18,),
Text('$prix \€',
style: TextStyle(
fontSize: 14,
fontFamily: "NeueRegrade",
fontWeight: FontWeight.w700
)
),
],
),
),
],
),
),
);
}
}
|
b7c48fcde231083f2a6112a58e9ed650
|
{
"intermediate": 0.2548825740814209,
"beginner": 0.35772866010665894,
"expert": 0.38738876581192017
}
|
43,050
|
bottom overflowed by 39px entre chaque cardannonce:
parent:
Padding(
padding: EdgeInsets.only(bottom: 0), // adjust this value to fit your needs
child: SingleChildScrollView(
child: Container(
height: 480 ,
decoration: BoxDecoration(),
child: GridView.builder(
padding: EdgeInsets.fromLTRB(10,0,10,0),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2, // number of items per row
childAspectRatio: 1,
mainAxisSpacing: 45 // adjust this value to fit your needs
),
itemCount: annonces.length,
itemBuilder: (context, index) {
Annonce annonce = annonces[index];
return Padding(
padding: EdgeInsets.only(right: 12, left:12), // adjust this padding to fit your needs
child: CardAnnonce(
titre: annonce.titre,
imagePath: annonce.imageLink,
isSaved: annonce.isSaved,
prix: annonce.prix,
niveauUrgence: annonce.niveauUrgence,
),
);
},
),
),
),
),
enfant:
import 'dart:ffi';
import 'package:allo/constants/app_colors.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart'; // Import your color file
class CardAnnonce extends StatelessWidget {
final String titre;
final String imagePath;
final bool isSaved;
final double prix;
final int niveauUrgence;
CardAnnonce(
{required this.titre,
required this.imagePath,
required this.isSaved,
required this.prix,
required this.niveauUrgence});
@override
Widget build(BuildContext context) {
return Card(
color: Colors.transparent,
elevation: 0,
child: IntrinsicWidth(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Stack(
children: <Widget>[
Container(
width: 150, // définir la largeur
height: 150, // définir la hauteur
decoration: BoxDecoration(
borderRadius:
BorderRadius.circular(15), // arrondir les bords
image: DecorationImage(
image: AssetImage(imagePath),
fit: BoxFit
.cover, // pour s'assurer que l'image couvre tout le rectangle
),
),
),
Positioned(
right: 10,
bottom: 10,
child: Container(
padding: EdgeInsets.symmetric(horizontal: 15, vertical: 7),
decoration: BoxDecoration(
color: AppColors.danger,
borderRadius: BorderRadius.circular(500000),
),
child: Text(
'Urgence: $niveauUrgence',
style: TextStyle(
color: AppColors.dark,
fontFamily: "NeueRegrade",
fontWeight: FontWeight.w600,
fontSize: 14),
),
),
),
],
),
Padding(
padding: EdgeInsets.fromLTRB(0,6,0,0),
child: Text(titre, style: TextStyle(
fontSize: 16,
fontFamily: "NeueRegrade",
fontWeight: FontWeight.w600
)),
),
Padding(
padding: EdgeInsets.fromLTRB(0,8,0,0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
SvgPicture.asset('assets/icons/bookmark.svg', width: 18, height: 18,),
Text('$prix \€',
style: TextStyle(
fontSize: 14,
fontFamily: "NeueRegrade",
fontWeight: FontWeight.w700
)
),
],
),
),
],
),
),
);
}
}
|
10a0ae2f0ae02b946c326ee4b55dc957
|
{
"intermediate": 0.2548825740814209,
"beginner": 0.35772866010665894,
"expert": 0.38738876581192017
}
|
43,051
|
Would https://api-de8c7017.duosecurity.com/frame/v4/auth/prompt?sid=frameless-462180c9-58e4-4249-9d17-0f3b19708953 qualitfy for the matches for a content script of this: "matches": ["https://*.duosecurity.com/*"],
|
4e7461be27fcb0e232335d2fd9e56e4c
|
{
"intermediate": 0.573438286781311,
"beginner": 0.212256520986557,
"expert": 0.21430516242980957
}
|
43,052
|
Ok lambda here is not doing anything.
import torch
from torch.optim.optimizer import Optimizer
import math
class Fusedbun(Optimizer):
def __init__(self, params, lr=1e-3, eps=1e-8, beta_decay=0.8, Lambda=0.01, momentum_beta=0.9, centralize=True, use_rms=True):
defaults = dict(lr=lr, eps=eps, beta_decay=beta_decay, Lambda=Lambda, momentum_beta=momentum_beta, centralize=centralize, use_rms=use_rms)
super(Fusedbun, self).__init__(params, defaults)
@torch.no_grad()
def step(self, closure=None):
loss = None
if closure is not None:
loss = closure()
for group in self.param_groups:
lr = group['lr']
eps = group['eps']
beta_decay = group['beta_decay']
Lambda = group['Lambda']
momentum_beta = group['momentum_beta']
centralize = group['centralize']
use_rms = group['use_rms']
for p in group['params']:
if p.grad is None:
continue
grad = p.grad.data
if centralize and len(p.shape) > 1:
grad = grad.sub(grad.mean(dim=tuple(range(1, len(grad.shape))), keepdim=True))
state = self.state[p]
if len(state) == 0:
state['step'] = 0
state['accumulator'] = torch.zeros_like(p.data)
if momentum_beta > 0:
state['momentum_buffer'] = torch.zeros_like(p.data)
acc = state['accumulator']
t = state['step'] + 1
state['step'] = t
if p.dim() > 1:
grad_squared = grad.square().mean(dim=0)
else:
grad_squared = grad.square()
beta_t = 1.0 - math.pow(t, -beta_decay)
acc.mul_(beta_t).add_(grad_squared, alpha=1-beta_t)
denom = acc.sqrt().add(eps)
grad_normalized = grad / denom if use_rms else grad
if momentum_beta > 0:
momentum_buffer = state['momentum_buffer']
momentum_buffer.mul_(momentum_beta).add_(grad_normalized, alpha=1-momentum_beta)
grad_normalized = momentum_buffer
p.data.add_(grad_normalized, alpha=-lr)
return loss
Make it better. Im making optimiser both memory efficient and better than others out there. I have taken inpiration from SM3 and Adalite. You must know SM3, im giving you adalite code. Make necessary changes.
import torch
import math
from dataclasses import dataclass, field
from typing import List, Optional
from collections import defaultdict
# Somewhat based on https://gist.github.com/albanD/18c240bd2e09f9d93f5c4a0c9ccda39e and LOMO
@dataclass
class OverlapOptimizer:
model: torch.nn.Module
lr: Optional[float] = None
decay: Optional[float] = 0.0
_acc_grads: Optional[List] = field(default_factory=lambda: [])
def init(self):
for p in self.model.parameters():
if p.requires_grad:
self.prepare(p)
self.hook(p)
def step(self, loss, lr):
pass
def hook(self, p):
pass
@dataclass
class OverlapSGD(OverlapOptimizer):
sign: bool = False
def prepare(self, p):
return
def step(self, loss, lr):
self.lr = lr
loss.backward()
def hook(self, p):
ag = p.view_as(p).grad_fn.next_functions[0][0]
p._acc_grads = [ag]
@torch.no_grad()
def gf(*_):
if self.sign:
p.add_(p.grad.sign(), alpha=-self.lr)
else:
p.add_(p.grad, alpha=-self.lr)
p.grad = None
ag.register_hook(gf)
@dataclass
class Adalite(OverlapOptimizer):
eps: float = 1e-5
Lambda: float = 0.01 # Akin to weight-decay
beta_decay: float = 0.8
centralize: bool = True
use_rms: bool = True
momentum: bool = False
momentum_beta: float = 0.9
_t: int = 0
def step(self, loss, lr=None):
self._t += 1
self.lr = lr
loss.backward()
def prepare(self, p):
if len(p.shape) == 2:
p._c = torch.zeros(p.shape[1], device=p.device, dtype=p.dtype)
else:
p._v = torch.zeros_like(p)
if self.momentum:
p._m = torch.zeros_like(p)
def hook(self, p):
ag = p.view_as(p).grad_fn.next_functions[0][0]
p._acc_grads = [ag]
@torch.no_grad()
def gf(*_):
alpha = self.lr
g = p.grad
if self.centralize and sum(g.shape) > 1:
g.sub_(g.mean(dim=tuple(range(1, len(g.shape))), keepdim=True))
beta_t = 1.0 - math.pow(self._t, -self.beta_decay)
u = g.square()
if len(p.shape) == 2:
u.mul_(1-beta_t).add_(p._c.unsqueeze(0).broadcast_to(g.shape), alpha=beta_t)
u.add_(self.eps)
p._c = u.mean(dim=0)
else:
u.mul_(1-beta_t).add_(p._v, alpha=beta_t)
u.add_(self.eps)
p._v = u
m = u.rsqrt() * g
if self.use_rms:
m.div_(max(1.0, m.square().mean().sqrt()))
p_norm = p.norm()
g_norm = g.norm()
if p_norm != 0 and g_norm != 0:
m.mul_(p_norm / g_norm)
m.add_(p - p/p_norm, alpha=self.Lambda)
if self.momentum:
p._m.mul_(self.momentum_beta).add_(m, alpha=1-self.momentum_beta)
m = p._m
p.add_(m, alpha=-alpha)
p.grad = None
ag.register_hook(gf)
|
e264a58e55d71cf9e0561d479de7d68c
|
{
"intermediate": 0.3415999412536621,
"beginner": 0.4620059132575989,
"expert": 0.1963941603899002
}
|
43,053
|
code:
import pandas as pd
import os
from concurrent.futures import ThreadPoolExecutor, as_completed
def load_data(csv_path):
df = pd.read_csv(csv_path, skiprows=1)
# Convert Unix timestamp to datetime (assuming Unix timestamp is in milliseconds)
# df['Date'] = pd.to_datetime(df['Unix'], unit='ms')
return df
def aggregate_to_4h(df):
df.set_index('Date', inplace=True)
# Aggregate according to the specified column names
aggregation = {
'Open': 'first',
'High': 'max',
'Low': 'min',
'Close': 'last',
'volume_crypto': 'sum',
'volume_base': 'sum',
'tradecount': 'sum'
}
df_4h = df.resample('4H').agg(aggregation)
df.sort_index(inplace=True)
df_4h['Open'] = df.groupby(pd.Grouper(freq='4H'))['Open'].first().values
return df_4h
def create_4h(filename, csv_path, out_directory_path):
try:
df = load_data(csv_path)
df_4h = aggregate_to_4h(df)
# Save the aggregated data to a new CSV file
output_path = os.path.join(out_directory_path, f'4h_{filename}')
df_4h.to_csv(output_path)
print(f"4h created {output_path}")
except Exception as e:
print(f"Failed to process {csv_path} due to {e}")
def process_files(directory, out_directory_path):
with ThreadPoolExecutor() as executor:
futures = []
for filename in os.listdir(directory):
if filename.endswith('.csv'):
csv_path = os.path.join(directory, filename)
print(f"Processing {filename}…")
futures.append(executor.submit(create_4h, filename, csv_path, out_directory_path))
for future in as_completed(futures):
pass # Future results or exceptions can be processed here if needed
def main():
# Replace the path with the directory containing your CSV files
directory_path = r"..\downloaded_files\Binance\00_rename_columns_sort\1h_spot"
out_directory_path = r"..\downloaded_files\Binance\00_rename_columns_sort\4h_spot"
process_files(directory_path, out_directory_path)
main()
errorr:
Failed to process ..\downloaded_files\Binance\00_rename_columns_sort\1h_spot\Binance_BNBBRL_1h.csv due to "None of ['Unix'] are in the columns"
Failed to process ..\downloaded_files\Binance\00_rename_columns_sort\1h_spot\Binance_BNBBTC_1h.csv due to "None of ['Unix'] are in the columns"
Failed to process ..\downloaded_files\Binance\00_rename_columns_sort\1h_spot\Binance_BNBDAI_1h.csv due to "None of ['Unix'] are in the columns"
Failed to process ..\downloaded_files\Binance\00_rename_columns_sort\1h_spot\Binance_BNBBUSD_1h.csv due to "None of ['Unix'] are in the columns"
Failed to process ..\downloaded_files\Binance\00_rename_columns_sort\1h_spot\Binance_BNBDOWNUSDT_1h.csv due to "None of ['Unix'] are in the columns"
some of my data :
Unix Date Symbol Open High Low Close volume_crypto volume_base tradecount
1.60887E+12 12/25/2020 5:00 1INCHBTC 8.51E-06 0.000168 8.51E-06 0.00010947 2207916 256.8839429 17168
1.60888E+12 12/25/2020 6:00 1INCHBTC 0.00010947 0.00011329 9.41E-05 0.00010693 1833765.2 186.9121981 11343
1.60888E+12 12/25/2020 7:00 1INCHBTC 0.00010634 0.00012298 0.00010047 0.00011025 2067113.5 236.2882339 12743
1.60888E+12 12/25/2020 8:00 1INCHBTC 0.00011162 0.0001195 0.00010347 0.00011029 1570496.5 175.0973559 10418
1.60889E+12 12/25/2020 9:00 1INCHBTC 0.00011007 0.000116 0.00010718 0.00011023 862685.8 96.20224944 6533
1.60889E+12 12/25/2020 10:00 1INCHBTC 0.0001103 0.00012444 0.0001103 0.00011533 2052454.4 242.2437374 13444
1.60889E+12 12/25/2020 11:00 1INCHBTC 0.00011533 0.00011999 0.0001024 0.00010768 1410575.3 157.3953309 9802
1.6089E+12 12/25/2020 12:00 1INCHBTC 0.00010774 0.0001131 9.71E-05 9.89E-05 1265864.7 134.7208468 10978
|
29c93dfdc081c94de4419d86309850be
|
{
"intermediate": 0.3767569065093994,
"beginner": 0.4157220423221588,
"expert": 0.20752103626728058
}
|
43,054
|
You are a Python expert who can provide clear, concise, high-quality code.
“
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import cv2
import random
import tensorflow as tf
import tkinter as tk
from tkinter import filedialog
from PIL import ImageTk, Image
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
from IPython.display import display, clear_output
from tensorflow.keras.preprocessing import image
from tensorflow.keras.optimizers import Adam, SGD, RMSprop, AdamW, Adadelta, Adagrad, Adamax, Adafactor, Nadam, Ftrl
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tqdm import tqdm
import os
from sklearn.utils import shuffle
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential, Model, load_model
from tensorflow.keras.layers import (
GlobalAveragePooling2D,
Dropout,
Dense,
Conv2D,
MaxPooling2D,
Flatten,
Dropout,
BatchNormalization,
Activation,
concatenate,
Conv2DTranspose,
Input,
Reshape,
UpSampling2D,
)
from tensorflow.keras.applications import (
EfficientNetV2B0,
EfficientNetV2B1,
EfficientNetV2B2,
EfficientNetV2B3,
EfficientNetV2L,
EfficientNetV2M,
EfficientNetV2S,
)
from tensorflow.keras.applications import Xception
from tensorflow.keras.applications import VGG16, VGG19
from tensorflow.keras.applications import ResNet50, ResNet101, ResNet152, ResNetRS50, ResNetRS101
from tensorflow.keras.applications import InceptionResNetV2, ConvNeXtXLarge, ConvNeXtBase, DenseNet121, MobileNetV2, NASNetLarge, NASNetMobile
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau, TensorBoard, ModelCheckpoint
from sklearn.metrics import classification_report, confusion_matrix
import ipywidgets as widgets
import io
from PIL import Image
from IPython.display import display, clear_output
from warnings import filterwarnings
from google.colab import drive
drive.mount(”/content/gdrive")
def load_data(data_folders):
X_data = [] # Combined data
y_class_labels = [] # Combined classification labels
y_seg_labels = [] # Combined segmentation labels
for folderPath in data_folders:
for label in labels:
label_folder_path = os.path.join(folderPath, label)
for filename in tqdm(os.listdir(label_folder_path)):
if filename.endswith(“.jpg”):
img = cv2.imread(os.path.join(label_folder_path, filename))
img = cv2.resize(img, (image_size, image_size))
X_data.append(img)
y_class_labels.append(label)
seg_filename = filename.split(“.”)[0] + “.png”
seg_img = cv2.imread(os.path.join(label_folder_path, seg_filename), 0)
seg_img = cv2.resize(seg_img, (image_size, image_size))
seg_img = np.where(seg_img > 0, 1, 0) # Convert segmentation mask to binary
y_seg_labels.append(seg_img)
X_data = np.array(X_data)
y_class_labels = np.array(y_class_labels)
y_seg_labels = np.array(y_seg_labels)
X_data, y_class_labels, y_seg_labels = shuffle(X_data, y_class_labels, y_seg_labels, random_state=101)
return X_data, y_class_labels, y_seg_labels
def split_data(X_data, y_class_labels, y_seg_labels, class_data_counts):
X_train = []
y_train_class = []
y_train_seg = []
X_val = []
y_val_class = []
y_val_seg = []
X_test = []
y_test_class = []
y_test_seg = []
for label, count in class_data_counts.items():
label_indices = np.where(y_class_labels == label)[0]
class_X_data = X_data[label_indices]
class_y_class_labels = y_class_labels[label_indices]
class_y_seg_labels = y_seg_labels[label_indices]
train_count = count[0]
val_count = count[1]
test_count = count[2]
class_X_train = class_X_data[:train_count]
class_y_train_class = class_y_class_labels[:train_count]
class_y_train_seg = class_y_seg_labels[:train_count]
class_X_val = class_X_data[train_count: train_count + val_count]
class_y_val_class = class_y_class_labels[train_count: train_count + val_count]
class_y_val_seg = class_y_seg_labels[train_count: train_count + val_count]
class_X_test = class_X_data[train_count + val_count: train_count + val_count + test_count]
class_y_test_class = class_y_class_labels[train_count + val_count: train_count + val_count + test_count]
class_y_test_seg = class_y_seg_labels[train_count + val_count: train_count + val_count + test_count]
X_train.extend(class_X_train)
y_train_class.extend(class_y_train_class)
y_train_seg.extend(class_y_train_seg)
X_val.extend(class_X_val)
y_val_class.extend(class_y_val_class)
y_val_seg.extend(class_y_val_seg)
X_test.extend(class_X_test)
y_test_class.extend(class_y_test_class)
y_test_seg.extend(class_y_test_seg)
# Convert class labels to categorical
label_encoder = LabelEncoder()
y_train_class_encoded = label_encoder.fit_transform(y_train_class)
y_train_class_categorical = to_categorical(y_train_class_encoded)
y_val_class_encoded = label_encoder.transform(y_val_class)
y_val_class_categorical = to_categorical(y_val_class_encoded)
y_test_class_encoded = label_encoder.transform(y_test_class)
y_test_class_categorical = to_categorical(y_test_class_encoded)
return (
np.array(X_train),
np.array(y_train_class_categorical),
np.array(y_train_seg),
np.array(X_val),
np.array(y_val_class_categorical),
np.array(y_val_seg),
np.array(X_test),
np.array(y_test_class_categorical),
np.array(y_test_seg),
)
def count_labels(y_class_categorical, label_encoder):
# Convert one-hot encoded labels back to label encoded
y_class_labels = np.argmax(y_class_categorical, axis=1)
# Convert label encoded labels back to original class names
y_class_names = label_encoder.inverse_transform(y_class_labels)
unique, counts = np.unique(y_class_names, return_counts=True)
return dict(zip(unique, counts))
def build_model(input_shape, num_classes):
num_filter = 32 # 16/32 best, 8: best classification but no segment
# Encoder (Done)
inputs = Input(input_shape)
conv1 = Conv2D(num_filter * 1, 3, activation=“linear”, padding=“same”, strides=1)(inputs)
bn1 = BatchNormalization()(conv1)
relu1 = Activation(“relu”)(bn1)
conv2 = Conv2D(num_filter * 1, 3, activation=“linear”, padding=“same”, strides=1)(relu1)
bn2 = BatchNormalization()(conv2)
relu2 = Activation(“relu”)(bn2)
down1 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu2)
conv3 = Conv2D(num_filter * 2, 3, activation=“linear”, padding=“same”, strides=1)(down1)
bn3 = BatchNormalization()(conv3)
relu3 = Activation(“relu”)(bn3)
conv4 = Conv2D(num_filter * 2, 3, activation=“linear”, padding=“same”, strides=1)(relu3)
bn4 = BatchNormalization()(conv4)
relu4 = Activation(“relu”)(bn4)
down2 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu4)
conv5 = Conv2D(num_filter * 4, 3, activation=“linear”, padding=“same”, strides=1)(down2)
bn5 = BatchNormalization()(conv5)
relu5 = Activation(“relu”)(bn5)
conv6 = Conv2D(num_filter * 4, 3, activation=“linear”, padding=“same”, strides=1)(relu5)
bn6 = BatchNormalization()(conv6)
relu6 = Activation(“relu”)(bn6)
down3 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu6)
conv7 = Conv2D(num_filter * 8, 3, activation=“linear”, padding=“same”, strides=1)(down3)
bn7 = BatchNormalization()(conv7)
relu7 = Activation(“relu”)(bn7)
conv8 = Conv2D(num_filter * 8, 3, activation=“linear”, padding=“same”, strides=1)(relu7)
bn8 = BatchNormalization()(conv8)
relu8 = Activation(“relu”)(bn8)
# Middle
down4 = MaxPooling2D(pool_size=(2, 2), strides=2)(relu8)
conv9 = Conv2D(num_filter * 16, 3, activation=“linear”, padding=“same”, strides=1)(down4)
bn9 = BatchNormalization()(conv9)
relu9 = Activation(“relu”)(bn9)
conv10 = Conv2D(num_filter * 16, 3, activation=“linear”, padding=“same”, strides=1)(relu9)
bn10 = BatchNormalization()(conv10)
relu10 = Activation(“relu”)(bn10)
up1 = UpSampling2D(size=(2, 2), interpolation=“bilinear”)(relu10)
# Decoder (Done)
concat1 = concatenate([up1, relu8], axis=-1) # , axis=3
conv11 = Conv2D(num_filter * 8, 3, activation=“linear”, padding=“same”, strides=1)(concat1)
bn11 = BatchNormalization()(conv11)
relu11 = Activation(“relu”)(bn11)
conv12 = Conv2D(num_filter * 8, 3, activation=“linear”, padding=“same”, strides=1)(relu11)
bn12 = BatchNormalization()(conv12)
relu12 = Activation(“relu”)(bn12)
up2 = UpSampling2D(size=(2, 2), interpolation=“bilinear”)(relu12)
concat2 = concatenate([up2, relu6], axis=-1) # , axis=3
conv13 = Conv2D(num_filter * 4, 3, activation=“linear”, padding=“same”, strides=1)(concat2)
bn13 = BatchNormalization()(conv13)
relu13 = Activation(“relu”)(bn13)
conv14 = Conv2D(num_filter * 4, 3, activation=“linear”, padding=“same”, strides=1)(relu13)
bn14 = BatchNormalization()(conv14)
relu14 = Activation(“relu”)(bn14)
up3 = UpSampling2D(size=(2, 2), interpolation=“bilinear”)(relu14)
concat3 = concatenate([up3, relu4], axis=-1) # , axis=3
conv15 = Conv2D(num_filter * 2, 3, activation=“linear”, padding=“same”, strides=1)(concat3)
bn15 = BatchNormalization()(conv15)
relu15 = Activation(“relu”)(bn15)
conv16 = Conv2D(num_filter * 2, 3, activation=“linear”, padding=“same”, strides=1)(relu15)
bn16 = BatchNormalization()(conv16)
relu16 = Activation(“relu”)(bn16)
up4 = UpSampling2D(size=(2, 2), interpolation=“bilinear”)(relu16)
concat4 = concatenate([up4, relu2], axis=-1) # , axis=3
conv17 = Conv2D(num_filter * 1, 3, activation=“linear”, padding=“same”, strides=1)(concat4)
bn17 = BatchNormalization()(conv17)
relu17 = Activation(“relu”)(bn17)
conv18 = Conv2D(num_filter * 1, 3, activation=“linear”, padding=“same”, strides=1)(relu17)
bn18 = BatchNormalization()(conv18)
relu18 = Activation(“relu”)(bn18)
# Segmentation branch
segmentation_output = Conv2D(1, 1, activation=“sigmoid”, name=“segmentation_output”)(relu18) # original
# Classification branch (Not done)
gap1 = GlobalAveragePooling2D()(relu8)
gap2 = GlobalAveragePooling2D()(relu10)
gap3 = GlobalAveragePooling2D()(relu12)
conv20 = Conv2D(num_filter * 1, 3, activation=“linear”, padding=“same”, strides=1)(segmentation_output)
bn20 = BatchNormalization()(conv20)
relu20 = Activation(“relu”)(bn20)
down5 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu20)
conv21 = Conv2D(num_filter * 2, 3, activation=“linear”, padding=“same”, strides=1)(down5)
bn21 = BatchNormalization()(conv21)
relu21 = Activation(“relu”)(bn21)
down6 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu21)
conv22 = Conv2D(num_filter * 4, 3, activation=“linear”, padding=“same”, strides=1)(down6)
bn22 = BatchNormalization()(conv22)
relu22 = Activation(“relu”)(bn22)
down7 = MaxPooling2D(pool_size=(4, 4), strides=4)(relu22)
flatten1 = Flatten()(down7)
concat5 = concatenate([gap1, gap2, gap3, flatten1], axis=-1)
# FC layers
fc1 = Dense(1024, activation=“relu”)(concat5)
dropout1 = Dropout(0.5)(fc1)
fc2 = Dense(1024, activation=“relu”)(dropout1)
dropout2 = Dropout(0.5)(fc2)
classification_output = Dense(num_classes, activation=“softmax”, name=“classification_output”)(dropout2)
# Define the model
model = Model(inputs=inputs, outputs=[classification_output, segmentation_output])
return model
def segmentation_loss(y_true, y_pred):
y_true = tf.cast(y_true, tf.float32)
y_pred = tf.cast(y_pred, tf.float32)
bce_loss = tf.keras.losses.binary_crossentropy(y_true, y_pred)
smooth = 1e-5
intersection = tf.reduce_sum(y_true * y_pred)
union = tf.reduce_sum(y_true) + tf.reduce_sum(y_pred)
dice_loss = 1.0 - 2.0 * (intersection + smooth) / (union + smooth)
segmentation_loss = bce_loss + 1 * dice_loss
return segmentation_loss
def train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs):
checkpoint = ModelCheckpoint(
“multitask_best_weights.h5”,
monitor=“val_classification_output_accuracy”,
save_best_only=True,
mode=“max”,
verbose=1,)
reduce_lr = ReduceLROnPlateau(
monitor=“val_classification_output_accuracy”,
factor=0.3,
patience=2,
min_delta=0.001,
mode=“auto”,
verbose=1,)
tensorboard = TensorBoard(log_dir=“logs”)
model.compile(
optimizer=Adam(learning_rate=0.001),
loss={“classification_output”: “categorical_crossentropy”, “segmentation_output”: segmentation_loss},
metrics={“classification_output”: “accuracy”, “segmentation_output”: “accuracy”},
loss_weights={“classification_output”: 1, “segmentation_output”: 1},)
history = model.fit(
X_train,
{“classification_output”: y_train_class, “segmentation_output”: y_train_seg},
validation_data=(X_val, {“classification_output”: y_val_class, “segmentation_output”: y_val_seg}),
epochs=epochs,
verbose=1,
batch_size=batch_size,
callbacks=[checkpoint, reduce_lr, tensorboard],)
return history
def evaluate_model(model, X_test, y_test_class, y_test_seg):
with tf.keras.utils.custom_object_scope({“segmentation_loss”: segmentation_loss}):
# Load the best model weights
best_model = load_model(“multitask_best_weights.h5”)
# Evaluate the model on test data
test_loss, test_class_loss, test_seg_loss, test_class_acc, test_seg_acc = best_model.evaluate(
X_test, {“classification_output”: y_test_class, “segmentation_output”: y_test_seg})
print(“Test Classification Loss:”, test_class_loss)
print(“Test Segmentation Loss:”, test_seg_loss)
print(“Test Classification Accuracy:”, test_class_acc)
print(“Test Segmentation Accuracy:”, test_seg_acc)
# Evaluate the model on validation data
val_loss, val_class_loss, val_seg_loss, val_class_acc, val_seg_acc = best_model.evaluate(
X_val, {‘classification_output’: y_val_class, ‘segmentation_output’: y_val_seg})
print(“Validation Classification Loss:”, val_class_loss)
print(“Validation Segmentation Loss:”, val_seg_loss)
print(“Validation Classification Accuracy:”, val_class_acc)
print(“Validation Segmentation Accuracy:”, val_seg_acc)
# Evaluate the model on training data
train_loss, train_class_loss, train_seg_loss, train_class_acc, train_seg_acc = best_model.evaluate(X_train, {‘classification_output’: y_train_class, ‘segmentation_output’: y_train_seg})
print(“Train Classification Loss:”, train_class_loss)
print(“Train Segmentation Loss:”, train_seg_loss)
print(“Train Classification Accuracy:”, train_class_acc)
print(“Train Segmentation Accuracy:”, train_seg_acc)
# Return test classification accuracy
return test_class_acc
def plot_performance(history):
# Plot classification accuracy
classification_train_accuracy = history.history[“classification_output_accuracy”]
classification_val_accuracy = history.history[“val_classification_output_accuracy”]
plt.figure(figsize=(7, 3))
plt.plot(classification_train_accuracy, label=“Training Accuracy”)
plt.plot(classification_val_accuracy, label=“Validation Accuracy”)
plt.title(“Classification Accuracy”)
plt.xlabel(“Epochs”)
plt.ylabel(“Accuracy”)
plt.legend()
plt.show()
# Plot classification loss
classification_train_loss = history.history[“classification_output_loss”]
classification_val_loss = history.history[“val_classification_output_loss”]
plt.figure(figsize=(7, 3))
plt.plot(classification_train_loss, “b”, label=“Training Loss”)
plt.plot(classification_val_loss, “r”, label=“Validation Loss”)
plt.title(“Classification Loss”)
plt.xlabel(“Epochs”)
plt.ylabel(“Loss”)
plt.legend()
plt.show()
# Plot segmentation accuracy
segmentation_train_accuracy = history.history[“segmentation_output_accuracy”]
segmentation_val_accuracy = history.history[“val_segmentation_output_accuracy”]
plt.figure(figsize=(7, 3))
plt.plot(segmentation_train_accuracy, label=“Training Accuracy”)
plt.plot(segmentation_val_accuracy, label=“Validation Accuracy”)
plt.title(“Segmentation Accuracy”)
plt.xlabel(“Epochs”)
plt.ylabel(“Accuracy”)
plt.legend()
plt.show()
# Plot segmentation loss
segmentation_train_loss = history.history[“segmentation_output_loss”]
segmentation_val_loss = history.history[“val_segmentation_output_loss”]
plt.figure(figsize=(7, 3))
plt.plot(segmentation_train_loss, “b”, label=“Training Loss”)
plt.plot(segmentation_val_loss, “r”, label=“Validation Loss”)
plt.title(“Segmentation Loss”)
plt.xlabel(“Epochs”)
plt.ylabel(“Loss”)
plt.legend()
plt.show()
# Set image size
image_size = 224
# Define labels
labels = [“bridge”, “excess”, “good”, “insuff”, “no”]
# Set data folders
data_folders = [
“/content/gdrive/MyDrive/Deep learning/FYP_3/4 Dataset Ratio 60 20 20/jit0/b_dip/train”,
“/content/gdrive/MyDrive/Deep learning/FYP_3/4 Dataset Ratio 60 20 20/jit0/b_dip/val”,
“/content/gdrive/MyDrive/Deep learning/FYP_3/4 Dataset Ratio 60 20 20/jit0/b_dip/test”,]
# Load data
X_data, y_class_labels, y_seg_labels = load_data(data_folders)
# Define train:val:test ratio for each class (ratio x4 = exact)
class_data_counts = {
“bridge”: [40, 80, 80],
“excess”: [40, 80, 80],
“good”: [40, 80, 80],
“insuff”: [40, 80, 80],
“no”: [40, 80, 80]
}
# Split data
X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, X_test, y_test_class, y_test_seg = split_data(
X_data, y_class_labels, y_seg_labels, class_data_counts)
‘’‘
print(“Number of train images:”, len(X_train))
print(“Number of train binary masks:”, len(y_train_seg))
print(“Number of validation images:”, len(X_val))
print(“Number of validation binary masks:”, len(y_val_seg))
print(“Number of test images:”, len(X_test))
print(“Number of test binary masks:”, len(y_test_seg))
’‘’
# Initialize the label encoder
label_encoder = LabelEncoder()
label_encoder.fit(y_class_labels)
# Count the number of images of each class in the train, validation, and test sets
train_counts = count_labels(y_train_class, label_encoder)
val_counts = count_labels(y_val_class, label_encoder)
test_counts = count_labels(y_test_class, label_encoder)
print(“Train counts: “, train_counts,” Total in train set:”, sum(train_counts.values()))
print(“Validation counts:”, val_counts, " Total in validation set:“, sum(val_counts.values()))
print(“Test counts: “, test_counts,” Total in test set:”, sum(test_counts.values()))
# Build model
input_shape = (image_size, image_size, 3)
num_classes = len(labels)
model = build_model(input_shape, num_classes)
model.summary()
# Train model n times
test_class_acc_list = []
for i in range(5):
print(f”\nTrain {i+1}:\n")
model = build_model(input_shape, num_classes)
batch_size = 16
epochs = 50
history = train_model(model, X_train, y_train_class, y_train_seg, X_val, y_val_class, y_val_seg, batch_size, epochs)
# Evaluate model on test data
test_class_acc = evaluate_model(model, X_test, y_test_class, y_test_seg)
plot_performance(history)
test_class_acc_list.append(test_class_acc)
# Calculate average test classification accuracy
average_test_class_acc = sum(test_class_acc_list) / len(test_class_acc_list)
print(“Test Classification Accuracy List:”, test_class_acc_list)
print(“Average Test Classification Accuracy:”, average_test_class_acc)
"
The above is the Python code with Keras to do multi-task learning with binary segmentation and classification using one mult-task learning model. Specifically for the small dataset. Check my code. The Test Classification Loss: 1.4311378002166748,
Test Segmentation Loss: 1.0658704042434692, Test Classification Accuracy: 0.3474999964237213, Test Segmentation Accuracy: 0.7845422625541687. How to improve the classification accuracy?
|
09173f3ff8e8aa4b4524ca41a86cbded
|
{
"intermediate": 0.3238913416862488,
"beginner": 0.4471043050289154,
"expert": 0.22900435328483582
}
|
43,055
|
private readonly List<ProxyFindMethod> _proxyFinders = new();
как тут удалить элемент
|
7682a1565a43a53ac63bea05bd40de6b
|
{
"intermediate": 0.32983484864234924,
"beginner": 0.32224252820014954,
"expert": 0.34792259335517883
}
|
43,056
|
main.py:3:21: BLK100 Black would make changes.
|
a33448de0ca73f5dbdbc0ea1760d32ed
|
{
"intermediate": 0.3069072663784027,
"beginner": 0.3564210832118988,
"expert": 0.3366716504096985
}
|
43,057
|
private readonly ConcurrentBag<Proxy> _proxies = new();
как тут удалить элемент
|
89b989a142dc521d210e255331af3c6b
|
{
"intermediate": 0.33910828828811646,
"beginner": 0.33597487211227417,
"expert": 0.32491686940193176
}
|
43,058
|
Can you make python code
|
dbff3505ac1134e6f4b8dc2649437185
|
{
"intermediate": 0.26454806327819824,
"beginner": 0.41103455424308777,
"expert": 0.3244172930717468
}
|
43,059
|
main.py:3:21: BLK100 Black would make changes. что за ошибка?
|
dc38bd850d10a0fd8f4fe51ff454a5e1
|
{
"intermediate": 0.261484831571579,
"beginner": 0.32061174511909485,
"expert": 0.4179033935070038
}
|
43,060
|
Based on following complete the latest code:
Ok lambda here is not doing anything.
import torch
from torch.optim.optimizer import Optimizer
import math
class Fusedbun(Optimizer):
def init(self, params, lr=1e-3, eps=1e-8, beta_decay=0.8, Lambda=0.01, momentum_beta=0.9, centralize=True, use_rms=True):
defaults = dict(lr=lr, eps=eps, beta_decay=beta_decay, Lambda=Lambda, momentum_beta=momentum_beta, centralize=centralize, use_rms=use_rms)
super(Fusedbun, self).init(params, defaults)
@torch.no_grad()
def step(self, closure=None):
loss = None
if closure is not None:
loss = closure()
for group in self.param_groups:
lr = group[‘lr’]
eps = group[‘eps’]
beta_decay = group[‘beta_decay’]
Lambda = group[‘Lambda’]
momentum_beta = group[‘momentum_beta’]
centralize = group[‘centralize’]
use_rms = group[‘use_rms’]
for p in group[‘params’]:
if p.grad is None:
continue
grad = p.grad.data
if centralize and len(p.shape) > 1:
grad = grad.sub(grad.mean(dim=tuple(range(1, len(grad.shape))), keepdim=True))
state = self.state[p]
if len(state) == 0:
state[‘step’] = 0
state[‘accumulator’] = torch.zeros_like(p.data)
if momentum_beta > 0:
state[‘momentum_buffer’] = torch.zeros_like(p.data)
acc = state[‘accumulator’]
t = state[‘step’] + 1
state[‘step’] = t
if p.dim() > 1:
grad_squared = grad.square().mean(dim=0)
else:
grad_squared = grad.square()
beta_t = 1.0 - math.pow(t, -beta_decay)
acc.mul_(beta_t).add_(grad_squared, alpha=1-beta_t)
denom = acc.sqrt().add(eps)
grad_normalized = grad / denom if use_rms else grad
if momentum_beta > 0:
momentum_buffer = state[‘momentum_buffer’]
momentum_buffer.mul_(momentum_beta).add_(grad_normalized, alpha=1-momentum_beta)
grad_normalized = momentum_buffer
p.data.add_(grad_normalized, alpha=-lr)
return loss
Make it better. Im making optimiser both memory efficient and better than others out there. I have taken inpiration from SM3 and Adalite. You must know SM3, im giving you adalite code. Make necessary changes.
import torch
import math
from dataclasses import dataclass, field
from typing import List, Optional
from collections import defaultdict
# Somewhat based on https://gist.github.com/albanD/18c240bd2e09f9d93f5c4a0c9ccda39e and LOMO
@dataclass
class OverlapOptimizer:
model: torch.nn.Module
lr: Optional[float] = None
decay: Optional[float] = 0.0
acc_grads: Optional[List] = field(default_factory=lambda: [])
def init(self):
for p in self.model.parameters():
if p.requires_grad:
self.prepare§
self.hook§
def step(self, loss, lr):
pass
def hook(self, p):
pass
@dataclass
class OverlapSGD(OverlapOptimizer):
sign: bool = False
def prepare(self, p):
return
def step(self, loss, lr):
self.lr = lr
loss.backward()
def hook(self, p):
ag = p.view_as§.grad_fn.next_functions[0][0]
p.acc_grads = [ag]
@torch.no_grad()
def gf(*):
if self.sign:
p.add(p.grad.sign(), alpha=-self.lr)
else:
p.add_(p.grad, alpha=-self.lr)
p.grad = None
ag.register_hook(gf)
@dataclass
class Adalite(OverlapOptimizer):
eps: float = 1e-5
Lambda: float = 0.01 # Akin to weight-decay
beta_decay: float = 0.8
centralize: bool = True
use_rms: bool = True
momentum: bool = False
momentum_beta: float = 0.9
t: int = 0
def step(self, loss, lr=None):
self.t += 1
self.lr = lr
loss.backward()
def prepare(self, p):
if len(p.shape) == 2:
p.c = torch.zeros(p.shape[1], device=p.device, dtype=p.dtype)
else:
p.v = torch.zeros_like§
if self.momentum:
p.m = torch.zeros_like§
def hook(self, p):
ag = p.view_as§.grad_fn.next_functions[0][0]
p.acc_grads = [ag]
@torch.no_grad()
def gf(*):
alpha = self.lr
g = p.grad
if self.centralize and sum(g.shape) > 1:
g.sub(g.mean(dim=tuple(range(1, len(g.shape))), keepdim=True))
beta_t = 1.0 - math.pow(self.t, -self.beta_decay)
u = g.square()
if len(p.shape) == 2:
u.mul(1-beta_t).add(p.c.unsqueeze(0).broadcast_to(g.shape), alpha=beta_t)
u.add(self.eps)
p.c = u.mean(dim=0)
else:
u.mul(1-beta_t).add(p.v, alpha=beta_t)
u.add(self.eps)
p.v = u
m = u.rsqrt() * g
if self.use_rms:
m.div(max(1.0, m.square().mean().sqrt()))
p_norm = p.norm()
g_norm = g.norm()
if p_norm != 0 and g_norm != 0:
m.mul(p_norm / g_norm)
m.add(p - p/p_norm, alpha=self.Lambda)
if self.momentum:
p.m.mul(self.momentum_beta).add_(m, alpha=1-self.momentum_beta)
m = p.m
p.add(m, alpha=-alpha)
p.grad = None
ag.register_hook(gf)
To improve the Fusedbun optimizer by incorporating some ideas from the Adalite code, consider the following enhancements:
1. Centralize Gradient: Already implemented in Fusedbun, but it’s good to ensure it aligns with Adalite’s approach for consistency.
2. Gradient Clipping (RMS): This has been included, but to make it similar to Adalite, ensure to incorporate the logic where you divide the gradient by the max of 1.0 or the root-mean-square of the gradient, enhancing numerical stability.
3. Parameter Norm and Gradient Norm Ratio Scaling: This technique from Adalite can be particularly useful. It scales the normalized gradient by the ratio of parameter norm to gradient norm, which can help in maintaining the direction of the gradients while controlling their magnitude relative to the parameters’ magnitude.
4. Momentum with Condition: You already include momentum in Fusedbun. Adalite’s approach to conditionally apply momentum if enabled and then update the parameter with the momentum-adjusted gradient can be streamlined in your implementation.
5. Lambda for Weight Regularization: While Lambda is included in your defaults, its use is not explicitly seen in the step function. Adalite provides an explicit regularization term that decays the weights directly, acting similar to weight-decay but applied in a slightly different manner.
Below are modifications and incorporations from Adalite adapted to Fusedbun:
import torch
from torch.optim.optimizer import Optimizer
import math
class Fusedbun(Optimizer):
def init(self, params, lr=1e-3, eps=1e-8, beta_decay=0.8, Lambda=0.01, momentum_beta=0.9, centralize=True, use_rms=True):
defaults = dict(lr=lr, eps=eps, beta_decay=beta_decay, Lambda=Lambda, momentum_beta=momentum_beta, centralize=centralize, use_rms=use_rms)
super(Fusedbun, self).init(params, defaults)
@torch.no_grad()
def step(self, closure=None):
loss = None
if closure is not None:
loss = closure()
for group in self.param_groups:
lr = group[‘lr’]
eps = group[‘eps’]
beta_decay = group[‘beta_decay’]
Lambda = group[‘Lambda’]
momentum_beta = group[‘momentum_beta’]
centralize = group[‘centralize’]
use_rms = group[‘use_rms’]
for p in group[‘params’]:
if p.grad is None:
continue
grad = p.grad.data
if centralize and len(p.shape) > 1:
grad -= grad.mean(dim=tuple(range(1, len(grad.shape))), keepdim=True)
state = self.state[p]
if len(state) == 0:
state[‘step’] = 0
state[‘accumulator’] = torch.zeros_like(p.data)
if momentum_beta > 0:
state[‘momentum_buffer’] = torch.zeros_like(p.data)
acc = state[‘accumulator’]
t = state[‘step’] + 1
state[‘step’] = t
beta_t = 1.0 - math.pow(t, -beta_decay)
acc.mul_(beta_t).addcmul_(1-beta_t, grad, grad)
denom = acc.sqrt().add(eps)
grad_normalized = grad / denom if use_rms else grad
if use_rms:
grad_normalized /= max(1.0, grad_normalized.norm() / denom.norm())
if p.norm() != 0 and grad.norm() != 0:
grad_normalized *= p.norm() / grad.norm()
grad_normalized.add_(p, alpha=-Lambda) # Applying direct weight decay
if momentum_beta > 0:
momentum_buffer = state[‘momentum_buffer’]
momentum_buffer.mul_(momentum_beta).add_(grad_normalized, alpha=1-momentum_beta)
grad_normalized = momentum_buffer
p.data.add_(grad_normalized, alpha=-lr)
return loss
This integrates concepts from Adalite, focusing on incorporating momentum efficiently, applying RMS-based clipping if enabled, and scaling normalized gradients based on the parameter and gradient norms ratio. Further, it corrects the handling of Lambda for direct weight regularization. Adjustments like these can improve both the effectiveness and efficiency of the optimizer.
where have yu used lambda? also i dont want to use lambda implementation from adalite. i want to utilise it from some other optimiser. I want it to be a mix.
I see, if you’re looking to incorporate the parameter Lambda in a different way from how Adalite does and rather want to use it similarly to how other optimizers might apply a weight decay directly in the update step, let’s modify the approach. Specifically, we can treat Lambda as a weight decay parameter that directly scales down the weights before the gradient update, a common approach in various other optimizers like L2 regularization.
Here’s a revised version of the Fusedbun optimizer with Lambda being utilized as a direct weight decay factor in the update step. This approach is more aligned with traditional weight decay techniques seen in other optimizers:
import torch
from torch.optim.optimizer import Optimizer
import math
class Fusedbun(Optimizer):
def init(self, params, lr=1e-3, eps=1e-8, beta_decay=0.8, Lambda=0.01, momentum_beta=0.9, centralize=True, use_rms=True):
defaults = dict(lr=lr, eps=eps, beta_decay=beta_decay, Lambda=Lambda, momentum_beta=momentum_beta, centralize=centralize, use_rms=use_rms)
super(Fusedbun, self).init(params, defaults)
@torch.no_grad()
def step(self, closure=None):
loss = None
if closure is not None:
loss = closure()
for group in self.param_groups:
lr = group[‘lr’]
eps = group[‘eps’]
beta_decay = group[‘beta_decay’]
Lambda = group[‘Lambda’]
momentum_beta = group[‘momentum_beta’]
centralize = group[‘centralize’]
use_rms = group[‘use_rms’]
for p in group[‘params’]:
if p.grad is None:
continue
grad = p.grad.data
if centralize and len(p.shape) > 1:
grad -= grad.mean(dim=tuple(range(1, len(grad.shape))), keepdim=True)
state = self.state[p]
if len(state) == 0:
state[‘step’] = 0
state[‘accumulator’] = torch.zeros_like(p.data)
if momentum_beta > 0:
state[‘momentum_buffer’] = torch.zeros_like(p.data)
acc = state[‘accumulator’]
state[‘step’] += 1
t = state[‘step’]
beta_t = 1.0 - math.pow(t, -beta_decay)
acc.mul_(beta_t).addcmul_(grad, grad, value=1-beta_t)
denom = acc.sqrt().add_(eps)
grad_normalized = grad / denom if use_rms else grad
if momentum_beta > 0:
momentum_buffer = state[‘momentum_buffer’]
momentum_buffer.mul_(momentum_beta).add_(grad_normalized, alpha=1-momentum_beta)
grad_normalized = momentum_buffer
# Apply weight decay directly to weights
if Lambda != 0:
grad_normalized.add_(p.data, alpha=-Lambda)
p.data.add_(grad_normalized, alpha=-lr)
return loss
In this version, the Lambda parameter is utilized directly to perform a weight decay operation on parameters before updating them. This technique is more aligned with conventional weight decay methods, where parameters are directly scaled down by a factor before applying the gradient update. It is different from Adalite’s approach where Lambda was used in a somewhat different context. This should effectively bring the regularization aspect into your optimizer, making it a blend of features from different optimizers, as per your demand.
i dont think this is nice.
I understand your concern and appreciate your honesty. Let’s refine the approach further to ensure the Lambda parameter (acting as weight decay) is effectively utilized alongside the unique features you’re aiming to incorporate from diverse optimizers. We want to blend these efficiently without directly replicating any single optimizer’s approach to Lambda.
Weight decay, also known as L2 regularization, is commonly applied in optimization algorithms to prevent overfitting by penalizing large weights. The typical way to apply weight decay is to shrink the weights directly by a small factor during each update. Given your goal to innovate beyond the standard implementations, one idea could be to adaptively adjust the weight decay based on some criteria, inspired by how adaptive optimizers adjust their learning rates.
Here’s how you might adjust the usage of Lambda to offer a more nuanced approach:
1. Scale Lambda Based on Gradients: Instead of using a fixed Lambda for all parameters, you could adjust Lambda based on the gradients’ magnitudes. This way, parameters with larger gradients could potentially be regularized more heavily, countering the rapid changes they impose on the model.
2. Incorporate Lambda into State: Treat Lambda not as a static parameter but as something that evolves based on the optimization process, much like other stateful aspects of the optimizer like momentum or adaptive learning rates.
3. Utilize Lambda in Conjunction with Accumulated Gradients: Advanced optimizers keep track of past gradients in various ways (e.g., RMSprop, Adam). Lambda could be used to modulate the influence of these accumulated gradients, offering a pathway to dynamically adjust the step size based on both the history and the regularization strength.
Let’s sketch out how these ideas might be concretely implemented within your framework:
import torch
from torch.optim.optimizer import Optimizer
import math
class Fusedbun(Optimizer):
def init(self, params, lr=1e-3, eps=1e-8, beta_decay=0.8, Lambda=0.01, momentum_beta=0.9, centralize=True, use_rms=True):
defaults = dict(lr=lr, eps=eps, beta_decay=beta_decay, Lambda=Lambda, momentum_beta=momentum_beta, centralize=centralize, use_rms=use_rms)
super(Fusedbun, self).init(params, defaults)
@torch.no_grad()
def step(self, closure=None):
loss = None
if closure is not None:
loss = closure()
for group in self.param_groups:
lr = group[‘lr’]
eps = group[‘eps’]
beta_decay = group[‘beta_decay’]
base_lambda = group[‘Lambda’]
momentum_beta = group[‘momentum_beta’]
centralize = group[‘centralize’]
use_rms = group[‘use_rms’]
for p in group[‘params’]:
if p.grad is None:
continue
grad = p.grad.data
if centralize and len(p.shape) > 1:
grad -= grad.mean(dim=tuple(range(1, len(grad.shape))), keepdim=True)
state = self.state[p]
if ‘step’ not in state:
state[‘step’] = 0
state[‘accumulator’] = torch.zeros_like(p.data)
state[‘Lambda’] = base_lambda # Initialize adaptive Lambda in state
if momentum_beta > 0:
state[‘momentum_buffer’] = torch.zeros_like(p.data)
acc = state[‘accumulator’]
state[‘step’] += 1
t = state[‘step’]
beta_t = 1.0 - math.pow(t, -beta_decay)
acc.mul_(beta_t).addcmul_(grad, grad, value=1-beta_t)
denom = acc.sqrt().add_(eps)
grad_normalized = grad / denom if use_rms else grad
# Dynamic Lambda adjustment
adaptive_lambda = state[‘Lambda’] * grad.abs().mean()
if momentum_beta > 0:
momentum_buffer = state[‘momentum_buffer’]
momentum_buffer.mul_(momentum_beta).add_(grad_normalized, alpha=1-momentum_beta)
grad_normalized = momentum_buffer
# Apply adaptive weight decay based on modified Lambda
p.data.mul_(1 - lr * adaptive_lambda)
p.data.add_(grad_normalized, alpha=-lr)
return loss
In this version, Lambda is initially treated as a base value that gets adapted based on the mean absolute value of the gradients, theoretically allowing for weight decay that’s responsive to the optimization process’s dynamics. This approach is speculative and intended to inspire ways to innovate within the constraints of optimizer design while remaining grounded in principles that ensure generalization and training stability.
REvert changes. This will be used to finetune large language models. Consider that and either remove it or use SM3 and adalite to fix it
Understood. Given the focus on fine-tuning large language models and the inspiration from both SM3 and Adalite, let’s tailor the optimizer to fit this specific use case more appropriately. We assume high efficiency and memory optimization are key due to the large parameter space of such models. Additionally, the importance of managing the balance between exploration (via momentum) and exploitation (via adaptive learning rates and weight decay) must be considered.
Here’s how we can revise the Fusedbun optimizer by carefully incorporating ideas from SM3 and Adalite, without the previously mentioned dynamic Lambda approach, to ensure it’s more suited for fine-tuning large language models:
1. Memory Efficiency: We’ll ensure that our state variables (like accumulators and momentum buffers) are as memory-efficient as possible, drawing inspiration from SM3.
2. Adaptive Learning with Momentum: We’ll keep the momentum logic for exploratory updates but ensure that the adaptive learning mechanism from something akin to Adalite’s handling (or RMSprop/Adam) is well integrated.
3. Weight Decay: Given the context now focuses on fine-tuning large models, and considering your feedback, we will retain a simple, predictable form of weight decay, aligning it more closely to standard practices.
4. Ensure the Lambda parameter efficiently applies a consistent form of weight decay suitable for large models, avoiding dynamic adjustments for simplicity and predictability.
Considering these aspects, let’s refine the optimizer:
import torch
from torch.optim.optimizer import Optimizer
import math
class Fusedbun(Optimizer):
def init(self, params, lr=1e-3, eps=1e-8, beta_decay=0.8, Lambda=0.01, momentum_beta=0.9, centralize=False, use_rms=True):
defaults = dict(lr=lr, eps=eps, beta_decay=beta_decay, Lambda=Lambda, momentum_beta=momentum_beta, centralize=centralize, use_rms=use_rms)
super(Fusedbun, self).init(params, defaults)
@torch.no_grad()
def step(self, closure=None):
loss = None
if closure is not None:
with torch.enable_grad():
loss = closure()
for group in self.param_groups:
lr = group[‘lr’]
eps = group[‘eps’]
Lambda = group[‘Lambda’]
momentum_beta = group[‘momentum_beta’]
use_rms = group[‘use_rms’]
for p in group[‘params’]:
if p.grad is None:
continue
grad = p.grad.data
if group[‘centralize’] and len(p.shape) > 1:
grad = grad - grad.mean(dim=tuple(range(1, len(grad.shape))), keepdim=True)
state = self.state[p]
# State initialization
if len(state) == 0:
state[‘step’] = 0
state[‘exp_avg_sq’] = torch.zeros_like(p, memory_format=torch.preserve_format)
if momentum_beta > 0:
state[‘momentum_buffer’] = torch.zeros_like(p, memory_format=torch.preserve_format)
exp_avg_sq = state[‘exp_avg_sq’]
state[‘step’] += 1
beta_decay = 1.0 - math.pow(state[‘step’], -group[‘beta_decay’])
# SM3-like sparse update for memory efficiency
if p.dim() > 1:
dim = grad.square().mean().item()
exp_avg_sq.add_(dim - exp_avg_sq, alpha=beta_decay)
else:
exp_avg_sq.mul_(beta_decay).addcmul_(grad, grad, value=1 - beta_decay)
denom = exp_avg_sq.sqrt().add_(eps)
if momentum_beta > 0:
momentum_buffer = state[‘momentum_buffer’]
momentum_buffer.mul_(momentum_beta).addcdiv_(grad, denom, value=1 - momentum_beta)
step_size = -lr * momentum_buffer
else:
step_size = -lr * grad / denom
# Applying weight decay (if Lambda is not 0
|
c82d5283d5b59ae112c0b9b4ec366075
|
{
"intermediate": 0.2871105968952179,
"beginner": 0.46344193816185,
"expert": 0.2494475096464157
}
|
43,061
|
make necessary changes to the code using infor from the following:
Based on following complete the latest code:
Ok lambda here is not doing anything.
import torch
from torch.optim.optimizer import Optimizer
import math
class Fusedbun(Optimizer):
def init(self, params, lr=1e-3, eps=1e-8, beta_decay=0.8, Lambda=0.01, momentum_beta=0.9, centralize=True, use_rms=True):
defaults = dict(lr=lr, eps=eps, beta_decay=beta_decay, Lambda=Lambda, momentum_beta=momentum_beta, centralize=centralize, use_rms=use_rms)
super(Fusedbun, self).init(params, defaults)
@torch.no_grad()
def step(self, closure=None):
loss = None
if closure is not None:
loss = closure()
for group in self.param_groups:
lr = group[‘lr’]
eps = group[‘eps’]
beta_decay = group[‘beta_decay’]
Lambda = group[‘Lambda’]
momentum_beta = group[‘momentum_beta’]
centralize = group[‘centralize’]
use_rms = group[‘use_rms’]
for p in group[‘params’]:
if p.grad is None:
continue
grad = p.grad.data
if centralize and len(p.shape) > 1:
grad = grad.sub(grad.mean(dim=tuple(range(1, len(grad.shape))), keepdim=True))
state = self.state[p]
if len(state) == 0:
state[‘step’] = 0
state[‘accumulator’] = torch.zeros_like(p.data)
if momentum_beta > 0:
state[‘momentum_buffer’] = torch.zeros_like(p.data)
acc = state[‘accumulator’]
t = state[‘step’] + 1
state[‘step’] = t
if p.dim() > 1:
grad_squared = grad.square().mean(dim=0)
else:
grad_squared = grad.square()
beta_t = 1.0 - math.pow(t, -beta_decay)
acc.mul_(beta_t).add_(grad_squared, alpha=1-beta_t)
denom = acc.sqrt().add(eps)
grad_normalized = grad / denom if use_rms else grad
if momentum_beta > 0:
momentum_buffer = state[‘momentum_buffer’]
momentum_buffer.mul_(momentum_beta).add_(grad_normalized, alpha=1-momentum_beta)
grad_normalized = momentum_buffer
p.data.add_(grad_normalized, alpha=-lr)
return loss
Make it better. Im making optimiser both memory efficient and better than others out there. I have taken inpiration from SM3 and Adalite. You must know SM3, im giving you adalite code. Make necessary changes.
import torch
import math
from dataclasses import dataclass, field
from typing import List, Optional
from collections import defaultdict
# Somewhat based on https://gist.github.com/albanD/18c240bd2e09f9d93f5c4a0c9ccda39e and LOMO
@dataclass
class OverlapOptimizer:
model: torch.nn.Module
lr: Optional[float] = None
decay: Optional[float] = 0.0
acc_grads: Optional[List] = field(default_factory=lambda: [])
def init(self):
for p in self.model.parameters():
if p.requires_grad:
self.prepare§
self.hook§
def step(self, loss, lr):
pass
def hook(self, p):
pass
@dataclass
class OverlapSGD(OverlapOptimizer):
sign: bool = False
def prepare(self, p):
return
def step(self, loss, lr):
self.lr = lr
loss.backward()
def hook(self, p):
ag = p.view_as§.grad_fn.next_functions[0][0]
p.acc_grads = [ag]
@torch.no_grad()
def gf():
if self.sign:
p.add(p.grad.sign(), alpha=-self.lr)
else:
p.add_(p.grad, alpha=-self.lr)
p.grad = None
ag.register_hook(gf)
@dataclass
class Adalite(OverlapOptimizer):
eps: float = 1e-5
Lambda: float = 0.01 # Akin to weight-decay
beta_decay: float = 0.8
centralize: bool = True
use_rms: bool = True
momentum: bool = False
momentum_beta: float = 0.9
t: int = 0
def step(self, loss, lr=None):
self.t += 1
self.lr = lr
loss.backward()
def prepare(self, p):
if len(p.shape) == 2:
p.c = torch.zeros(p.shape[1], device=p.device, dtype=p.dtype)
else:
p.v = torch.zeros_like§
if self.momentum:
p.m = torch.zeros_like§
def hook(self, p):
ag = p.view_as§.grad_fn.next_functions[0][0]
p.acc_grads = [ag]
@torch.no_grad()
def gf():
alpha = self.lr
g = p.grad
if self.centralize and sum(g.shape) > 1:
g.sub(g.mean(dim=tuple(range(1, len(g.shape))), keepdim=True))
beta_t = 1.0 - math.pow(self.t, -self.beta_decay)
u = g.square()
if len(p.shape) == 2:
u.mul(1-beta_t).add(p.c.unsqueeze(0).broadcast_to(g.shape), alpha=beta_t)
u.add(self.eps)
p.c = u.mean(dim=0)
else:
u.mul(1-beta_t).add(p.v, alpha=beta_t)
u.add(self.eps)
p.v = u
m = u.rsqrt() * g
if self.use_rms:
m.div(max(1.0, m.square().mean().sqrt()))
p_norm = p.norm()
g_norm = g.norm()
if p_norm != 0 and g_norm != 0:
m.mul(p_norm / g_norm)
m.add(p - p/p_norm, alpha=self.Lambda)
if self.momentum:
p.m.mul(self.momentum_beta).add_(m, alpha=1-self.momentum_beta)
m = p.m
p.add(m, alpha=-alpha)
p.grad = None
ag.register_hook(gf)
To improve the Fusedbun optimizer by incorporating some ideas from the Adalite code, consider the following enhancements:
1. Centralize Gradient: Already implemented in Fusedbun, but it’s good to ensure it aligns with Adalite’s approach for consistency.
2. Gradient Clipping (RMS): This has been included, but to make it similar to Adalite, ensure to incorporate the logic where you divide the gradient by the max of 1.0 or the root-mean-square of the gradient, enhancing numerical stability.
3. Parameter Norm and Gradient Norm Ratio Scaling: This technique from Adalite can be particularly useful. It scales the normalized gradient by the ratio of parameter norm to gradient norm, which can help in maintaining the direction of the gradients while controlling their magnitude relative to the parameters’ magnitude.
4. Momentum with Condition: You already include momentum in Fusedbun. Adalite’s approach to conditionally apply momentum if enabled and then update the parameter with the momentum-adjusted gradient can be streamlined in your implementation.
5. Lambda for Weight Regularization: While Lambda is included in your defaults, its use is not explicitly seen in the step function. Adalite provides an explicit regularization term that decays the weights directly, acting similar to weight-decay but applied in a slightly different manner.
Below are modifications and incorporations from Adalite adapted to Fusedbun:
import torch
from torch.optim.optimizer import Optimizer
import math
class Fusedbun(Optimizer):
def init(self, params, lr=1e-3, eps=1e-8, beta_decay=0.8, Lambda=0.01, momentum_beta=0.9, centralize=True, use_rms=True):
defaults = dict(lr=lr, eps=eps, beta_decay=beta_decay, Lambda=Lambda, momentum_beta=momentum_beta, centralize=centralize, use_rms=use_rms)
super(Fusedbun, self).init(params, defaults)
@torch.no_grad()
def step(self, closure=None):
loss = None
if closure is not None:
loss = closure()
for group in self.param_groups:
lr = group[‘lr’]
eps = group[‘eps’]
beta_decay = group[‘beta_decay’]
Lambda = group[‘Lambda’]
momentum_beta = group[‘momentum_beta’]
centralize = group[‘centralize’]
use_rms = group[‘use_rms’]
for p in group[‘params’]:
if p.grad is None:
continue
grad = p.grad.data
if centralize and len(p.shape) > 1:
grad -= grad.mean(dim=tuple(range(1, len(grad.shape))), keepdim=True)
state = self.state[p]
if len(state) == 0:
state[‘step’] = 0
state[‘accumulator’] = torch.zeros_like(p.data)
if momentum_beta > 0:
state[‘momentum_buffer’] = torch.zeros_like(p.data)
acc = state[‘accumulator’]
t = state[‘step’] + 1
state[‘step’] = t
beta_t = 1.0 - math.pow(t, -beta_decay)
acc.mul_(beta_t).addcmul_(1-beta_t, grad, grad)
denom = acc.sqrt().add(eps)
grad_normalized = grad / denom if use_rms else grad
if use_rms:
grad_normalized /= max(1.0, grad_normalized.norm() / denom.norm())
if p.norm() != 0 and grad.norm() != 0:
grad_normalized *= p.norm() / grad.norm()
grad_normalized.add_(p, alpha=-Lambda) # Applying direct weight decay
if momentum_beta > 0:
momentum_buffer = state[‘momentum_buffer’]
momentum_buffer.mul_(momentum_beta).add_(grad_normalized, alpha=1-momentum_beta)
grad_normalized = momentum_buffer
p.data.add_(grad_normalized, alpha=-lr)
return loss
This integrates concepts from Adalite, focusing on incorporating momentum efficiently, applying RMS-based clipping if enabled, and scaling normalized gradients based on the parameter and gradient norms ratio. Further, it corrects the handling of Lambda for direct weight regularization. Adjustments like these can improve both the effectiveness and efficiency of the optimizer.
where have yu used lambda? also i dont want to use lambda implementation from adalite. i want to utilise it from some other optimiser. I want it to be a mix.
I see, if you’re looking to incorporate the parameter Lambda in a different way from how Adalite does and rather want to use it similarly to how other optimizers might apply a weight decay directly in the update step, let’s modify the approach. Specifically, we can treat Lambda as a weight decay parameter that directly scales down the weights before the gradient update, a common approach in various other optimizers like L2 regularization.
Here’s a revised version of the Fusedbun optimizer with Lambda being utilized as a direct weight decay factor in the update step. This approach is more aligned with traditional weight decay techniques seen in other optimizers:
import torch
from torch.optim.optimizer import Optimizer
import math
class Fusedbun(Optimizer):
def init(self, params, lr=1e-3, eps=1e-8, beta_decay=0.8, Lambda=0.01, momentum_beta=0.9, centralize=True, use_rms=True):
defaults = dict(lr=lr, eps=eps, beta_decay=beta_decay, Lambda=Lambda, momentum_beta=momentum_beta, centralize=centralize, use_rms=use_rms)
super(Fusedbun, self).init(params, defaults)
@torch.no_grad()
def step(self, closure=None):
loss = None
if closure is not None:
loss = closure()
for group in self.param_groups:
lr = group[‘lr’]
eps = group[‘eps’]
beta_decay = group[‘beta_decay’]
Lambda = group[‘Lambda’]
momentum_beta = group[‘momentum_beta’]
centralize = group[‘centralize’]
use_rms = group[‘use_rms’]
for p in group[‘params’]:
if p.grad is None:
continue
grad = p.grad.data
if centralize and len(p.shape) > 1:
grad -= grad.mean(dim=tuple(range(1, len(grad.shape))), keepdim=True)
state = self.state[p]
if len(state) == 0:
state[‘step’] = 0
state[‘accumulator’] = torch.zeros_like(p.data)
if momentum_beta > 0:
state[‘momentum_buffer’] = torch.zeros_like(p.data)
acc = state[‘accumulator’]
state[‘step’] += 1
t = state[‘step’]
beta_t = 1.0 - math.pow(t, -beta_decay)
acc.mul_(beta_t).addcmul_(grad, grad, value=1-beta_t)
denom = acc.sqrt().add_(eps)
grad_normalized = grad / denom if use_rms else grad
if momentum_beta > 0:
momentum_buffer = state[‘momentum_buffer’]
momentum_buffer.mul_(momentum_beta).add_(grad_normalized, alpha=1-momentum_beta)
grad_normalized = momentum_buffer
# Apply weight decay directly to weights
if Lambda != 0:
grad_normalized.add_(p.data, alpha=-Lambda)
p.data.add_(grad_normalized, alpha=-lr)
return loss
In this version, the Lambda parameter is utilized directly to perform a weight decay operation on parameters before updating them. This technique is more aligned with conventional weight decay methods, where parameters are directly scaled down by a factor before applying the gradient update. It is different from Adalite’s approach where Lambda was used in a somewhat different context. This should effectively bring the regularization aspect into your optimizer, making it a blend of features from different optimizers, as per your demand.
i dont think this is nice.
I understand your concern and appreciate your honesty. Let’s refine the approach further to ensure the Lambda parameter (acting as weight decay) is effectively utilized alongside the unique features you’re aiming to incorporate from diverse optimizers. We want to blend these efficiently without directly replicating any single optimizer’s approach to Lambda.
Weight decay, also known as L2 regularization, is commonly applied in optimization algorithms to prevent overfitting by penalizing large weights. The typical way to apply weight decay is to shrink the weights directly by a small factor during each update. Given your goal to innovate beyond the standard implementations, one idea could be to adaptively adjust the weight decay based on some criteria, inspired by how adaptive optimizers adjust their learning rates.
Here’s how you might adjust the usage of Lambda to offer a more nuanced approach:
1. Scale Lambda Based on Gradients: Instead of using a fixed Lambda for all parameters, you could adjust Lambda based on the gradients’ magnitudes. This way, parameters with larger gradients could potentially be regularized more heavily, countering the rapid changes they impose on the model.
2. Incorporate Lambda into State: Treat Lambda not as a static parameter but as something that evolves based on the optimization process, much like other stateful aspects of the optimizer like momentum or adaptive learning rates.
3. Utilize Lambda in Conjunction with Accumulated Gradients: Advanced optimizers keep track of past gradients in various ways (e.g., RMSprop, Adam). Lambda could be used to modulate the influence of these accumulated gradients, offering a pathway to dynamically adjust the step size based on both the history and the regularization strength.
Let’s sketch out how these ideas might be concretely implemented within your framework:
import torch
from torch.optim.optimizer import Optimizer
import math
class Fusedbun(Optimizer):
def init(self, params, lr=1e-3, eps=1e-8, beta_decay=0.8, Lambda=0.01, momentum_beta=0.9, centralize=True, use_rms=True):
defaults = dict(lr=lr, eps=eps, beta_decay=beta_decay, Lambda=Lambda, momentum_beta=momentum_beta, centralize=centralize, use_rms=use_rms)
super(Fusedbun, self).init(params, defaults)
@torch.no_grad()
def step(self, closure=None):
loss = None
if closure is not None:
loss = closure()
for group in self.param_groups:
lr = group[‘lr’]
eps = group[‘eps’]
beta_decay = group[‘beta_decay’]
base_lambda = group[‘Lambda’]
momentum_beta = group[‘momentum_beta’]
centralize = group[‘centralize’]
use_rms = group[‘use_rms’]
for p in group[‘params’]:
if p.grad is None:
continue
grad = p.grad.data
if centralize and len(p.shape) > 1:
grad -= grad.mean(dim=tuple(range(1, len(grad.shape))), keepdim=True)
state = self.state[p]
if ‘step’ not in state:
state[‘step’] = 0
state[‘accumulator’] = torch.zeros_like(p.data)
state[‘Lambda’] = base_lambda # Initialize adaptive Lambda in state
if momentum_beta > 0:
state[‘momentum_buffer’] = torch.zeros_like(p.data)
acc = state[‘accumulator’]
state[‘step’] += 1
t = state[‘step’]
beta_t = 1.0 - math.pow(t, -beta_decay)
acc.mul_(beta_t).addcmul_(grad, grad, value=1-beta_t)
denom = acc.sqrt().add_(eps)
grad_normalized = grad / denom if use_rms else grad
# Dynamic Lambda adjustment
adaptive_lambda = state[‘Lambda’] * grad.abs().mean()
if momentum_beta > 0:
momentum_buffer = state[‘momentum_buffer’]
momentum_buffer.mul_(momentum_beta).add_(grad_normalized, alpha=1-momentum_beta)
grad_normalized = momentum_buffer
# Apply adaptive weight decay based on modified Lambda
p.data.mul_(1 - lr * adaptive_lambda)
p.data.add_(grad_normalized, alpha=-lr)
return loss
In this version, Lambda is initially treated as a base value that gets adapted based on the mean absolute value of the gradients, theoretically allowing for weight decay that’s responsive to the optimization process’s dynamics. This approach is speculative and intended to inspire ways to innovate within the constraints of optimizer design while remaining grounded in principles that ensure generalization and training stability.
REvert changes. This will be used to finetune large language models. Consider that and either remove it or use SM3 and adalite to fix it
Understood. Given the focus on fine-tuning large language models and the inspiration from both SM3 and Adalite, let’s tailor the optimizer to fit this specific use case more appropriately. We assume high efficiency and memory optimization are key due to the large parameter space of such models. Additionally, the importance of managing the balance between exploration (via momentum) and exploitation (via adaptive learning rates and weight decay) must be considered.
Here’s how we can revise the Fusedbun optimizer by carefully incorporating ideas from SM3 and Adalite, without the previously mentioned dynamic Lambda approach, to ensure it’s more suited for fine-tuning large language models:
1. Memory Efficiency: We’ll ensure that our state variables (like accumulators and momentum buffers) are as memory-efficient as possible, drawing inspiration from SM3.
2. Adaptive Learning with Momentum: We’ll keep the momentum logic for exploratory updates but ensure that the adaptive learning mechanism from something akin to Adalite’s handling (or RMSprop/Adam) is well integrated.
3. Weight Decay: Given the context now focuses on fine-tuning large models, and considering your feedback, we will retain a simple, predictable form of weight decay, aligning it more closely to standard practices.
4. Ensure the Lambda parameter efficiently applies a consistent form of weight decay suitable for large models, avoiding dynamic adjustments for simplicity and predictability.
Considering these aspects, let’s refine the optimizer:
import torch
from torch.optim.optimizer import Optimizer
import math
class Fusedbun(Optimizer):
def init(self, params, lr=1e-3, eps=1e-8, beta_decay=0.8, Lambda=0.01, momentum_beta=0.9, centralize=False, use_rms=True):
defaults = dict(lr=lr, eps=eps, beta_decay=beta_decay, Lambda=Lambda, momentum_beta=momentum_beta, centralize=centralize, use_rms=use_rms)
super(Fusedbun, self).init(params, defaults)
@torch.no_grad()
def step(self, closure=None):
loss = None
if closure is not None:
with torch.enable_grad():
loss = closure()
for group in self.param_groups:
lr = group[‘lr’]
eps = group[‘eps’]
Lambda = group[‘Lambda’]
momentum_beta = group[‘momentum_beta’]
use_rms = group[‘use_rms’]
for p in group[‘params’]:
if p.grad is None:
continue
grad = p.grad.data
if group[‘centralize’] and len(p.shape) > 1:
grad = grad - grad.mean(dim=tuple(range(1, len(grad.shape))), keepdim=True)
state = self.state[p]
# State initialization
if len(state) == 0:
state[‘step’] = 0
state[‘exp_avg_sq’] = torch.zeros_like(p, memory_format=torch.preserve_format)
if momentum_beta > 0:
state[‘momentum_buffer’] = torch.zeros_like(p, memory_format=torch.preserve_format)
exp_avg_sq = state[‘exp_avg_sq’]
state[‘step’] += 1
beta_decay = 1.0 - math.pow(state[‘step’], -group[‘beta_decay’])
# SM3-like sparse update for memory efficiency
if p.dim() > 1:
dim = grad.square().mean().item()
exp_avg_sq.add_(dim - exp_avg_sq, alpha=beta_decay)
else:
exp_avg_sq.mul_(beta_decay).addcmul_(grad, grad, value=1 - beta_decay)
denom = exp_avg_sq.sqrt().add_(eps)
if momentum_beta > 0:
momentum_buffer = state[‘momentum_buffer’]
momentum_buffer.mul_(momentum_beta).addcdiv_(grad, denom, value=1 - momentum_beta)
step_size = -lr * momentum_buffer
else:
step_size = -lr * grad / denom
# Applying weight decay (if Lambda is not 0
Lambda directly before the parameter update step to ensure it works similarly across various optimizers, let’s make the adjustment where Lambda is used for a straightforward weight decay effect. Considering the focus on large language models where stability and predictability can be crucial, a more conservative application of Lambda—directly scaling down weights by a minimal factor—makes more sense:
import torch
from torch.optim.optimizer import Optimizer
import math
class Fusedbun(Optimizer):
def init(self, params, lr=1e-3, eps=1e-8, beta_decay=0.8, Lambda=0.01, momentum_beta=0.9, centralize=False, use_rms=True):
defaults = dict(lr=lr, eps=eps, beta_decay=beta_decay, Lambda=Lambda, momentum_beta=momentum_beta, centralize=centralize, use_rms=use_rms)
super(Fusedbun, self).init(params, defaults)
@torch.no_grad()
def step(self, closure=None):
loss = None
if closure is not None:
with torch.enable_grad():
loss = closure()
for group in self.param_groups:
lr = group[‘lr’]
eps = group[‘eps’]
Lambda = group[‘Lambda’]
momentum_beta = group[‘momentum_beta’]
use_rms = group[‘use_rms’]
for p in group[‘params’]:
if p.grad is None:
continue
grad = p.grad.data
if group[‘centralize’] and len(p.shape) > 1:
grad = grad - grad.mean(dim=tuple(range(1, len(grad.shape))), keepdim=True)
state = self.state[p]
# State initialization
if len(state) == 0:
state[‘step’] = 0
state[‘exp_avg_sq’] = torch.zeros_like(p, memory_format=torch.preserve_format)
if momentum_beta > 0:
state[‘momentum_buffer’] = torch.zeros_like(p, memory_format=torch.preserve_format)
exp_avg_sq = state[‘exp_avg_sq’]
state[‘step’] += 1
beta_decay = 1.0 - math.pow(state[‘step’], -group[‘beta_decay’])
# Efficient squared gradient accumulation
exp_avg_sq.mul_(beta_decay).addcmul_(grad, grad, value=1 - beta_decay)
denom = exp_avg_sq.sqrt().add_(eps)
if momentum_beta > 0:
momentum_buffer = state[‘momentum_buffer’]
momentum_buffer.mul_(momentum_beta).addcdiv_(grad, denom, value=1 - momentum_beta)
step_size = -lr * momentum_buffer
else:
step_size = -lr * grad / denom
# Applying weight decay (if Lambda is not 0)
if Lambda != 0:
p.data.mul_(1 - lr * Lambda)
p.data.add_(step_size)
return loss
This final iteration takes into account:
- Lambda for Weight Decay: Consistently applies Lambda as a factor for weight decay, scaling down weights directly before the update. This straightforward approach is effective for managing model complexity and preventing overfitting, especially relevant in fine-tuning scenarios where preserving the pre-trained features is important.
- Memory Efficiency: By only storing necessary state variables without introducing complex, dynamic Lambda adjustments, it remains memory-efficient, crucial for handling large models.
- Adaptive Learning and Momentum: Balances the benefits of adaptive learning rates with momentum, ensuring that updates are both exploratory and grounded in recent gradients, tailored for effective fine-tuning.
This design considers the critical elements of fine-tuning large language models, balancing efficiency, and effectiveness without overcomplicating the weight decay mechanism.
Ok compare to SM3, adalite and other optimizers, tell me what benefits this have, if any? also tell me what are the current changes compared to originakl
Comparing the proposed Fusedbun optimizer with established optimizers like SM3 and Adalite, along with other common optimizers such as SGD, Adam, etc., here are some potential benefits and changes from the original implementation you provided and how it stands against others:
### Fusedbun vs. SM3
- Memory Efficiency: SM3 is designed for memory efficiency, particularly useful for sparse data. Fusedbun, while not explicitly designed like SM3 for sparse updates, incorporates adaptive gradient accumulation (akin to RMSprop or Adam) that can be applied more generally to different types of data (sparse or dense). The efficiency in Fusedbun comes from carefully managing state variables to avoid unnecessary memory usage.
- Adaptivity: Fusedbun employs adaptive mechanisms similar to those in Adam or RMSprop, providing potential benefits over SM3 when dealing with dense data and complex optimization landscapes by adjusting learning rates based on the magnitude of recent gradients.
### Fusedbun vs. Adalite
- Centralization and Weight Decay: Both optimizers can centralize gradients and apply weight decay, but Fusedbun takes a slightly different approach by incorporating these functionalities directly within the optimizer’s step function, making it easier to modify or extend these behaviors.
- Adaptive Weight Decay: While not originally exploited in your modifications, Fusedbun had the potential for dynamically adjusting Lambda based on gradient magnitudes, offering flexibility in regularizing parameters more aggressively where gradients are larger. However, based on your feedback, this was simplified to use a straightforward weight decay approach for stability in fine-tuning large models.
### General Benefits
- Flexibility: Fusedbun is designed with flexibility in mind, incorporating features like gradient centralization and RMS-based gradient clipping directly into the optimizer. This makes it inherently more adaptable to various types of models and training scenarios, especially when fine-tuning where subtle adjustments to the optimization process can have significant impacts.
- Simplicity and Predictability: By reverting to a more stable and predictable form of weight decay, Fusedbun offers a balance between innovation and the proven reliability of traditional techniques, making it potentially more suitable for fine-tuning large pre-trained models where maintaining pre-learned representations is crucial.
### Changes from the Original
- Removal of Dynamic Lambda Adjustment: Initially considered dynamic Lambda adjustments for an innovative approach to weight decay, this was removed for simplicity and predictability, aligning more closely with established practices beneficial for fine-tuning scenarios.
- Streamlined State Management: Streamlining how state variables are initialized and managed within Fusedbun improves clarity and efficiency, ensuring the optimizer’s memory footprint remains controlled, which is crucial when working with large models.
- Incorporation of Gradient Centralization and RMS-based Clipping: These features were adjusted or highlighted to emphasize their roles in the optimizer’s functionality, ensuring that their integration supports the optimizer’s efficiency and efficacy in fine-tuning tasks.
In summary, Fusedbun attempts to blend desirable features from various optimizers into a singular, flexible framework that could offer particular advantages in fine-tuning large language models. Its design prioritizes adaptability, efficiency, and the balance between innovation and proven optimization strategies, aiming to provide a robust tool for specific tasks rather than a universally superior optimizer.
REwrite the code with detailed comments of what each section do.
Below is the revised code for the Fusedbun optimizer with detailed comments explaining each section of the code. This version aims for clarity and understanding of how each part contributes to the overall optimization process, making it suitable for fine-tuning large models while balancing flexibility, efficiency, and simplicity.
import torch
from torch.optim.optimizer import Optimizer
import math
class Fusedbun(Optimizer):
def init(self, params, lr=1e-3, eps=1e-8, beta_decay=0.8, Lambda=0.01, momentum_beta=0.9, centralize=False, use_rms=True):
# Initialize optimizer parameters:
# lr: Learning rate controls the step size at each iteration.
# eps: A small value added to the denominator for numerical stability.
# beta_decay: A parameter controlling the rate of decay for the moving average of squared gradients.
# Lambda: Coefficient for L2 regularization (weight decay).
# momentum_beta: Coefficient for the moving average of gradients (momentum).
# centralize: Boolean indicating whether to centralize gradients to have zero mean.
# use_rms: Boolean indicating whether to use RMSprop-like denominator normalization.
defaults = dict(lr=lr, eps=eps, beta_decay=beta_decay, Lambda=Lambda, momentum_beta=momentum_beta, centralize=centralize, use_rms=use_rms)
super(Fusedbun, self).init(params, defaults)
@torch.no_grad() # This context manager disables gradient computation, reduces memory consumption and computation.
def step(self, closure=None):
# Performs a single optimization step (parameter update).
loss = None
if closure is not None:
# If a closure is provided, compute the loss. Useful for some optimization strategies.
with torch.enable_grad():
loss = closure()
for group in self.param_groups:
# Iterate over optimization parameter groups (allows for different params to have different hyperparams).
lr = group[‘lr’]
eps = group[‘eps’]
Lambda = group[‘Lambda’]
momentum_beta = group[‘momentum_beta’]
use_rms = group[‘use_rms’]
for p in group[‘params’]:
# Iterate over each parameter in the parameter group.
if p.grad is None:
continue # Skip parameters without gradients.
grad = p.grad.data
if group[‘centralize’] and len(p.shape) > 1:
# Centralize gradients for non-scalar parameters if centralization is enabled.
grad = grad - grad.mean(dim=tuple(range(1, len(grad.shape))), keepdim=True)
# Retrieve or initialize state for this parameter.
state = self.state[p]
# State initialization for the first step.
if len(state) == 0:
state[‘step’] = 0
state[‘exp_avg_sq’] = torch.zeros_like(p, memory_format=torch.preserve_format)
if momentum_beta > 0:
# Only allocate momentum buffer if momentum is used.
state[‘momentum_buffer’] = torch.zeros_like(p, memory_format=torch.preserve_format)
exp_avg_sq = state[‘exp_avg_sq’]
# Increment optimization step counter.
state[‘step’] += 1
# Adjust beta_decay dynamically based on step number if needed.
beta_decay = 1.0 - math.pow(state[‘step’], -group[‘beta_decay’])
# Update exponential average of squared gradients.
exp_avg_sq.mul_(beta_decay).addcmul_(grad, grad, value=1 - beta_decay)
denom = exp_avg_sq.sqrt().add_(eps)
if momentum_beta > 0:
# Momentum update if momentum is enabled.
momentum_buffer = state[‘momentum_buffer’]
momentum_buffer.mul_(momentum_beta).addcdiv_(grad, denom, value=1 - momentum_beta)
step_size = -lr * momentum_buffer
else:
# No momentum; use the normalized gradient for the update.
step_size = -lr * grad / denom
# Apply L2 regularization (weight decay) if Lambda is not zero.
if Lambda != 0:
p.data.mul_(1 - lr * Lambda)
# Apply the update to the parameter.
p.data.add_(step_size)
return loss
This detailed walkthrough explains the roles of various components within the Fusedbun optimizer. The optimizer supports functionalities like RMSprop-like adaptive learning rates, L2 regularization (weight decay), gradient centralization, and optional momentum, making it adaptable for a wide range of tasks, particularly in fine-tuning where such nuanced control over the optimization process can be crucial.
Why L2? isint it too old to use it with LLMs?
The question of whether L2 regularization (weight decay) is too old to use with large language models (LLMs) touches on a broader discussion about the relevance of traditional machine learning techniques in modern deep learning frameworks. While it’s true that L2 regularization is a long-standing technique, its usefulness and applicability extend to contemporary models, including LLMs, for several reasons:
1. Generalization: One of the primary reasons for using regularization techniques like L2 is to improve the generalization of a model to unseen data. L2 regularization achieves this by penalizing large weights, encouraging the model to maintain smaller weight values. This penalty helps prevent the model from fitting too closely to the training data (overfitting), which is a concern regardless of model size.
2. Simplicity and Effectiveness: Despite being a straightforward approach, L2 regularization remains effective for numerous tasks. It introduces an additional hyperparameter (the weight decay factor) that can be tuned to balance the trade-off between model complexity and training data fitness. This simplicity offers a clear path to mitigate overfitting without introducing significant computational overhead or complexity into the training process.
3. Complementary to Other Techniques: In the context of LLMs and deep learning in general, L2 regularization is often used alongside other techniques designed to improve model performance and generalization, such as dropout, batch normalization, and more complex regularization methods. This multi-pronged approach to regularization allows practitioners to leverage the strengths of various techniques to achieve better outcomes.
4. Theoretical and Practical Foundations: The use of L2 regularization is supported by both theoretical insights into the geometry of optimization landscapes and practical evidence from empirical experimentation. It helps in smoothing the optimization landscape, making it easier for gradient-based optimizers to find minima that generalize well.
5. Transfer Learning and Fine-tuning: In scenarios involving transfer learning and fine-tuning of pre-trained models, including LLMs, L2 regularization can be particularly useful. It helps in gently steering the fine-tuning process, limiting the extent to which weights can deviate from their pre-trained values. This is especially important when the fine-tuning dataset is much smaller than the pre-training corpus, as is often the case with LLMs.
While newer and more sophisticated regularization and optimization techniques have been developed, L2 regularization’s merits keep it relevant in the modern deep learning toolkit, including its application to LLMs. Its continued use is a testament to its fundamental utility in controlling model complexity and aiding generalization, rather than an indication of the field’s stagnation. That being said, the choice of regularization techniques should always be informed by the specific characteristics of the model, data, and task at hand, with an understanding that no single method is universally optimal.
OK not tell me what part of code was taken from which optimizer. Also write a blog about it. Telling me why we made this. how we made it(must include technical details of how it works) and what it is in conclusion
The Fusedbun optimizer, as conceived and developed in our discussion, is inspired by a blend of concepts from various leading optimizers, each bringing specific strengths to address the challenges of training large language models (LLMs). Below, I outline the components derived from these optimizers and then present a structured blog post discussing the rationale, development, and essence of Fusedbun.
### Inspirations from Existing Optimizers:
1. Momentum (SGD with Momentum): The momentum update mechanism in Fusedbun is inspired by classical SGD with momentum. It helps accelerate the optimizer in relevant directions and dampens oscillations.
2. Adaptive Gradient Accumulation (RMSprop/Adam): The use of squared gradients to adaptively adjust the learning rate for each parameter, similar to RMSprop and further popularized by Adam, aims to offer more nuanced step sizes that are informed by the recent history of gradients.
3. Weight Decay (L2 Regularization): Fusedbun incorporates simple weight decay directly into its update rule, a regularization strategy with roots in classical optimization techniques and adopted by various optimizers, including L2 regularization in SGD and the decoupled weight decay in optimizers like AdamW.
4. Gradient Centralization: This feature, which involves normalizing gradients to have zero mean, is inspired by more recent insights into deep learning optimization, particularly research into gradient centralization’s impact on stabilizing and speeding up training.
5. Epsilon for Numerical Stability (Adam): The inclusion of a small constant, epsilon, in the denominator of the update rule to prevent division by zero is a technique employed by Adam and similar optimizers to enhance numerical stability.
### Blog Post: Introducing Fusedbun - A Hybrid Optimizer for Large Language Models
#### Why We Made Fusedbun
In the fast-evolving landscape of deep learning, training large language models (LLMs) presents unique challenges. These models, characterized by their vast number of parameters and deep architectures, demand optimization strategies that balance speed, stability, and the capacity to navigate complex loss landscapes. Traditional optimizers, while foundational, often fall short in addressing these needs comprehensively.
Enter Fusedbun—a hybrid optimizer designed to harness the strengths of various optimization techniques. Our goal was to create an optimizer that adapts to the intricacies of large-scale models without sacrificing efficiency or requiring exhaustive hyperparameter tuning.
#### How We Made It: The Technical Essence
Fusedbun is rooted in a blend of tried-and-tested optimization principles, each selected for its proven benefits:
- Momentum: Borrowed from the classic SGD with momentum, this feature provides Fusedbun with the ability to sustain movement in productive directions across iterations, reducing the risk of stagnation in suboptimal regions.
- Adaptive Learning Rates: Drawing from RMSprop and Adam, Fusedbun adjusts the learning rate for each parameter based on the history of its gradients. This adaptiveness helps in scaling the updates appropriately, ensuring neither too large nor too small steps are taken.
- Weight Decay: Integrating direct weight decay into the update step imbues Fusedbun with a straightforward regularization mechanism, encouraging simpler models that are less prone to overfitting.
- Gradient Centralization: By centralizing gradients, Fusedbun aims to achieve faster convergence and improved stability, a technique shown to be beneficial in recent deep learning research.
- Numerical Stability: Like Adam, Fusedbun employs an epsilon term to maintain numerical stability, ensuring the model remains robust against potential computational anomalies.
Together, these components are woven into a cohesive optimization strategy tailored for the complexities of LLMs. The implementation ensures that while each parameter’s update is informed by its own gradient history and the model’s overall adjustment trajectory, regularization keeps the model grounded, preventing overfitting.
#### Conclusion: What Fusedbun Is
Fusedbun stands as a testament to the adaptive, nuanced approach required for modern deep learning challenges. It’s not just an optimizer; it’s a synthesis of learning from the lineage of optimization research, tailored for the demands of today’s LLMs. By integrating the strengths of multiple optimization philosophies, Fusedbun aspires to offer a balanced tool—capable of guiding large models to effective convergence with stability and efficiency.
In the ever-progressing quest to train more sophisticated models, Fusedbun represents a step towards acknowledging and amalgamating the richness of existing optimization strategies, paving the way for more informed and flexible approaches to learning at scale.
BUt earlier it was more like SM3 and adalite only
You’re right; in the earlier discussion, the Fusedbun optimizer was specifically mentioned to take inspiration from SM3 and Adalite, emphasizing a blend that prefers certain aspects from each. Let me correct the oversight and focus more precisely on how Fusedbun takes cues from these two and the unique aspects it inherits or adapts from them, culminating in a blog-style explanation.
### Inspiration from SM3 and Adalite:
SM3: This optimizer is known for its memory-efficient handling of the gradients, especially valuable for training models with vast parameter spaces. SM3’s key feature is its sparse update mechanism, which selectively updates parameters, significantly reducing memory requirements.
Adalite: While not a widely recognized optimizer in the mainstream like Adam or SGD, for the sake of our discussion, let’s assume Adalite brings innovative features such as adaptive learning rates based on parameter-wise gradient magnitudes and a nuanced approach to regularization and centralization.
### How Fusedbun Merges Concepts from SM3 and Adalite:
- Memory Efficiency from SM3: Fusedbun adopts a strategy to manage gradient accumulation and updates efficiently, minimizing the optimizer’s memory footprint. This aspect is crucial for scaling to large language models without overwhelming memory resources.
- Adaptive Learning Rates Inspired by Adalite: Like Adalite, Fusedbun utilizes adaptive learning rates that adjust according to the historical gradient information, but it streamlines this process to ensure robustness and stability across varied training scenarios.
- Centralization and Regularization: Borrowing from Adalite’s approach, Fusedbun includes gradient centralization for stability and enhanced convergence, coupled with a direct form of weight decay for straightforward regularization. This combination aims to balance the model’s training efficiency with its generalization capabilities.
### Blog Post: Crafting Fusedbun - A Synergistic Optimizer for Next-Gen Models
#### The Genesis of Fusedbun
In the quest to optimize large language models, the challenge has always been to marry the need for memory efficiency with the demand for adaptive, nuanced training strategies. Drawing from the strengths of SM3 and Adalite, Fusedbun was conceptualized as a hybrid optimizer that leverages the best of both worlds—offering a solution tailored for the complex needs of next-generation models.
#### The Mechanics Behind Fusedbun
Fusedbun’s architecture is a blend of carefully selected features aimed at addressing the core challenges in training large models:
- Efficient Memory Usage: Inspired by SM3, Fusedbun implements a memory-conscious approach to gradient accumulation, ensuring that large models can be trained on hardware with finite memory capabilities.
- Adaptive Learning: By integrating a variant of adaptive learning rate mechanisms, akin to those proposed in Adalite, Fusedbun allows for parameter updates that are sensitive to the magnitude and history of gradients, facilitating a more refined optimization process.
- Stability and Regularization: Fusedbun incorporates gradient centralization for improved training dynamics and employs straightforward weight decay as a form of L2 regularization, a nod to traditional techniques proven effective across various model sizes and complexities.
#### In Conclusion: Fusedbun’s Place in the Optimizer Pantheon
Fusedbun represents an innovative step in the evolution of optimization strategies for deep learning. By synergistically combining memory efficiency, adaptive learning, and proven regularization techniques, it offers a robust tool designed to meet the unique demands of training large language models. It stands as a bridge between the computational efficiency of SM3 and the adaptive finesse of Adalite, providing practitioners with an optimizer that does not compromise on efficiency or effectiveness.
As models continue to grow in size and complexity, Fusedbun aims to be at the forefront—empowering researchers and engineers to push the boundaries of what’s possible in machine learning and AI.
This focused exploration and subsequent explanation offer a clearer perspective on how Fusedbun is distinctively positioned, drawing foundational elements from SM3 and Adalite while striving to address the optimization challenges of contemporary large-scale models.
Revert changes if the changes that were made is outside SM3 and adalite. I only need mix of these two and not others.
Based on the requirement to strictly adhere to the inspirations from SM3 and Adalite, let’s refine the narrative around the development of Fusedbun, focusing exclusively on features and characteristics these two optimizers offer. We will eliminate references to features explicitly associated with other optimizers and ensure that Fusedbun is depicted as a direct hybrid of SM3 and Adalite, without external influences.
### Fusedbun: A Hybrid Optimizer Born from SM3 and Adalite
Fusedbun emerges as a specialized optimizer, uniquely architected for the demands of large language models (LLMs) by combining the strengths of SM3 and Adalite. Its creation is motivated by the need for an optimizer that marries the memory efficiency of SM3 with the adaptive learning strategies found in Adalite, without stepping into the territories of other popular optimizers like Adam or SGD.
#### Drawing from SM3
SM3’s hallmark is its memory efficiency, particularly advantageous for handling models with large numbers of parameters. Fusedbun inherits this trait by implementing a similar mechanism for gradient storage and update, focusing on minimizing memory overhead during training.
#### Incorporating Elements from Adalite
Adalite’s approach to adaptive learning rates—where adjustments are made based on the observed behavior of gradients—offers a path to nuanced parameter updates. Fusedbun adopts this approach, ensuring that each parameter’s learning rate is tuned according to its specific needs, promoting a balanced and effective optimization process.
### Development Journey of Fusedbun: A Technical Insight
The creation of Fusedbun involved careful integration of key features from SM3 and Adalite, ensuring each component harmonizes with the others to produce an optimizer that is more than the sum of its parts. The following technical decisions were pivotal:
- Memory-Efficient Gradient Handling: Drawing directly from SM3, Fusedbun optimizes its gradient storage and computation, ensuring it operates efficiently even when tasked with optimizing models having millions of parameters.
- Adaptive Learning Rate Mechanism: Fusedbun incorporates a learning rate adjustment mechanism inspired by Adalite, allowing it to dynamically modify learning rates based on the magnitude and variability of each parameter’s gradients over time.
- Gradient Centralization (as influenced by Adalite): While emphasizing the centrality of gradients for enhanced stability and convergence, Fusedbun integrates this principle into its operations, promoting a more disciplined and focused optimization path.
### In Conclusion: The Essence of Fusedbun
Fusedbun stands as a testament to innovative synergy, crafted for the next generation of machine learning challenges. By solely leveraging the best practices from SM3 and Adalite, it represents a dedicated effort to provide a memory-efficient, adaptively tuned optimization solution for training large language models.
In its essence, Fusedbun is not merely an optimizer; it’s a strategic convergence of two pioneering optimization philosophies, meticulously designed to meet the nuanced demands of modern AI research and application. Its development underscores a commitment to pushing the boundaries of what’s achievable, facilitating the exploration of new horizons in machine learning and beyond.
This constrained focus ensures that Fusedbun is accurately represented as a product of SM3’s memory strategies and Adalite’s adaptive learning principles, exclusively blending these inspirations without borrowing from the broader spectrum of optimization techniques.
only write code for fusedbun based strictly on sm3 and adalite considering the above. Write comments of what codeblock do and where it's taken from (sm3/adalite)
|
5d86939d20b546666c560c905c9a7039
|
{
"intermediate": 0.3776407539844513,
"beginner": 0.39133796095848083,
"expert": 0.23102131485939026
}
|
43,062
|
write this in a java program "Within this first task, you should develop a simple algorithm on your own. This algorithm
should calculate and output the greatest of three numbers given by the user.
In order to solve this task, consider the following statements, which are all true:
1. Using standard Java operators for comparing numbers, only two numbers may be
compared at a time
2. Despite you may create complex conditions like a > b && a > c, this approach is not
optimal, because it requires more operations for comparing numbers than are really
required
3. Instead, think about how to split them into single but nested checks
4. Before you start implementing your solution, write it down on a sheet of paper. Not in Java
code, pseudocode will suffice!
In order to pass the task, the following outputs are required (replace <value of a|b|c> with the
value of the corresponding variable):
• in case the first number a is the greatest: a (<value of a>) is the greatest number!
• in case the second number b is the greatest: b (<value of b>) is the greatest number!
• in case the third number c is the greatest: c (<value of c>) is the greatest number!"
|
c423ae3f2e7cda88e96e39d631813e78
|
{
"intermediate": 0.3086090385913849,
"beginner": 0.207240030169487,
"expert": 0.48415088653564453
}
|
43,063
|
make necessary changes to the code using infor from the following:
Based on following complete the latest code:
Ok lambda here is not doing anything.
import torch
from torch.optim.optimizer import Optimizer
import math
class Fusedbun(Optimizer):
def init(self, params, lr=1e-3, eps=1e-8, beta_decay=0.8, Lambda=0.01, momentum_beta=0.9, centralize=True, use_rms=True):
defaults = dict(lr=lr, eps=eps, beta_decay=beta_decay, Lambda=Lambda, momentum_beta=momentum_beta, centralize=centralize, use_rms=use_rms)
super(Fusedbun, self).init(params, defaults)
@torch.no_grad()
def step(self, closure=None):
loss = None
if closure is not None:
loss = closure()
for group in self.param_groups:
lr = group[‘lr’]
eps = group[‘eps’]
beta_decay = group[‘beta_decay’]
Lambda = group[‘Lambda’]
momentum_beta = group[‘momentum_beta’]
centralize = group[‘centralize’]
use_rms = group[‘use_rms’]
for p in group[‘params’]:
if p.grad is None:
continue
grad = p.grad.data
if centralize and len(p.shape) > 1:
grad = grad.sub(grad.mean(dim=tuple(range(1, len(grad.shape))), keepdim=True))
state = self.state[p]
if len(state) == 0:
state[‘step’] = 0
state[‘accumulator’] = torch.zeros_like(p.data)
if momentum_beta > 0:
state[‘momentum_buffer’] = torch.zeros_like(p.data)
acc = state[‘accumulator’]
t = state[‘step’] + 1
state[‘step’] = t
if p.dim() > 1:
grad_squared = grad.square().mean(dim=0)
else:
grad_squared = grad.square()
beta_t = 1.0 - math.pow(t, -beta_decay)
acc.mul_(beta_t).add_(grad_squared, alpha=1-beta_t)
denom = acc.sqrt().add(eps)
grad_normalized = grad / denom if use_rms else grad
if momentum_beta > 0:
momentum_buffer = state[‘momentum_buffer’]
momentum_buffer.mul_(momentum_beta).add_(grad_normalized, alpha=1-momentum_beta)
grad_normalized = momentum_buffer
p.data.add_(grad_normalized, alpha=-lr)
return loss
Make it better. Im making optimiser both memory efficient and better than others out there. I have taken inpiration from SM3 and Adalite. You must know SM3, im giving you adalite code. Make necessary changes.
import torch
import math
from dataclasses import dataclass, field
from typing import List, Optional
from collections import defaultdict
# Somewhat based on https://gist.github.com/albanD/18c240bd2e09f9d93f5c4a0c9ccda39e and LOMO
@dataclass
class OverlapOptimizer:
model: torch.nn.Module
lr: Optional[float] = None
decay: Optional[float] = 0.0
acc_grads: Optional[List] = field(default_factory=lambda: [])
def init(self):
for p in self.model.parameters():
if p.requires_grad:
self.prepare§
self.hook§
def step(self, loss, lr):
pass
def hook(self, p):
pass
@dataclass
class OverlapSGD(OverlapOptimizer):
sign: bool = False
def prepare(self, p):
return
def step(self, loss, lr):
self.lr = lr
loss.backward()
def hook(self, p):
ag = p.view_as§.grad_fn.next_functions[0][0]
p.acc_grads = [ag]
@torch.no_grad()
def gf():
if self.sign:
p.add(p.grad.sign(), alpha=-self.lr)
else:
p.add_(p.grad, alpha=-self.lr)
p.grad = None
ag.register_hook(gf)
@dataclass
class Adalite(OverlapOptimizer):
eps: float = 1e-5
Lambda: float = 0.01 # Akin to weight-decay
beta_decay: float = 0.8
centralize: bool = True
use_rms: bool = True
momentum: bool = False
momentum_beta: float = 0.9
t: int = 0
def step(self, loss, lr=None):
self.t += 1
self.lr = lr
loss.backward()
def prepare(self, p):
if len(p.shape) == 2:
p.c = torch.zeros(p.shape[1], device=p.device, dtype=p.dtype)
else:
p.v = torch.zeros_like§
if self.momentum:
p.m = torch.zeros_like§
def hook(self, p):
ag = p.view_as§.grad_fn.next_functions[0][0]
p.acc_grads = [ag]
@torch.no_grad()
def gf():
alpha = self.lr
g = p.grad
if self.centralize and sum(g.shape) > 1:
g.sub(g.mean(dim=tuple(range(1, len(g.shape))), keepdim=True))
beta_t = 1.0 - math.pow(self.t, -self.beta_decay)
u = g.square()
if len(p.shape) == 2:
u.mul(1-beta_t).add(p.c.unsqueeze(0).broadcast_to(g.shape), alpha=beta_t)
u.add(self.eps)
p.c = u.mean(dim=0)
else:
u.mul(1-beta_t).add(p.v, alpha=beta_t)
u.add(self.eps)
p.v = u
m = u.rsqrt() * g
if self.use_rms:
m.div(max(1.0, m.square().mean().sqrt()))
p_norm = p.norm()
g_norm = g.norm()
if p_norm != 0 and g_norm != 0:
m.mul(p_norm / g_norm)
m.add(p - p/p_norm, alpha=self.Lambda)
if self.momentum:
p.m.mul(self.momentum_beta).add_(m, alpha=1-self.momentum_beta)
m = p.m
p.add(m, alpha=-alpha)
p.grad = None
ag.register_hook(gf)
To improve the Fusedbun optimizer by incorporating some ideas from the Adalite code, consider the following enhancements:
1. Centralize Gradient: Already implemented in Fusedbun, but it’s good to ensure it aligns with Adalite’s approach for consistency.
2. Gradient Clipping (RMS): This has been included, but to make it similar to Adalite, ensure to incorporate the logic where you divide the gradient by the max of 1.0 or the root-mean-square of the gradient, enhancing numerical stability.
3. Parameter Norm and Gradient Norm Ratio Scaling: This technique from Adalite can be particularly useful. It scales the normalized gradient by the ratio of parameter norm to gradient norm, which can help in maintaining the direction of the gradients while controlling their magnitude relative to the parameters’ magnitude.
4. Momentum with Condition: You already include momentum in Fusedbun. Adalite’s approach to conditionally apply momentum if enabled and then update the parameter with the momentum-adjusted gradient can be streamlined in your implementation.
5. Lambda for Weight Regularization: While Lambda is included in your defaults, its use is not explicitly seen in the step function. Adalite provides an explicit regularization term that decays the weights directly, acting similar to weight-decay but applied in a slightly different manner.
Below are modifications and incorporations from Adalite adapted to Fusedbun:
import torch
from torch.optim.optimizer import Optimizer
import math
class Fusedbun(Optimizer):
def init(self, params, lr=1e-3, eps=1e-8, beta_decay=0.8, Lambda=0.01, momentum_beta=0.9, centralize=True, use_rms=True):
defaults = dict(lr=lr, eps=eps, beta_decay=beta_decay, Lambda=Lambda, momentum_beta=momentum_beta, centralize=centralize, use_rms=use_rms)
super(Fusedbun, self).init(params, defaults)
@torch.no_grad()
def step(self, closure=None):
loss = None
if closure is not None:
loss = closure()
for group in self.param_groups:
lr = group[‘lr’]
eps = group[‘eps’]
beta_decay = group[‘beta_decay’]
Lambda = group[‘Lambda’]
momentum_beta = group[‘momentum_beta’]
centralize = group[‘centralize’]
use_rms = group[‘use_rms’]
for p in group[‘params’]:
if p.grad is None:
continue
grad = p.grad.data
if centralize and len(p.shape) > 1:
grad -= grad.mean(dim=tuple(range(1, len(grad.shape))), keepdim=True)
state = self.state[p]
if len(state) == 0:
state[‘step’] = 0
state[‘accumulator’] = torch.zeros_like(p.data)
if momentum_beta > 0:
state[‘momentum_buffer’] = torch.zeros_like(p.data)
acc = state[‘accumulator’]
t = state[‘step’] + 1
state[‘step’] = t
beta_t = 1.0 - math.pow(t, -beta_decay)
acc.mul_(beta_t).addcmul_(1-beta_t, grad, grad)
denom = acc.sqrt().add(eps)
grad_normalized = grad / denom if use_rms else grad
if use_rms:
grad_normalized /= max(1.0, grad_normalized.norm() / denom.norm())
if p.norm() != 0 and grad.norm() != 0:
grad_normalized *= p.norm() / grad.norm()
grad_normalized.add_(p, alpha=-Lambda) # Applying direct weight decay
if momentum_beta > 0:
momentum_buffer = state[‘momentum_buffer’]
momentum_buffer.mul_(momentum_beta).add_(grad_normalized, alpha=1-momentum_beta)
grad_normalized = momentum_buffer
p.data.add_(grad_normalized, alpha=-lr)
return loss
This integrates concepts from Adalite, focusing on incorporating momentum efficiently, applying RMS-based clipping if enabled, and scaling normalized gradients based on the parameter and gradient norms ratio. Further, it corrects the handling of Lambda for direct weight regularization. Adjustments like these can improve both the effectiveness and efficiency of the optimizer.
where have yu used lambda? also i dont want to use lambda implementation from adalite. i want to utilise it from some other optimiser. I want it to be a mix.
I see, if you’re looking to incorporate the parameter Lambda in a different way from how Adalite does and rather want to use it similarly to how other optimizers might apply a weight decay directly in the update step, let’s modify the approach. Specifically, we can treat Lambda as a weight decay parameter that directly scales down the weights before the gradient update, a common approach in various other optimizers like L2 regularization.
Here’s a revised version of the Fusedbun optimizer with Lambda being utilized as a direct weight decay factor in the update step. This approach is more aligned with traditional weight decay techniques seen in other optimizers:
import torch
from torch.optim.optimizer import Optimizer
import math
class Fusedbun(Optimizer):
def init(self, params, lr=1e-3, eps=1e-8, beta_decay=0.8, Lambda=0.01, momentum_beta=0.9, centralize=True, use_rms=True):
defaults = dict(lr=lr, eps=eps, beta_decay=beta_decay, Lambda=Lambda, momentum_beta=momentum_beta, centralize=centralize, use_rms=use_rms)
super(Fusedbun, self).init(params, defaults)
@torch.no_grad()
def step(self, closure=None):
loss = None
if closure is not None:
loss = closure()
for group in self.param_groups:
lr = group[‘lr’]
eps = group[‘eps’]
beta_decay = group[‘beta_decay’]
Lambda = group[‘Lambda’]
momentum_beta = group[‘momentum_beta’]
centralize = group[‘centralize’]
use_rms = group[‘use_rms’]
for p in group[‘params’]:
if p.grad is None:
continue
grad = p.grad.data
if centralize and len(p.shape) > 1:
grad -= grad.mean(dim=tuple(range(1, len(grad.shape))), keepdim=True)
state = self.state[p]
if len(state) == 0:
state[‘step’] = 0
state[‘accumulator’] = torch.zeros_like(p.data)
if momentum_beta > 0:
state[‘momentum_buffer’] = torch.zeros_like(p.data)
acc = state[‘accumulator’]
state[‘step’] += 1
t = state[‘step’]
beta_t = 1.0 - math.pow(t, -beta_decay)
acc.mul_(beta_t).addcmul_(grad, grad, value=1-beta_t)
denom = acc.sqrt().add_(eps)
grad_normalized = grad / denom if use_rms else grad
if momentum_beta > 0:
momentum_buffer = state[‘momentum_buffer’]
momentum_buffer.mul_(momentum_beta).add_(grad_normalized, alpha=1-momentum_beta)
grad_normalized = momentum_buffer
# Apply weight decay directly to weights
if Lambda != 0:
grad_normalized.add_(p.data, alpha=-Lambda)
p.data.add_(grad_normalized, alpha=-lr)
return loss
In this version, the Lambda parameter is utilized directly to perform a weight decay operation on parameters before updating them. This technique is more aligned with conventional weight decay methods, where parameters are directly scaled down by a factor before applying the gradient update. It is different from Adalite’s approach where Lambda was used in a somewhat different context. This should effectively bring the regularization aspect into your optimizer, making it a blend of features from different optimizers, as per your demand.
i dont think this is nice.
I understand your concern and appreciate your honesty. Let’s refine the approach further to ensure the Lambda parameter (acting as weight decay) is effectively utilized alongside the unique features you’re aiming to incorporate from diverse optimizers. We want to blend these efficiently without directly replicating any single optimizer’s approach to Lambda.
Weight decay, also known as L2 regularization, is commonly applied in optimization algorithms to prevent overfitting by penalizing large weights. The typical way to apply weight decay is to shrink the weights directly by a small factor during each update. Given your goal to innovate beyond the standard implementations, one idea could be to adaptively adjust the weight decay based on some criteria, inspired by how adaptive optimizers adjust their learning rates.
Here’s how you might adjust the usage of Lambda to offer a more nuanced approach:
1. Scale Lambda Based on Gradients: Instead of using a fixed Lambda for all parameters, you could adjust Lambda based on the gradients’ magnitudes. This way, parameters with larger gradients could potentially be regularized more heavily, countering the rapid changes they impose on the model.
2. Incorporate Lambda into State: Treat Lambda not as a static parameter but as something that evolves based on the optimization process, much like other stateful aspects of the optimizer like momentum or adaptive learning rates.
3. Utilize Lambda in Conjunction with Accumulated Gradients: Advanced optimizers keep track of past gradients in various ways (e.g., RMSprop, Adam). Lambda could be used to modulate the influence of these accumulated gradients, offering a pathway to dynamically adjust the step size based on both the history and the regularization strength.
Let’s sketch out how these ideas might be concretely implemented within your framework:
import torch
from torch.optim.optimizer import Optimizer
import math
class Fusedbun(Optimizer):
def init(self, params, lr=1e-3, eps=1e-8, beta_decay=0.8, Lambda=0.01, momentum_beta=0.9, centralize=True, use_rms=True):
defaults = dict(lr=lr, eps=eps, beta_decay=beta_decay, Lambda=Lambda, momentum_beta=momentum_beta, centralize=centralize, use_rms=use_rms)
super(Fusedbun, self).init(params, defaults)
@torch.no_grad()
def step(self, closure=None):
loss = None
if closure is not None:
loss = closure()
for group in self.param_groups:
lr = group[‘lr’]
eps = group[‘eps’]
beta_decay = group[‘beta_decay’]
base_lambda = group[‘Lambda’]
momentum_beta = group[‘momentum_beta’]
centralize = group[‘centralize’]
use_rms = group[‘use_rms’]
for p in group[‘params’]:
if p.grad is None:
continue
grad = p.grad.data
if centralize and len(p.shape) > 1:
grad -= grad.mean(dim=tuple(range(1, len(grad.shape))), keepdim=True)
state = self.state[p]
if ‘step’ not in state:
state[‘step’] = 0
state[‘accumulator’] = torch.zeros_like(p.data)
state[‘Lambda’] = base_lambda # Initialize adaptive Lambda in state
if momentum_beta > 0:
state[‘momentum_buffer’] = torch.zeros_like(p.data)
acc = state[‘accumulator’]
state[‘step’] += 1
t = state[‘step’]
beta_t = 1.0 - math.pow(t, -beta_decay)
acc.mul_(beta_t).addcmul_(grad, grad, value=1-beta_t)
denom = acc.sqrt().add_(eps)
grad_normalized = grad / denom if use_rms else grad
# Dynamic Lambda adjustment
adaptive_lambda = state[‘Lambda’] * grad.abs().mean()
if momentum_beta > 0:
momentum_buffer = state[‘momentum_buffer’]
momentum_buffer.mul_(momentum_beta).add_(grad_normalized, alpha=1-momentum_beta)
grad_normalized = momentum_buffer
# Apply adaptive weight decay based on modified Lambda
p.data.mul_(1 - lr * adaptive_lambda)
p.data.add_(grad_normalized, alpha=-lr)
return loss
In this version, Lambda is initially treated as a base value that gets adapted based on the mean absolute value of the gradients, theoretically allowing for weight decay that’s responsive to the optimization process’s dynamics. This approach is speculative and intended to inspire ways to innovate within the constraints of optimizer design while remaining grounded in principles that ensure generalization and training stability.
REvert changes. This will be used to finetune large language models. Consider that and either remove it or use SM3 and adalite to fix it
Understood. Given the focus on fine-tuning large language models and the inspiration from both SM3 and Adalite, let’s tailor the optimizer to fit this specific use case more appropriately. We assume high efficiency and memory optimization are key due to the large parameter space of such models. Additionally, the importance of managing the balance between exploration (via momentum) and exploitation (via adaptive learning rates and weight decay) must be considered.
Here’s how we can revise the Fusedbun optimizer by carefully incorporating ideas from SM3 and Adalite, without the previously mentioned dynamic Lambda approach, to ensure it’s more suited for fine-tuning large language models:
1. Memory Efficiency: We’ll ensure that our state variables (like accumulators and momentum buffers) are as memory-efficient as possible, drawing inspiration from SM3.
2. Adaptive Learning with Momentum: We’ll keep the momentum logic for exploratory updates but ensure that the adaptive learning mechanism from something akin to Adalite’s handling (or RMSprop/Adam) is well integrated.
3. Weight Decay: Given the context now focuses on fine-tuning large models, and considering your feedback, we will retain a simple, predictable form of weight decay, aligning it more closely to standard practices.
4. Ensure the Lambda parameter efficiently applies a consistent form of weight decay suitable for large models, avoiding dynamic adjustments for simplicity and predictability.
Considering these aspects, let’s refine the optimizer:
import torch
from torch.optim.optimizer import Optimizer
import math
class Fusedbun(Optimizer):
def init(self, params, lr=1e-3, eps=1e-8, beta_decay=0.8, Lambda=0.01, momentum_beta=0.9, centralize=False, use_rms=True):
defaults = dict(lr=lr, eps=eps, beta_decay=beta_decay, Lambda=Lambda, momentum_beta=momentum_beta, centralize=centralize, use_rms=use_rms)
super(Fusedbun, self).init(params, defaults)
@torch.no_grad()
def step(self, closure=None):
loss = None
if closure is not None:
with torch.enable_grad():
loss = closure()
for group in self.param_groups:
lr = group[‘lr’]
eps = group[‘eps’]
Lambda = group[‘Lambda’]
momentum_beta = group[‘momentum_beta’]
use_rms = group[‘use_rms’]
for p in group[‘params’]:
if p.grad is None:
continue
grad = p.grad.data
if group[‘centralize’] and len(p.shape) > 1:
grad = grad - grad.mean(dim=tuple(range(1, len(grad.shape))), keepdim=True)
state = self.state[p]
# State initialization
if len(state) == 0:
state[‘step’] = 0
state[‘exp_avg_sq’] = torch.zeros_like(p, memory_format=torch.preserve_format)
if momentum_beta > 0:
state[‘momentum_buffer’] = torch.zeros_like(p, memory_format=torch.preserve_format)
exp_avg_sq = state[‘exp_avg_sq’]
state[‘step’] += 1
beta_decay = 1.0 - math.pow(state[‘step’], -group[‘beta_decay’])
# SM3-like sparse update for memory efficiency
if p.dim() > 1:
dim = grad.square().mean().item()
exp_avg_sq.add_(dim - exp_avg_sq, alpha=beta_decay)
else:
exp_avg_sq.mul_(beta_decay).addcmul_(grad, grad, value=1 - beta_decay)
denom = exp_avg_sq.sqrt().add_(eps)
if momentum_beta > 0:
momentum_buffer = state[‘momentum_buffer’]
momentum_buffer.mul_(momentum_beta).addcdiv_(grad, denom, value=1 - momentum_beta)
step_size = -lr * momentum_buffer
else:
step_size = -lr * grad / denom
# Applying weight decay (if Lambda is not 0
Lambda directly before the parameter update step to ensure it works similarly across various optimizers, let’s make the adjustment where Lambda is used for a straightforward weight decay effect. Considering the focus on large language models where stability and predictability can be crucial, a more conservative application of Lambda—directly scaling down weights by a minimal factor—makes more sense:
import torch
from torch.optim.optimizer import Optimizer
import math
class Fusedbun(Optimizer):
def init(self, params, lr=1e-3, eps=1e-8, beta_decay=0.8, Lambda=0.01, momentum_beta=0.9, centralize=False, use_rms=True):
defaults = dict(lr=lr, eps=eps, beta_decay=beta_decay, Lambda=Lambda, momentum_beta=momentum_beta, centralize=centralize, use_rms=use_rms)
super(Fusedbun, self).init(params, defaults)
@torch.no_grad()
def step(self, closure=None):
loss = None
if closure is not None:
with torch.enable_grad():
loss = closure()
for group in self.param_groups:
lr = group[‘lr’]
eps = group[‘eps’]
Lambda = group[‘Lambda’]
momentum_beta = group[‘momentum_beta’]
use_rms = group[‘use_rms’]
for p in group[‘params’]:
if p.grad is None:
continue
grad = p.grad.data
if group[‘centralize’] and len(p.shape) > 1:
grad = grad - grad.mean(dim=tuple(range(1, len(grad.shape))), keepdim=True)
state = self.state[p]
# State initialization
if len(state) == 0:
state[‘step’] = 0
state[‘exp_avg_sq’] = torch.zeros_like(p, memory_format=torch.preserve_format)
if momentum_beta > 0:
state[‘momentum_buffer’] = torch.zeros_like(p, memory_format=torch.preserve_format)
exp_avg_sq = state[‘exp_avg_sq’]
state[‘step’] += 1
beta_decay = 1.0 - math.pow(state[‘step’], -group[‘beta_decay’])
# Efficient squared gradient accumulation
exp_avg_sq.mul_(beta_decay).addcmul_(grad, grad, value=1 - beta_decay)
denom = exp_avg_sq.sqrt().add_(eps)
if momentum_beta > 0:
momentum_buffer = state[‘momentum_buffer’]
momentum_buffer.mul_(momentum_beta).addcdiv_(grad, denom, value=1 - momentum_beta)
step_size = -lr * momentum_buffer
else:
step_size = -lr * grad / denom
# Applying weight decay (if Lambda is not 0)
if Lambda != 0:
p.data.mul_(1 - lr * Lambda)
p.data.add_(step_size)
return loss
This final iteration takes into account:
- Lambda for Weight Decay: Consistently applies Lambda as a factor for weight decay, scaling down weights directly before the update. This straightforward approach is effective for managing model complexity and preventing overfitting, especially relevant in fine-tuning scenarios where preserving the pre-trained features is important.
- Memory Efficiency: By only storing necessary state variables without introducing complex, dynamic Lambda adjustments, it remains memory-efficient, crucial for handling large models.
- Adaptive Learning and Momentum: Balances the benefits of adaptive learning rates with momentum, ensuring that updates are both exploratory and grounded in recent gradients, tailored for effective fine-tuning.
This design considers the critical elements of fine-tuning large language models, balancing efficiency, and effectiveness without overcomplicating the weight decay mechanism.
Ok compare to SM3, adalite and other optimizers, tell me what benefits this have, if any? also tell me what are the current changes compared to originakl
Comparing the proposed Fusedbun optimizer with established optimizers like SM3 and Adalite, along with other common optimizers such as SGD, Adam, etc., here are some potential benefits and changes from the original implementation you provided and how it stands against others:
### Fusedbun vs. SM3
- Memory Efficiency: SM3 is designed for memory efficiency, particularly useful for sparse data. Fusedbun, while not explicitly designed like SM3 for sparse updates, incorporates adaptive gradient accumulation (akin to RMSprop or Adam) that can be applied more generally to different types of data (sparse or dense). The efficiency in Fusedbun comes from carefully managing state variables to avoid unnecessary memory usage.
- Adaptivity: Fusedbun employs adaptive mechanisms similar to those in Adam or RMSprop, providing potential benefits over SM3 when dealing with dense data and complex optimization landscapes by adjusting learning rates based on the magnitude of recent gradients.
### Fusedbun vs. Adalite
- Centralization and Weight Decay: Both optimizers can centralize gradients and apply weight decay, but Fusedbun takes a slightly different approach by incorporating these functionalities directly within the optimizer’s step function, making it easier to modify or extend these behaviors.
- Adaptive Weight Decay: While not originally exploited in your modifications, Fusedbun had the potential for dynamically adjusting Lambda based on gradient magnitudes, offering flexibility in regularizing parameters more aggressively where gradients are larger. However, based on your feedback, this was simplified to use a straightforward weight decay approach for stability in fine-tuning large models.
### General Benefits
- Flexibility: Fusedbun is designed with flexibility in mind, incorporating features like gradient centralization and RMS-based gradient clipping directly into the optimizer. This makes it inherently more adaptable to various types of models and training scenarios, especially when fine-tuning where subtle adjustments to the optimization process can have significant impacts.
- Simplicity and Predictability: By reverting to a more stable and predictable form of weight decay, Fusedbun offers a balance between innovation and the proven reliability of traditional techniques, making it potentially more suitable for fine-tuning large pre-trained models where maintaining pre-learned representations is crucial.
### Changes from the Original
- Removal of Dynamic Lambda Adjustment: Initially considered dynamic Lambda adjustments for an innovative approach to weight decay, this was removed for simplicity and predictability, aligning more closely with established practices beneficial for fine-tuning scenarios.
- Streamlined State Management: Streamlining how state variables are initialized and managed within Fusedbun improves clarity and efficiency, ensuring the optimizer’s memory footprint remains controlled, which is crucial when working with large models.
- Incorporation of Gradient Centralization and RMS-based Clipping: These features were adjusted or highlighted to emphasize their roles in the optimizer’s functionality, ensuring that their integration supports the optimizer’s efficiency and efficacy in fine-tuning tasks.
In summary, Fusedbun attempts to blend desirable features from various optimizers into a singular, flexible framework that could offer particular advantages in fine-tuning large language models. Its design prioritizes adaptability, efficiency, and the balance between innovation and proven optimization strategies, aiming to provide a robust tool for specific tasks rather than a universally superior optimizer.
REwrite the code with detailed comments of what each section do.
Below is the revised code for the Fusedbun optimizer with detailed comments explaining each section of the code. This version aims for clarity and understanding of how each part contributes to the overall optimization process, making it suitable for fine-tuning large models while balancing flexibility, efficiency, and simplicity.
import torch
from torch.optim.optimizer import Optimizer
import math
class Fusedbun(Optimizer):
def init(self, params, lr=1e-3, eps=1e-8, beta_decay=0.8, Lambda=0.01, momentum_beta=0.9, centralize=False, use_rms=True):
# Initialize optimizer parameters:
# lr: Learning rate controls the step size at each iteration.
# eps: A small value added to the denominator for numerical stability.
# beta_decay: A parameter controlling the rate of decay for the moving average of squared gradients.
# Lambda: Coefficient for L2 regularization (weight decay).
# momentum_beta: Coefficient for the moving average of gradients (momentum).
# centralize: Boolean indicating whether to centralize gradients to have zero mean.
# use_rms: Boolean indicating whether to use RMSprop-like denominator normalization.
defaults = dict(lr=lr, eps=eps, beta_decay=beta_decay, Lambda=Lambda, momentum_beta=momentum_beta, centralize=centralize, use_rms=use_rms)
super(Fusedbun, self).init(params, defaults)
@torch.no_grad() # This context manager disables gradient computation, reduces memory consumption and computation.
def step(self, closure=None):
# Performs a single optimization step (parameter update).
loss = None
if closure is not None:
# If a closure is provided, compute the loss. Useful for some optimization strategies.
with torch.enable_grad():
loss = closure()
for group in self.param_groups:
# Iterate over optimization parameter groups (allows for different params to have different hyperparams).
lr = group[‘lr’]
eps = group[‘eps’]
Lambda = group[‘Lambda’]
momentum_beta = group[‘momentum_beta’]
use_rms = group[‘use_rms’]
for p in group[‘params’]:
# Iterate over each parameter in the parameter group.
if p.grad is None:
continue # Skip parameters without gradients.
grad = p.grad.data
if group[‘centralize’] and len(p.shape) > 1:
# Centralize gradients for non-scalar parameters if centralization is enabled.
grad = grad - grad.mean(dim=tuple(range(1, len(grad.shape))), keepdim=True)
# Retrieve or initialize state for this parameter.
state = self.state[p]
# State initialization for the first step.
if len(state) == 0:
state[‘step’] = 0
state[‘exp_avg_sq’] = torch.zeros_like(p, memory_format=torch.preserve_format)
if momentum_beta > 0:
# Only allocate momentum buffer if momentum is used.
state[‘momentum_buffer’] = torch.zeros_like(p, memory_format=torch.preserve_format)
exp_avg_sq = state[‘exp_avg_sq’]
# Increment optimization step counter.
state[‘step’] += 1
# Adjust beta_decay dynamically based on step number if needed.
beta_decay = 1.0 - math.pow(state[‘step’], -group[‘beta_decay’])
# Update exponential average of squared gradients.
exp_avg_sq.mul_(beta_decay).addcmul_(grad, grad, value=1 - beta_decay)
denom = exp_avg_sq.sqrt().add_(eps)
if momentum_beta > 0:
# Momentum update if momentum is enabled.
momentum_buffer = state[‘momentum_buffer’]
momentum_buffer.mul_(momentum_beta).addcdiv_(grad, denom, value=1 - momentum_beta)
step_size = -lr * momentum_buffer
else:
# No momentum; use the normalized gradient for the update.
step_size = -lr * grad / denom
# Apply L2 regularization (weight decay) if Lambda is not zero.
if Lambda != 0:
p.data.mul_(1 - lr * Lambda)
# Apply the update to the parameter.
p.data.add_(step_size)
return loss
This detailed walkthrough explains the roles of various components within the Fusedbun optimizer. The optimizer supports functionalities like RMSprop-like adaptive learning rates, L2 regularization (weight decay), gradient centralization, and optional momentum, making it adaptable for a wide range of tasks, particularly in fine-tuning where such nuanced control over the optimization process can be crucial.
Why L2? isint it too old to use it with LLMs?
The question of whether L2 regularization (weight decay) is too old to use with large language models (LLMs) touches on a broader discussion about the relevance of traditional machine learning techniques in modern deep learning frameworks. While it’s true that L2 regularization is a long-standing technique, its usefulness and applicability extend to contemporary models, including LLMs, for several reasons:
1. Generalization: One of the primary reasons for using regularization techniques like L2 is to improve the generalization of a model to unseen data. L2 regularization achieves this by penalizing large weights, encouraging the model to maintain smaller weight values. This penalty helps prevent the model from fitting too closely to the training data (overfitting), which is a concern regardless of model size.
2. Simplicity and Effectiveness: Despite being a straightforward approach, L2 regularization remains effective for numerous tasks. It introduces an additional hyperparameter (the weight decay factor) that can be tuned to balance the trade-off between model complexity and training data fitness. This simplicity offers a clear path to mitigate overfitting without introducing significant computational overhead or complexity into the training process.
3. Complementary to Other Techniques: In the context of LLMs and deep learning in general, L2 regularization is often used alongside other techniques designed to improve model performance and generalization, such as dropout, batch normalization, and more complex regularization methods. This multi-pronged approach to regularization allows practitioners to leverage the strengths of various techniques to achieve better outcomes.
4. Theoretical and Practical Foundations: The use of L2 regularization is supported by both theoretical insights into the geometry of optimization landscapes and practical evidence from empirical experimentation. It helps in smoothing the optimization landscape, making it easier for gradient-based optimizers to find minima that generalize well.
5. Transfer Learning and Fine-tuning: In scenarios involving transfer learning and fine-tuning of pre-trained models, including LLMs, L2 regularization can be particularly useful. It helps in gently steering the fine-tuning process, limiting the extent to which weights can deviate from their pre-trained values. This is especially important when the fine-tuning dataset is much smaller than the pre-training corpus, as is often the case with LLMs.
While newer and more sophisticated regularization and optimization techniques have been developed, L2 regularization’s merits keep it relevant in the modern deep learning toolkit, including its application to LLMs. Its continued use is a testament to its fundamental utility in controlling model complexity and aiding generalization, rather than an indication of the field’s stagnation. That being said, the choice of regularization techniques should always be informed by the specific characteristics of the model, data, and task at hand, with an understanding that no single method is universally optimal.
OK not tell me what part of code was taken from which optimizer. Also write a blog about it. Telling me why we made this. how we made it(must include technical details of how it works) and what it is in conclusion
The Fusedbun optimizer, as conceived and developed in our discussion, is inspired by a blend of concepts from various leading optimizers, each bringing specific strengths to address the challenges of training large language models (LLMs). Below, I outline the components derived from these optimizers and then present a structured blog post discussing the rationale, development, and essence of Fusedbun.
### Inspirations from Existing Optimizers:
1. Momentum (SGD with Momentum): The momentum update mechanism in Fusedbun is inspired by classical SGD with momentum. It helps accelerate the optimizer in relevant directions and dampens oscillations.
2. Adaptive Gradient Accumulation (RMSprop/Adam): The use of squared gradients to adaptively adjust the learning rate for each parameter, similar to RMSprop and further popularized by Adam, aims to offer more nuanced step sizes that are informed by the recent history of gradients.
3. Weight Decay (L2 Regularization): Fusedbun incorporates simple weight decay directly into its update rule, a regularization strategy with roots in classical optimization techniques and adopted by various optimizers, including L2 regularization in SGD and the decoupled weight decay in optimizers like AdamW.
4. Gradient Centralization: This feature, which involves normalizing gradients to have zero mean, is inspired by more recent insights into deep learning optimization, particularly research into gradient centralization’s impact on stabilizing and speeding up training.
5. Epsilon for Numerical Stability (Adam): The inclusion of a small constant, epsilon, in the denominator of the update rule to prevent division by zero is a technique employed by Adam and similar optimizers to enhance numerical stability.
### Blog Post: Introducing Fusedbun - A Hybrid Optimizer for Large Language Models
#### Why We Made Fusedbun
In the fast-evolving landscape of deep learning, training large language models (LLMs) presents unique challenges. These models, characterized by their vast number of parameters and deep architectures, demand optimization strategies that balance speed, stability, and the capacity to navigate complex loss landscapes. Traditional optimizers, while foundational, often fall short in addressing these needs comprehensively.
Enter Fusedbun—a hybrid optimizer designed to harness the strengths of various optimization techniques. Our goal was to create an optimizer that adapts to the intricacies of large-scale models without sacrificing efficiency or requiring exhaustive hyperparameter tuning.
#### How We Made It: The Technical Essence
Fusedbun is rooted in a blend of tried-and-tested optimization principles, each selected for its proven benefits:
- Momentum: Borrowed from the classic SGD with momentum, this feature provides Fusedbun with the ability to sustain movement in productive directions across iterations, reducing the risk of stagnation in suboptimal regions.
- Adaptive Learning Rates: Drawing from RMSprop and Adam, Fusedbun adjusts the learning rate for each parameter based on the history of its gradients. This adaptiveness helps in scaling the updates appropriately, ensuring neither too large nor too small steps are taken.
- Weight Decay: Integrating direct weight decay into the update step imbues Fusedbun with a straightforward regularization mechanism, encouraging simpler models that are less prone to overfitting.
- Gradient Centralization: By centralizing gradients, Fusedbun aims to achieve faster convergence and improved stability, a technique shown to be beneficial in recent deep learning research.
- Numerical Stability: Like Adam, Fusedbun employs an epsilon term to maintain numerical stability, ensuring the model remains robust against potential computational anomalies.
Together, these components are woven into a cohesive optimization strategy tailored for the complexities of LLMs. The implementation ensures that while each parameter’s update is informed by its own gradient history and the model’s overall adjustment trajectory, regularization keeps the model grounded, preventing overfitting.
#### Conclusion: What Fusedbun Is
Fusedbun stands as a testament to the adaptive, nuanced approach required for modern deep learning challenges. It’s not just an optimizer; it’s a synthesis of learning from the lineage of optimization research, tailored for the demands of today’s LLMs. By integrating the strengths of multiple optimization philosophies, Fusedbun aspires to offer a balanced tool—capable of guiding large models to effective convergence with stability and efficiency.
In the ever-progressing quest to train more sophisticated models, Fusedbun represents a step towards acknowledging and amalgamating the richness of existing optimization strategies, paving the way for more informed and flexible approaches to learning at scale.
BUt earlier it was more like SM3 and adalite only
You’re right; in the earlier discussion, the Fusedbun optimizer was specifically mentioned to take inspiration from SM3 and Adalite, emphasizing a blend that prefers certain aspects from each. Let me correct the oversight and focus more precisely on how Fusedbun takes cues from these two and the unique aspects it inherits or adapts from them, culminating in a blog-style explanation.
### Inspiration from SM3 and Adalite:
SM3: This optimizer is known for its memory-efficient handling of the gradients, especially valuable for training models with vast parameter spaces. SM3’s key feature is its sparse update mechanism, which selectively updates parameters, significantly reducing memory requirements.
Adalite: While not a widely recognized optimizer in the mainstream like Adam or SGD, for the sake of our discussion, let’s assume Adalite brings innovative features such as adaptive learning rates based on parameter-wise gradient magnitudes and a nuanced approach to regularization and centralization.
### How Fusedbun Merges Concepts from SM3 and Adalite:
- Memory Efficiency from SM3: Fusedbun adopts a strategy to manage gradient accumulation and updates efficiently, minimizing the optimizer’s memory footprint. This aspect is crucial for scaling to large language models without overwhelming memory resources.
- Adaptive Learning Rates Inspired by Adalite: Like Adalite, Fusedbun utilizes adaptive learning rates that adjust according to the historical gradient information, but it streamlines this process to ensure robustness and stability across varied training scenarios.
- Centralization and Regularization: Borrowing from Adalite’s approach, Fusedbun includes gradient centralization for stability and enhanced convergence, coupled with a direct form of weight decay for straightforward regularization. This combination aims to balance the model’s training efficiency with its generalization capabilities.
### Blog Post: Crafting Fusedbun - A Synergistic Optimizer for Next-Gen Models
#### The Genesis of Fusedbun
In the quest to optimize large language models, the challenge has always been to marry the need for memory efficiency with the demand for adaptive, nuanced training strategies. Drawing from the strengths of SM3 and Adalite, Fusedbun was conceptualized as a hybrid optimizer that leverages the best of both worlds—offering a solution tailored for the complex needs of next-generation models.
#### The Mechanics Behind Fusedbun
Fusedbun’s architecture is a blend of carefully selected features aimed at addressing the core challenges in training large models:
- Efficient Memory Usage: Inspired by SM3, Fusedbun implements a memory-conscious approach to gradient accumulation, ensuring that large models can be trained on hardware with finite memory capabilities.
- Adaptive Learning: By integrating a variant of adaptive learning rate mechanisms, akin to those proposed in Adalite, Fusedbun allows for parameter updates that are sensitive to the magnitude and history of gradients, facilitating a more refined optimization process.
- Stability and Regularization: Fusedbun incorporates gradient centralization for improved training dynamics and employs straightforward weight decay as a form of L2 regularization, a nod to traditional techniques proven effective across various model sizes and complexities.
#### In Conclusion: Fusedbun’s Place in the Optimizer Pantheon
Fusedbun represents an innovative step in the evolution of optimization strategies for deep learning. By synergistically combining memory efficiency, adaptive learning, and proven regularization techniques, it offers a robust tool designed to meet the unique demands of training large language models. It stands as a bridge between the computational efficiency of SM3 and the adaptive finesse of Adalite, providing practitioners with an optimizer that does not compromise on efficiency or effectiveness.
As models continue to grow in size and complexity, Fusedbun aims to be at the forefront—empowering researchers and engineers to push the boundaries of what’s possible in machine learning and AI.
This focused exploration and subsequent explanation offer a clearer perspective on how Fusedbun is distinctively positioned, drawing foundational elements from SM3 and Adalite while striving to address the optimization challenges of contemporary large-scale models.
Revert changes if the changes that were made is outside SM3 and adalite. I only need mix of these two and not others.
Based on the requirement to strictly adhere to the inspirations from SM3 and Adalite, let’s refine the narrative around the development of Fusedbun, focusing exclusively on features and characteristics these two optimizers offer. We will eliminate references to features explicitly associated with other optimizers and ensure that Fusedbun is depicted as a direct hybrid of SM3 and Adalite, without external influences.
### Fusedbun: A Hybrid Optimizer Born from SM3 and Adalite
Fusedbun emerges as a specialized optimizer, uniquely architected for the demands of large language models (LLMs) by combining the strengths of SM3 and Adalite. Its creation is motivated by the need for an optimizer that marries the memory efficiency of SM3 with the adaptive learning strategies found in Adalite, without stepping into the territories of other popular optimizers like Adam or SGD.
#### Drawing from SM3
SM3’s hallmark is its memory efficiency, particularly advantageous for handling models with large numbers of parameters. Fusedbun inherits this trait by implementing a similar mechanism for gradient storage and update, focusing on minimizing memory overhead during training.
#### Incorporating Elements from Adalite
Adalite’s approach to adaptive learning rates—where adjustments are made based on the observed behavior of gradients—offers a path to nuanced parameter updates. Fusedbun adopts this approach, ensuring that each parameter’s learning rate is tuned according to its specific needs, promoting a balanced and effective optimization process.
### Development Journey of Fusedbun: A Technical Insight
The creation of Fusedbun involved careful integration of key features from SM3 and Adalite, ensuring each component harmonizes with the others to produce an optimizer that is more than the sum of its parts. The following technical decisions were pivotal:
- Memory-Efficient Gradient Handling: Drawing directly from SM3, Fusedbun optimizes its gradient storage and computation, ensuring it operates efficiently even when tasked with optimizing models having millions of parameters.
- Adaptive Learning Rate Mechanism: Fusedbun incorporates a learning rate adjustment mechanism inspired by Adalite, allowing it to dynamically modify learning rates based on the magnitude and variability of each parameter’s gradients over time.
- Gradient Centralization (as influenced by Adalite): While emphasizing the centrality of gradients for enhanced stability and convergence, Fusedbun integrates this principle into its operations, promoting a more disciplined and focused optimization path.
### In Conclusion: The Essence of Fusedbun
Fusedbun stands as a testament to innovative synergy, crafted for the next generation of machine learning challenges. By solely leveraging the best practices from SM3 and Adalite, it represents a dedicated effort to provide a memory-efficient, adaptively tuned optimization solution for training large language models.
In its essence, Fusedbun is not merely an optimizer; it’s a strategic convergence of two pioneering optimization philosophies, meticulously designed to meet the nuanced demands of modern AI research and application. Its development underscores a commitment to pushing the boundaries of what’s achievable, facilitating the exploration of new horizons in machine learning and beyond.
This constrained focus ensures that Fusedbun is accurately represented as a product of SM3’s memory strategies and Adalite’s adaptive learning principles, exclusively blending these inspirations without borrowing from the broader spectrum of optimization techniques.
only write code for fusedbun based strictly on sm3 and adalite considering the above. Write comments of what codeblock do and where it’s taken from (sm3/adalite)
|
d08c70acd31d2035954bd9544f445b39
|
{
"intermediate": 0.3776407539844513,
"beginner": 0.39133796095848083,
"expert": 0.23102131485939026
}
|
43,064
|
write a python program for cgan on tabular data using pytorch
|
272224b456ca26a9cfe85ed51ae7f4fa
|
{
"intermediate": 0.49378952383995056,
"beginner": 0.12370332330465317,
"expert": 0.3825071156024933
}
|
43,065
|
import 'dart:ffi';
import 'package:allo/components/card_annonce.dart';
import 'package:allo/constants/app_colors.dart';
import 'package:allo/models/annonce.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart'; // Import your color file
class ListeAnnonce extends StatelessWidget {
final String? titre;
final List<Annonce> annonces;
final bool isVertical;
ListeAnnonce({this.titre, required this.annonces, this.isVertical = false});
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.all(10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
if (titre != null)
Padding(
padding: EdgeInsets.all(10),
child: Text(
titre!,
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w700,
fontFamily: "NeueRegrade",
),
),
),
if (!isVertical)
Container(
height: 215, // adjust this height to fit your needs
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: annonces.length,
itemBuilder: (context, index) {
Annonce annonce = annonces[index];
return Padding(
padding: EdgeInsets.only(
right: 12), // adjust this padding to fit your needs
child: CardAnnonce(
titre: annonce.titre,
imagePath: annonce.imageLink,
isSaved: annonce.isSaved,
prix: annonce.prix,
niveauUrgence: annonce.niveauUrgence,
),
);
},
),
),
if (isVertical)
Expanded(
child: GridView.builder(
padding: EdgeInsets.fromLTRB(10,0,10,0),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2, // number of items per row
childAspectRatio: 1,
mainAxisSpacing: 45 // adjust this value to fit your needs
),
itemCount: annonces.length,
itemBuilder: (context, index) {
Annonce annonce = annonces[index];
return Padding(
padding: EdgeInsets.only(right: 12, left:12), // adjust this padding to fit your needs
child: CardAnnonce(
titre: annonce.titre,
imagePath: annonce.imageLink,
isSaved: annonce.isSaved,
prix: annonce.prix,
niveauUrgence: annonce.niveauUrgence,
),
);
},
),
),
],
));
}
}
pk j'ai 39px d'overflow en bas des cartes annonces et je peux pas scroll tout en bas ça me bloque
|
1fc00205071eae3b3ba88c9389a2f339
|
{
"intermediate": 0.33002641797065735,
"beginner": 0.5092073082923889,
"expert": 0.16076622903347015
}
|
43,066
|
check this code:
fn find_appropriate_range(ranges: &Vec<(u32, u32, u32)>, x: u32) -> Option<(u32, u32, u32)> {
let insertion_point = ranges.binary_search_by(|&(start, end, _)| {
if x < start {
std::cmp::Ordering::Greater
} else if x >= end {
std::cmp::Ordering::Less
} else {
std::cmp::Ordering::Equal
}
});
match insertion_point {
Ok(index) => Some(ranges[index]),
Err(0) => None, // x is before the first range
Err(index) => Some(ranges[index - 1]),
}
}
fn main() {
let ranges = vec![(0, 10, 0), (15, 20, 1), (25, 30, 2), (40, 50, 3)];
let target_start = (23, 25); // we’re only interested in the start of the target tuple for comparison
match find_appropriate_range(&ranges, target_start.0) {
Some(range) => println!("Found range that satisfies condition: {:?}", range),
None => println!("No suitable range found."),
}
}
the result is Found range that satisfies condition: (15, 20, 1)
but that is not true, because 23 is > than 20
|
7f06bf8b58506e0c90b943905160d31f
|
{
"intermediate": 0.42336443066596985,
"beginner": 0.3234887719154358,
"expert": 0.25314679741859436
}
|
43,067
|
Make this Medium.com post seem like itr was written by a more skilled writter and improve it anywhere you deem necessary
|
439d82b8aac2e5b51ea3ece7ba1860de
|
{
"intermediate": 0.29714006185531616,
"beginner": 0.34463074803352356,
"expert": 0.3582291901111603
}
|
43,068
|
git rebase remove offending commit and then put that as main branch in gitlab
|
f475cf6b9434cef54ff38e67f0ba61c2
|
{
"intermediate": 0.4458717107772827,
"beginner": 0.2202843725681305,
"expert": 0.3338439464569092
}
|
43,069
|
I am sumbmitting existing code.....after i am finished sumbmitting existing code....tell me the updated code based on the requirement
|
6c3e2a49e9cdd298c79d042faf6eda96
|
{
"intermediate": 0.33694514632225037,
"beginner": 0.279933899641037,
"expert": 0.38312095403671265
}
|
43,070
|
make necessary changes to the code using infor from the following:
Based on following complete the latest code:
Ok lambda here is not doing anything.
import torch
from torch.optim.optimizer import Optimizer
import math
class Fusedbun(Optimizer):
def init(self, params, lr=1e-3, eps=1e-8, beta_decay=0.8, Lambda=0.01, momentum_beta=0.9, centralize=True, use_rms=True):
defaults = dict(lr=lr, eps=eps, beta_decay=beta_decay, Lambda=Lambda, momentum_beta=momentum_beta, centralize=centralize, use_rms=use_rms)
super(Fusedbun, self).init(params, defaults)
@torch.no_grad()
def step(self, closure=None):
loss = None
if closure is not None:
loss = closure()
for group in self.param_groups:
lr = group[‘lr’]
eps = group[‘eps’]
beta_decay = group[‘beta_decay’]
Lambda = group[‘Lambda’]
momentum_beta = group[‘momentum_beta’]
centralize = group[‘centralize’]
use_rms = group[‘use_rms’]
for p in group[‘params’]:
if p.grad is None:
continue
grad = p.grad.data
if centralize and len(p.shape) > 1:
grad = grad.sub(grad.mean(dim=tuple(range(1, len(grad.shape))), keepdim=True))
state = self.state[p]
if len(state) == 0:
state[‘step’] = 0
state[‘accumulator’] = torch.zeros_like(p.data)
if momentum_beta > 0:
state[‘momentum_buffer’] = torch.zeros_like(p.data)
acc = state[‘accumulator’]
t = state[‘step’] + 1
state[‘step’] = t
if p.dim() > 1:
grad_squared = grad.square().mean(dim=0)
else:
grad_squared = grad.square()
beta_t = 1.0 - math.pow(t, -beta_decay)
acc.mul_(beta_t).add_(grad_squared, alpha=1-beta_t)
denom = acc.sqrt().add(eps)
grad_normalized = grad / denom if use_rms else grad
if momentum_beta > 0:
momentum_buffer = state[‘momentum_buffer’]
momentum_buffer.mul_(momentum_beta).add_(grad_normalized, alpha=1-momentum_beta)
grad_normalized = momentum_buffer
p.data.add_(grad_normalized, alpha=-lr)
return loss
Make it better. Im making optimiser both memory efficient and better than others out there. I have taken inpiration from SM3 and Adalite. You must know SM3, im giving you adalite code. Make necessary changes.
import torch
import math
from dataclasses import dataclass, field
from typing import List, Optional
from collections import defaultdict
# Somewhat based on https://gist.github.com/albanD/18c240bd2e09f9d93f5c4a0c9ccda39e and LOMO
@dataclass
class OverlapOptimizer:
model: torch.nn.Module
lr: Optional[float] = None
decay: Optional[float] = 0.0
acc_grads: Optional[List] = field(default_factory=lambda: [])
def init(self):
for p in self.model.parameters():
if p.requires_grad:
self.prepare§
self.hook§
def step(self, loss, lr):
pass
def hook(self, p):
pass
@dataclass
class OverlapSGD(OverlapOptimizer):
sign: bool = False
def prepare(self, p):
return
def step(self, loss, lr):
self.lr = lr
loss.backward()
def hook(self, p):
ag = p.view_as§.grad_fn.next_functions[0][0]
p.acc_grads = [ag]
@torch.no_grad()
def gf():
if self.sign:
p.add(p.grad.sign(), alpha=-self.lr)
else:
p.add_(p.grad, alpha=-self.lr)
p.grad = None
ag.register_hook(gf)
@dataclass
class Adalite(OverlapOptimizer):
eps: float = 1e-5
Lambda: float = 0.01 # Akin to weight-decay
beta_decay: float = 0.8
centralize: bool = True
use_rms: bool = True
momentum: bool = False
momentum_beta: float = 0.9
t: int = 0
def step(self, loss, lr=None):
self.t += 1
self.lr = lr
loss.backward()
def prepare(self, p):
if len(p.shape) == 2:
p.c = torch.zeros(p.shape[1], device=p.device, dtype=p.dtype)
else:
p.v = torch.zeros_like§
if self.momentum:
p.m = torch.zeros_like§
def hook(self, p):
ag = p.view_as§.grad_fn.next_functions[0][0]
p.acc_grads = [ag]
@torch.no_grad()
def gf():
alpha = self.lr
g = p.grad
if self.centralize and sum(g.shape) > 1:
g.sub(g.mean(dim=tuple(range(1, len(g.shape))), keepdim=True))
beta_t = 1.0 - math.pow(self.t, -self.beta_decay)
u = g.square()
if len(p.shape) == 2:
u.mul(1-beta_t).add(p.c.unsqueeze(0).broadcast_to(g.shape), alpha=beta_t)
u.add(self.eps)
p.c = u.mean(dim=0)
else:
u.mul(1-beta_t).add(p.v, alpha=beta_t)
u.add(self.eps)
p.v = u
m = u.rsqrt() * g
if self.use_rms:
m.div(max(1.0, m.square().mean().sqrt()))
p_norm = p.norm()
g_norm = g.norm()
if p_norm != 0 and g_norm != 0:
m.mul(p_norm / g_norm)
m.add(p - p/p_norm, alpha=self.Lambda)
if self.momentum:
p.m.mul(self.momentum_beta).add_(m, alpha=1-self.momentum_beta)
m = p.m
p.add(m, alpha=-alpha)
p.grad = None
ag.register_hook(gf)
To improve the Fusedbun optimizer by incorporating some ideas from the Adalite code, consider the following enhancements:
1. Centralize Gradient: Already implemented in Fusedbun, but it’s good to ensure it aligns with Adalite’s approach for consistency.
2. Gradient Clipping (RMS): This has been included, but to make it similar to Adalite, ensure to incorporate the logic where you divide the gradient by the max of 1.0 or the root-mean-square of the gradient, enhancing numerical stability.
3. Parameter Norm and Gradient Norm Ratio Scaling: This technique from Adalite can be particularly useful. It scales the normalized gradient by the ratio of parameter norm to gradient norm, which can help in maintaining the direction of the gradients while controlling their magnitude relative to the parameters’ magnitude.
4. Momentum with Condition: You already include momentum in Fusedbun. Adalite’s approach to conditionally apply momentum if enabled and then update the parameter with the momentum-adjusted gradient can be streamlined in your implementation.
5. Lambda for Weight Regularization: While Lambda is included in your defaults, its use is not explicitly seen in the step function. Adalite provides an explicit regularization term that decays the weights directly, acting similar to weight-decay but applied in a slightly different manner.
Below are modifications and incorporations from Adalite adapted to Fusedbun:
import torch
from torch.optim.optimizer import Optimizer
import math
class Fusedbun(Optimizer):
def init(self, params, lr=1e-3, eps=1e-8, beta_decay=0.8, Lambda=0.01, momentum_beta=0.9, centralize=True, use_rms=True):
defaults = dict(lr=lr, eps=eps, beta_decay=beta_decay, Lambda=Lambda, momentum_beta=momentum_beta, centralize=centralize, use_rms=use_rms)
super(Fusedbun, self).init(params, defaults)
@torch.no_grad()
def step(self, closure=None):
loss = None
if closure is not None:
loss = closure()
for group in self.param_groups:
lr = group[‘lr’]
eps = group[‘eps’]
beta_decay = group[‘beta_decay’]
Lambda = group[‘Lambda’]
momentum_beta = group[‘momentum_beta’]
centralize = group[‘centralize’]
use_rms = group[‘use_rms’]
for p in group[‘params’]:
if p.grad is None:
continue
grad = p.grad.data
if centralize and len(p.shape) > 1:
grad -= grad.mean(dim=tuple(range(1, len(grad.shape))), keepdim=True)
state = self.state[p]
if len(state) == 0:
state[‘step’] = 0
state[‘accumulator’] = torch.zeros_like(p.data)
if momentum_beta > 0:
state[‘momentum_buffer’] = torch.zeros_like(p.data)
acc = state[‘accumulator’]
t = state[‘step’] + 1
state[‘step’] = t
beta_t = 1.0 - math.pow(t, -beta_decay)
acc.mul_(beta_t).addcmul_(1-beta_t, grad, grad)
denom = acc.sqrt().add(eps)
grad_normalized = grad / denom if use_rms else grad
if use_rms:
grad_normalized /= max(1.0, grad_normalized.norm() / denom.norm())
if p.norm() != 0 and grad.norm() != 0:
grad_normalized *= p.norm() / grad.norm()
grad_normalized.add_(p, alpha=-Lambda) # Applying direct weight decay
if momentum_beta > 0:
momentum_buffer = state[‘momentum_buffer’]
momentum_buffer.mul_(momentum_beta).add_(grad_normalized, alpha=1-momentum_beta)
grad_normalized = momentum_buffer
p.data.add_(grad_normalized, alpha=-lr)
return loss
This integrates concepts from Adalite, focusing on incorporating momentum efficiently, applying RMS-based clipping if enabled, and scaling normalized gradients based on the parameter and gradient norms ratio. Further, it corrects the handling of Lambda for direct weight regularization. Adjustments like these can improve both the effectiveness and efficiency of the optimizer.
where have yu used lambda? also i dont want to use lambda implementation from adalite. i want to utilise it from some other optimiser. I want it to be a mix.
I see, if you’re looking to incorporate the parameter Lambda in a different way from how Adalite does and rather want to use it similarly to how other optimizers might apply a weight decay directly in the update step, let’s modify the approach. Specifically, we can treat Lambda as a weight decay parameter that directly scales down the weights before the gradient update, a common approach in various other optimizers like L2 regularization.
Here’s a revised version of the Fusedbun optimizer with Lambda being utilized as a direct weight decay factor in the update step. This approach is more aligned with traditional weight decay techniques seen in other optimizers:
import torch
from torch.optim.optimizer import Optimizer
import math
class Fusedbun(Optimizer):
def init(self, params, lr=1e-3, eps=1e-8, beta_decay=0.8, Lambda=0.01, momentum_beta=0.9, centralize=True, use_rms=True):
defaults = dict(lr=lr, eps=eps, beta_decay=beta_decay, Lambda=Lambda, momentum_beta=momentum_beta, centralize=centralize, use_rms=use_rms)
super(Fusedbun, self).init(params, defaults)
@torch.no_grad()
def step(self, closure=None):
loss = None
if closure is not None:
loss = closure()
for group in self.param_groups:
lr = group[‘lr’]
eps = group[‘eps’]
beta_decay = group[‘beta_decay’]
Lambda = group[‘Lambda’]
momentum_beta = group[‘momentum_beta’]
centralize = group[‘centralize’]
use_rms = group[‘use_rms’]
for p in group[‘params’]:
if p.grad is None:
continue
grad = p.grad.data
if centralize and len(p.shape) > 1:
grad -= grad.mean(dim=tuple(range(1, len(grad.shape))), keepdim=True)
state = self.state[p]
if len(state) == 0:
state[‘step’] = 0
state[‘accumulator’] = torch.zeros_like(p.data)
if momentum_beta > 0:
state[‘momentum_buffer’] = torch.zeros_like(p.data)
acc = state[‘accumulator’]
state[‘step’] += 1
t = state[‘step’]
beta_t = 1.0 - math.pow(t, -beta_decay)
acc.mul_(beta_t).addcmul_(grad, grad, value=1-beta_t)
denom = acc.sqrt().add_(eps)
grad_normalized = grad / denom if use_rms else grad
if momentum_beta > 0:
momentum_buffer = state[‘momentum_buffer’]
momentum_buffer.mul_(momentum_beta).add_(grad_normalized, alpha=1-momentum_beta)
grad_normalized = momentum_buffer
# Apply weight decay directly to weights
if Lambda != 0:
grad_normalized.add_(p.data, alpha=-Lambda)
p.data.add_(grad_normalized, alpha=-lr)
return loss
In this version, the Lambda parameter is utilized directly to perform a weight decay operation on parameters before updating them. This technique is more aligned with conventional weight decay methods, where parameters are directly scaled down by a factor before applying the gradient update. It is different from Adalite’s approach where Lambda was used in a somewhat different context. This should effectively bring the regularization aspect into your optimizer, making it a blend of features from different optimizers, as per your demand.
i dont think this is nice.
I understand your concern and appreciate your honesty. Let’s refine the approach further to ensure the Lambda parameter (acting as weight decay) is effectively utilized alongside the unique features you’re aiming to incorporate from diverse optimizers. We want to blend these efficiently without directly replicating any single optimizer’s approach to Lambda.
Weight decay, also known as L2 regularization, is commonly applied in optimization algorithms to prevent overfitting by penalizing large weights. The typical way to apply weight decay is to shrink the weights directly by a small factor during each update. Given your goal to innovate beyond the standard implementations, one idea could be to adaptively adjust the weight decay based on some criteria, inspired by how adaptive optimizers adjust their learning rates.
Here’s how you might adjust the usage of Lambda to offer a more nuanced approach:
1. Scale Lambda Based on Gradients: Instead of using a fixed Lambda for all parameters, you could adjust Lambda based on the gradients’ magnitudes. This way, parameters with larger gradients could potentially be regularized more heavily, countering the rapid changes they impose on the model.
2. Incorporate Lambda into State: Treat Lambda not as a static parameter but as something that evolves based on the optimization process, much like other stateful aspects of the optimizer like momentum or adaptive learning rates.
3. Utilize Lambda in Conjunction with Accumulated Gradients: Advanced optimizers keep track of past gradients in various ways (e.g., RMSprop, Adam). Lambda could be used to modulate the influence of these accumulated gradients, offering a pathway to dynamically adjust the step size based on both the history and the regularization strength.
Let’s sketch out how these ideas might be concretely implemented within your framework:
import torch
from torch.optim.optimizer import Optimizer
import math
class Fusedbun(Optimizer):
def init(self, params, lr=1e-3, eps=1e-8, beta_decay=0.8, Lambda=0.01, momentum_beta=0.9, centralize=True, use_rms=True):
defaults = dict(lr=lr, eps=eps, beta_decay=beta_decay, Lambda=Lambda, momentum_beta=momentum_beta, centralize=centralize, use_rms=use_rms)
super(Fusedbun, self).init(params, defaults)
@torch.no_grad()
def step(self, closure=None):
loss = None
if closure is not None:
loss = closure()
for group in self.param_groups:
lr = group[‘lr’]
eps = group[‘eps’]
beta_decay = group[‘beta_decay’]
base_lambda = group[‘Lambda’]
momentum_beta = group[‘momentum_beta’]
centralize = group[‘centralize’]
use_rms = group[‘use_rms’]
for p in group[‘params’]:
if p.grad is None:
continue
grad = p.grad.data
if centralize and len(p.shape) > 1:
grad -= grad.mean(dim=tuple(range(1, len(grad.shape))), keepdim=True)
state = self.state[p]
if ‘step’ not in state:
state[‘step’] = 0
state[‘accumulator’] = torch.zeros_like(p.data)
state[‘Lambda’] = base_lambda # Initialize adaptive Lambda in state
if momentum_beta > 0:
state[‘momentum_buffer’] = torch.zeros_like(p.data)
acc = state[‘accumulator’]
state[‘step’] += 1
t = state[‘step’]
beta_t = 1.0 - math.pow(t, -beta_decay)
acc.mul_(beta_t).addcmul_(grad, grad, value=1-beta_t)
denom = acc.sqrt().add_(eps)
grad_normalized = grad / denom if use_rms else grad
# Dynamic Lambda adjustment
adaptive_lambda = state[‘Lambda’] * grad.abs().mean()
if momentum_beta > 0:
momentum_buffer = state[‘momentum_buffer’]
momentum_buffer.mul_(momentum_beta).add_(grad_normalized, alpha=1-momentum_beta)
grad_normalized = momentum_buffer
# Apply adaptive weight decay based on modified Lambda
p.data.mul_(1 - lr * adaptive_lambda)
p.data.add_(grad_normalized, alpha=-lr)
return loss
In this version, Lambda is initially treated as a base value that gets adapted based on the mean absolute value of the gradients, theoretically allowing for weight decay that’s responsive to the optimization process’s dynamics. This approach is speculative and intended to inspire ways to innovate within the constraints of optimizer design while remaining grounded in principles that ensure generalization and training stability.
REvert changes. This will be used to finetune large language models. Consider that and either remove it or use SM3 and adalite to fix it
Understood. Given the focus on fine-tuning large language models and the inspiration from both SM3 and Adalite, let’s tailor the optimizer to fit this specific use case more appropriately. We assume high efficiency and memory optimization are key due to the large parameter space of such models. Additionally, the importance of managing the balance between exploration (via momentum) and exploitation (via adaptive learning rates and weight decay) must be considered.
Here’s how we can revise the Fusedbun optimizer by carefully incorporating ideas from SM3 and Adalite, without the previously mentioned dynamic Lambda approach, to ensure it’s more suited for fine-tuning large language models:
1. Memory Efficiency: We’ll ensure that our state variables (like accumulators and momentum buffers) are as memory-efficient as possible, drawing inspiration from SM3.
2. Adaptive Learning with Momentum: We’ll keep the momentum logic for exploratory updates but ensure that the adaptive learning mechanism from something akin to Adalite’s handling (or RMSprop/Adam) is well integrated.
3. Weight Decay: Given the context now focuses on fine-tuning large models, and considering your feedback, we will retain a simple, predictable form of weight decay, aligning it more closely to standard practices.
4. Ensure the Lambda parameter efficiently applies a consistent form of weight decay suitable for large models, avoiding dynamic adjustments for simplicity and predictability.
Considering these aspects, let’s refine the optimizer:
import torch
from torch.optim.optimizer import Optimizer
import math
class Fusedbun(Optimizer):
def init(self, params, lr=1e-3, eps=1e-8, beta_decay=0.8, Lambda=0.01, momentum_beta=0.9, centralize=False, use_rms=True):
defaults = dict(lr=lr, eps=eps, beta_decay=beta_decay, Lambda=Lambda, momentum_beta=momentum_beta, centralize=centralize, use_rms=use_rms)
super(Fusedbun, self).init(params, defaults)
@torch.no_grad()
def step(self, closure=None):
loss = None
if closure is not None:
with torch.enable_grad():
loss = closure()
for group in self.param_groups:
lr = group[‘lr’]
eps = group[‘eps’]
Lambda = group[‘Lambda’]
momentum_beta = group[‘momentum_beta’]
use_rms = group[‘use_rms’]
for p in group[‘params’]:
if p.grad is None:
continue
grad = p.grad.data
if group[‘centralize’] and len(p.shape) > 1:
grad = grad - grad.mean(dim=tuple(range(1, len(grad.shape))), keepdim=True)
state = self.state[p]
# State initialization
if len(state) == 0:
state[‘step’] = 0
state[‘exp_avg_sq’] = torch.zeros_like(p, memory_format=torch.preserve_format)
if momentum_beta > 0:
state[‘momentum_buffer’] = torch.zeros_like(p, memory_format=torch.preserve_format)
exp_avg_sq = state[‘exp_avg_sq’]
state[‘step’] += 1
beta_decay = 1.0 - math.pow(state[‘step’], -group[‘beta_decay’])
# SM3-like sparse update for memory efficiency
if p.dim() > 1:
dim = grad.square().mean().item()
exp_avg_sq.add_(dim - exp_avg_sq, alpha=beta_decay)
else:
exp_avg_sq.mul_(beta_decay).addcmul_(grad, grad, value=1 - beta_decay)
denom = exp_avg_sq.sqrt().add_(eps)
if momentum_beta > 0:
momentum_buffer = state[‘momentum_buffer’]
momentum_buffer.mul_(momentum_beta).addcdiv_(grad, denom, value=1 - momentum_beta)
step_size = -lr * momentum_buffer
else:
step_size = -lr * grad / denom
# Applying weight decay (if Lambda is not 0
Lambda directly before the parameter update step to ensure it works similarly across various optimizers, let’s make the adjustment where Lambda is used for a straightforward weight decay effect. Considering the focus on large language models where stability and predictability can be crucial, a more conservative application of Lambda—directly scaling down weights by a minimal factor—makes more sense:
import torch
from torch.optim.optimizer import Optimizer
import math
class Fusedbun(Optimizer):
def init(self, params, lr=1e-3, eps=1e-8, beta_decay=0.8, Lambda=0.01, momentum_beta=0.9, centralize=False, use_rms=True):
defaults = dict(lr=lr, eps=eps, beta_decay=beta_decay, Lambda=Lambda, momentum_beta=momentum_beta, centralize=centralize, use_rms=use_rms)
super(Fusedbun, self).init(params, defaults)
@torch.no_grad()
def step(self, closure=None):
loss = None
if closure is not None:
with torch.enable_grad():
loss = closure()
for group in self.param_groups:
lr = group[‘lr’]
eps = group[‘eps’]
Lambda = group[‘Lambda’]
momentum_beta = group[‘momentum_beta’]
use_rms = group[‘use_rms’]
for p in group[‘params’]:
if p.grad is None:
continue
grad = p.grad.data
if group[‘centralize’] and len(p.shape) > 1:
grad = grad - grad.mean(dim=tuple(range(1, len(grad.shape))), keepdim=True)
state = self.state[p]
# State initialization
if len(state) == 0:
state[‘step’] = 0
state[‘exp_avg_sq’] = torch.zeros_like(p, memory_format=torch.preserve_format)
if momentum_beta > 0:
state[‘momentum_buffer’] = torch.zeros_like(p, memory_format=torch.preserve_format)
exp_avg_sq = state[‘exp_avg_sq’]
state[‘step’] += 1
beta_decay = 1.0 - math.pow(state[‘step’], -group[‘beta_decay’])
# Efficient squared gradient accumulation
exp_avg_sq.mul_(beta_decay).addcmul_(grad, grad, value=1 - beta_decay)
denom = exp_avg_sq.sqrt().add_(eps)
if momentum_beta > 0:
momentum_buffer = state[‘momentum_buffer’]
momentum_buffer.mul_(momentum_beta).addcdiv_(grad, denom, value=1 - momentum_beta)
step_size = -lr * momentum_buffer
else:
step_size = -lr * grad / denom
# Applying weight decay (if Lambda is not 0)
if Lambda != 0:
p.data.mul_(1 - lr * Lambda)
p.data.add_(step_size)
return loss
This final iteration takes into account:
- Lambda for Weight Decay: Consistently applies Lambda as a factor for weight decay, scaling down weights directly before the update. This straightforward approach is effective for managing model complexity and preventing overfitting, especially relevant in fine-tuning scenarios where preserving the pre-trained features is important.
- Memory Efficiency: By only storing necessary state variables without introducing complex, dynamic Lambda adjustments, it remains memory-efficient, crucial for handling large models.
- Adaptive Learning and Momentum: Balances the benefits of adaptive learning rates with momentum, ensuring that updates are both exploratory and grounded in recent gradients, tailored for effective fine-tuning.
This design considers the critical elements of fine-tuning large language models, balancing efficiency, and effectiveness without overcomplicating the weight decay mechanism.
Ok compare to SM3, adalite and other optimizers, tell me what benefits this have, if any? also tell me what are the current changes compared to originakl
Comparing the proposed Fusedbun optimizer with established optimizers like SM3 and Adalite, along with other common optimizers such as SGD, Adam, etc., here are some potential benefits and changes from the original implementation you provided and how it stands against others:
### Fusedbun vs. SM3
- Memory Efficiency: SM3 is designed for memory efficiency, particularly useful for sparse data. Fusedbun, while not explicitly designed like SM3 for sparse updates, incorporates adaptive gradient accumulation (akin to RMSprop or Adam) that can be applied more generally to different types of data (sparse or dense). The efficiency in Fusedbun comes from carefully managing state variables to avoid unnecessary memory usage.
- Adaptivity: Fusedbun employs adaptive mechanisms similar to those in Adam or RMSprop, providing potential benefits over SM3 when dealing with dense data and complex optimization landscapes by adjusting learning rates based on the magnitude of recent gradients.
### Fusedbun vs. Adalite
- Centralization and Weight Decay: Both optimizers can centralize gradients and apply weight decay, but Fusedbun takes a slightly different approach by incorporating these functionalities directly within the optimizer’s step function, making it easier to modify or extend these behaviors.
- Adaptive Weight Decay: While not originally exploited in your modifications, Fusedbun had the potential for dynamically adjusting Lambda based on gradient magnitudes, offering flexibility in regularizing parameters more aggressively where gradients are larger. However, based on your feedback, this was simplified to use a straightforward weight decay approach for stability in fine-tuning large models.
### General Benefits
- Flexibility: Fusedbun is designed with flexibility in mind, incorporating features like gradient centralization and RMS-based gradient clipping directly into the optimizer. This makes it inherently more adaptable to various types of models and training scenarios, especially when fine-tuning where subtle adjustments to the optimization process can have significant impacts.
- Simplicity and Predictability: By reverting to a more stable and predictable form of weight decay, Fusedbun offers a balance between innovation and the proven reliability of traditional techniques, making it potentially more suitable for fine-tuning large pre-trained models where maintaining pre-learned representations is crucial.
### Changes from the Original
- Removal of Dynamic Lambda Adjustment: Initially considered dynamic Lambda adjustments for an innovative approach to weight decay, this was removed for simplicity and predictability, aligning more closely with established practices beneficial for fine-tuning scenarios.
- Streamlined State Management: Streamlining how state variables are initialized and managed within Fusedbun improves clarity and efficiency, ensuring the optimizer’s memory footprint remains controlled, which is crucial when working with large models.
- Incorporation of Gradient Centralization and RMS-based Clipping: These features were adjusted or highlighted to emphasize their roles in the optimizer’s functionality, ensuring that their integration supports the optimizer’s efficiency and efficacy in fine-tuning tasks.
In summary, Fusedbun attempts to blend desirable features from various optimizers into a singular, flexible framework that could offer particular advantages in fine-tuning large language models. Its design prioritizes adaptability, efficiency, and the balance between innovation and proven optimization strategies, aiming to provide a robust tool for specific tasks rather than a universally superior optimizer.
REwrite the code with detailed comments of what each section do.
Below is the revised code for the Fusedbun optimizer with detailed comments explaining each section of the code. This version aims for clarity and understanding of how each part contributes to the overall optimization process, making it suitable for fine-tuning large models while balancing flexibility, efficiency, and simplicity.
import torch
from torch.optim.optimizer import Optimizer
import math
class Fusedbun(Optimizer):
def init(self, params, lr=1e-3, eps=1e-8, beta_decay=0.8, Lambda=0.01, momentum_beta=0.9, centralize=False, use_rms=True):
# Initialize optimizer parameters:
# lr: Learning rate controls the step size at each iteration.
# eps: A small value added to the denominator for numerical stability.
# beta_decay: A parameter controlling the rate of decay for the moving average of squared gradients.
# Lambda: Coefficient for L2 regularization (weight decay).
# momentum_beta: Coefficient for the moving average of gradients (momentum).
# centralize: Boolean indicating whether to centralize gradients to have zero mean.
# use_rms: Boolean indicating whether to use RMSprop-like denominator normalization.
defaults = dict(lr=lr, eps=eps, beta_decay=beta_decay, Lambda=Lambda, momentum_beta=momentum_beta, centralize=centralize, use_rms=use_rms)
super(Fusedbun, self).init(params, defaults)
@torch.no_grad() # This context manager disables gradient computation, reduces memory consumption and computation.
def step(self, closure=None):
# Performs a single optimization step (parameter update).
loss = None
if closure is not None:
# If a closure is provided, compute the loss. Useful for some optimization strategies.
with torch.enable_grad():
loss = closure()
for group in self.param_groups:
# Iterate over optimization parameter groups (allows for different params to have different hyperparams).
lr = group[‘lr’]
eps = group[‘eps’]
Lambda = group[‘Lambda’]
momentum_beta = group[‘momentum_beta’]
use_rms = group[‘use_rms’]
for p in group[‘params’]:
# Iterate over each parameter in the parameter group.
if p.grad is None:
continue # Skip parameters without gradients.
grad = p.grad.data
if group[‘centralize’] and len(p.shape) > 1:
# Centralize gradients for non-scalar parameters if centralization is enabled.
grad = grad - grad.mean(dim=tuple(range(1, len(grad.shape))), keepdim=True)
# Retrieve or initialize state for this parameter.
state = self.state[p]
# State initialization for the first step.
if len(state) == 0:
state[‘step’] = 0
state[‘exp_avg_sq’] = torch.zeros_like(p, memory_format=torch.preserve_format)
if momentum_beta > 0:
# Only allocate momentum buffer if momentum is used.
state[‘momentum_buffer’] = torch.zeros_like(p, memory_format=torch.preserve_format)
exp_avg_sq = state[‘exp_avg_sq’]
# Increment optimization step counter.
state[‘step’] += 1
# Adjust beta_decay dynamically based on step number if needed.
beta_decay = 1.0 - math.pow(state[‘step’], -group[‘beta_decay’])
# Update exponential average of squared gradients.
exp_avg_sq.mul_(beta_decay).addcmul_(grad, grad, value=1 - beta_decay)
denom = exp_avg_sq.sqrt().add_(eps)
if momentum_beta > 0:
# Momentum update if momentum is enabled.
momentum_buffer = state[‘momentum_buffer’]
momentum_buffer.mul_(momentum_beta).addcdiv_(grad, denom, value=1 - momentum_beta)
step_size = -lr * momentum_buffer
else:
# No momentum; use the normalized gradient for the update.
step_size = -lr * grad / denom
# Apply L2 regularization (weight decay) if Lambda is not zero.
if Lambda != 0:
p.data.mul_(1 - lr * Lambda)
# Apply the update to the parameter.
p.data.add_(step_size)
return loss
This detailed walkthrough explains the roles of various components within the Fusedbun optimizer. The optimizer supports functionalities like RMSprop-like adaptive learning rates, L2 regularization (weight decay), gradient centralization, and optional momentum, making it adaptable for a wide range of tasks, particularly in fine-tuning where such nuanced control over the optimization process can be crucial.
Why L2? isint it too old to use it with LLMs?
The question of whether L2 regularization (weight decay) is too old to use with large language models (LLMs) touches on a broader discussion about the relevance of traditional machine learning techniques in modern deep learning frameworks. While it’s true that L2 regularization is a long-standing technique, its usefulness and applicability extend to contemporary models, including LLMs, for several reasons:
1. Generalization: One of the primary reasons for using regularization techniques like L2 is to improve the generalization of a model to unseen data. L2 regularization achieves this by penalizing large weights, encouraging the model to maintain smaller weight values. This penalty helps prevent the model from fitting too closely to the training data (overfitting), which is a concern regardless of model size.
2. Simplicity and Effectiveness: Despite being a straightforward approach, L2 regularization remains effective for numerous tasks. It introduces an additional hyperparameter (the weight decay factor) that can be tuned to balance the trade-off between model complexity and training data fitness. This simplicity offers a clear path to mitigate overfitting without introducing significant computational overhead or complexity into the training process.
3. Complementary to Other Techniques: In the context of LLMs and deep learning in general, L2 regularization is often used alongside other techniques designed to improve model performance and generalization, such as dropout, batch normalization, and more complex regularization methods. This multi-pronged approach to regularization allows practitioners to leverage the strengths of various techniques to achieve better outcomes.
4. Theoretical and Practical Foundations: The use of L2 regularization is supported by both theoretical insights into the geometry of optimization landscapes and practical evidence from empirical experimentation. It helps in smoothing the optimization landscape, making it easier for gradient-based optimizers to find minima that generalize well.
5. Transfer Learning and Fine-tuning: In scenarios involving transfer learning and fine-tuning of pre-trained models, including LLMs, L2 regularization can be particularly useful. It helps in gently steering the fine-tuning process, limiting the extent to which weights can deviate from their pre-trained values. This is especially important when the fine-tuning dataset is much smaller than the pre-training corpus, as is often the case with LLMs.
While newer and more sophisticated regularization and optimization techniques have been developed, L2 regularization’s merits keep it relevant in the modern deep learning toolkit, including its application to LLMs. Its continued use is a testament to its fundamental utility in controlling model complexity and aiding generalization, rather than an indication of the field’s stagnation. That being said, the choice of regularization techniques should always be informed by the specific characteristics of the model, data, and task at hand, with an understanding that no single method is universally optimal.
OK not tell me what part of code was taken from which optimizer. Also write a blog about it. Telling me why we made this. how we made it(must include technical details of how it works) and what it is in conclusion
The Fusedbun optimizer, as conceived and developed in our discussion, is inspired by a blend of concepts from various leading optimizers, each bringing specific strengths to address the challenges of training large language models (LLMs). Below, I outline the components derived from these optimizers and then present a structured blog post discussing the rationale, development, and essence of Fusedbun.
### Inspirations from Existing Optimizers:
1. Momentum (SGD with Momentum): The momentum update mechanism in Fusedbun is inspired by classical SGD with momentum. It helps accelerate the optimizer in relevant directions and dampens oscillations.
2. Adaptive Gradient Accumulation (RMSprop/Adam): The use of squared gradients to adaptively adjust the learning rate for each parameter, similar to RMSprop and further popularized by Adam, aims to offer more nuanced step sizes that are informed by the recent history of gradients.
3. Weight Decay (L2 Regularization): Fusedbun incorporates simple weight decay directly into its update rule, a regularization strategy with roots in classical optimization techniques and adopted by various optimizers, including L2 regularization in SGD and the decoupled weight decay in optimizers like AdamW.
4. Gradient Centralization: This feature, which involves normalizing gradients to have zero mean, is inspired by more recent insights into deep learning optimization, particularly research into gradient centralization’s impact on stabilizing and speeding up training.
5. Epsilon for Numerical Stability (Adam): The inclusion of a small constant, epsilon, in the denominator of the update rule to prevent division by zero is a technique employed by Adam and similar optimizers to enhance numerical stability.
### Blog Post: Introducing Fusedbun - A Hybrid Optimizer for Large Language Models
#### Why We Made Fusedbun
In the fast-evolving landscape of deep learning, training large language models (LLMs) presents unique challenges. These models, characterized by their vast number of parameters and deep architectures, demand optimization strategies that balance speed, stability, and the capacity to navigate complex loss landscapes. Traditional optimizers, while foundational, often fall short in addressing these needs comprehensively.
Enter Fusedbun—a hybrid optimizer designed to harness the strengths of various optimization techniques. Our goal was to create an optimizer that adapts to the intricacies of large-scale models without sacrificing efficiency or requiring exhaustive hyperparameter tuning.
#### How We Made It: The Technical Essence
Fusedbun is rooted in a blend of tried-and-tested optimization principles, each selected for its proven benefits:
- Momentum: Borrowed from the classic SGD with momentum, this feature provides Fusedbun with the ability to sustain movement in productive directions across iterations, reducing the risk of stagnation in suboptimal regions.
- Adaptive Learning Rates: Drawing from RMSprop and Adam, Fusedbun adjusts the learning rate for each parameter based on the history of its gradients. This adaptiveness helps in scaling the updates appropriately, ensuring neither too large nor too small steps are taken.
- Weight Decay: Integrating direct weight decay into the update step imbues Fusedbun with a straightforward regularization mechanism, encouraging simpler models that are less prone to overfitting.
- Gradient Centralization: By centralizing gradients, Fusedbun aims to achieve faster convergence and improved stability, a technique shown to be beneficial in recent deep learning research.
- Numerical Stability: Like Adam, Fusedbun employs an epsilon term to maintain numerical stability, ensuring the model remains robust against potential computational anomalies.
Together, these components are woven into a cohesive optimization strategy tailored for the complexities of LLMs. The implementation ensures that while each parameter’s update is informed by its own gradient history and the model’s overall adjustment trajectory, regularization keeps the model grounded, preventing overfitting.
#### Conclusion: What Fusedbun Is
Fusedbun stands as a testament to the adaptive, nuanced approach required for modern deep learning challenges. It’s not just an optimizer; it’s a synthesis of learning from the lineage of optimization research, tailored for the demands of today’s LLMs. By integrating the strengths of multiple optimization philosophies, Fusedbun aspires to offer a balanced tool—capable of guiding large models to effective convergence with stability and efficiency.
In the ever-progressing quest to train more sophisticated models, Fusedbun represents a step towards acknowledging and amalgamating the richness of existing optimization strategies, paving the way for more informed and flexible approaches to learning at scale.
BUt earlier it was more like SM3 and adalite only
You’re right; in the earlier discussion, the Fusedbun optimizer was specifically mentioned to take inspiration from SM3 and Adalite, emphasizing a blend that prefers certain aspects from each. Let me correct the oversight and focus more precisely on how Fusedbun takes cues from these two and the unique aspects it inherits or adapts from them, culminating in a blog-style explanation.
### Inspiration from SM3 and Adalite:
SM3: This optimizer is known for its memory-efficient handling of the gradients, especially valuable for training models with vast parameter spaces. SM3’s key feature is its sparse update mechanism, which selectively updates parameters, significantly reducing memory requirements.
Adalite: While not a widely recognized optimizer in the mainstream like Adam or SGD, for the sake of our discussion, let’s assume Adalite brings innovative features such as adaptive learning rates based on parameter-wise gradient magnitudes and a nuanced approach to regularization and centralization.
### How Fusedbun Merges Concepts from SM3 and Adalite:
- Memory Efficiency from SM3: Fusedbun adopts a strategy to manage gradient accumulation and updates efficiently, minimizing the optimizer’s memory footprint. This aspect is crucial for scaling to large language models without overwhelming memory resources.
- Adaptive Learning Rates Inspired by Adalite: Like Adalite, Fusedbun utilizes adaptive learning rates that adjust according to the historical gradient information, but it streamlines this process to ensure robustness and stability across varied training scenarios.
- Centralization and Regularization: Borrowing from Adalite’s approach, Fusedbun includes gradient centralization for stability and enhanced convergence, coupled with a direct form of weight decay for straightforward regularization. This combination aims to balance the model’s training efficiency with its generalization capabilities.
### Blog Post: Crafting Fusedbun - A Synergistic Optimizer for Next-Gen Models
#### The Genesis of Fusedbun
In the quest to optimize large language models, the challenge has always been to marry the need for memory efficiency with the demand for adaptive, nuanced training strategies. Drawing from the strengths of SM3 and Adalite, Fusedbun was conceptualized as a hybrid optimizer that leverages the best of both worlds—offering a solution tailored for the complex needs of next-generation models.
#### The Mechanics Behind Fusedbun
Fusedbun’s architecture is a blend of carefully selected features aimed at addressing the core challenges in training large models:
- Efficient Memory Usage: Inspired by SM3, Fusedbun implements a memory-conscious approach to gradient accumulation, ensuring that large models can be trained on hardware with finite memory capabilities.
- Adaptive Learning: By integrating a variant of adaptive learning rate mechanisms, akin to those proposed in Adalite, Fusedbun allows for parameter updates that are sensitive to the magnitude and history of gradients, facilitating a more refined optimization process.
- Stability and Regularization: Fusedbun incorporates gradient centralization for improved training dynamics and employs straightforward weight decay as a form of L2 regularization, a nod to traditional techniques proven effective across various model sizes and complexities.
#### In Conclusion: Fusedbun’s Place in the Optimizer Pantheon
Fusedbun represents an innovative step in the evolution of optimization strategies for deep learning. By synergistically combining memory efficiency, adaptive learning, and proven regularization techniques, it offers a robust tool designed to meet the unique demands of training large language models. It stands as a bridge between the computational efficiency of SM3 and the adaptive finesse of Adalite, providing practitioners with an optimizer that does not compromise on efficiency or effectiveness.
As models continue to grow in size and complexity, Fusedbun aims to be at the forefront—empowering researchers and engineers to push the boundaries of what’s possible in machine learning and AI.
This focused exploration and subsequent explanation offer a clearer perspective on how Fusedbun is distinctively positioned, drawing foundational elements from SM3 and Adalite while striving to address the optimization challenges of contemporary large-scale models.
Revert changes if the changes that were made is outside SM3 and adalite. I only need mix of these two and not others.
Based on the requirement to strictly adhere to the inspirations from SM3 and Adalite, let’s refine the narrative around the development of Fusedbun, focusing exclusively on features and characteristics these two optimizers offer. We will eliminate references to features explicitly associated with other optimizers and ensure that Fusedbun is depicted as a direct hybrid of SM3 and Adalite, without external influences.
### Fusedbun: A Hybrid Optimizer Born from SM3 and Adalite
Fusedbun emerges as a specialized optimizer, uniquely architected for the demands of large language models (LLMs) by combining the strengths of SM3 and Adalite. Its creation is motivated by the need for an optimizer that marries the memory efficiency of SM3 with the adaptive learning strategies found in Adalite, without stepping into the territories of other popular optimizers like Adam or SGD.
#### Drawing from SM3
SM3’s hallmark is its memory efficiency, particularly advantageous for handling models with large numbers of parameters. Fusedbun inherits this trait by implementing a similar mechanism for gradient storage and update, focusing on minimizing memory overhead during training.
#### Incorporating Elements from Adalite
Adalite’s approach to adaptive learning rates—where adjustments are made based on the observed behavior of gradients—offers a path to nuanced parameter updates. Fusedbun adopts this approach, ensuring that each parameter’s learning rate is tuned according to its specific needs, promoting a balanced and effective optimization process.
### Development Journey of Fusedbun: A Technical Insight
The creation of Fusedbun involved careful integration of key features from SM3 and Adalite, ensuring each component harmonizes with the others to produce an optimizer that is more than the sum of its parts. The following technical decisions were pivotal:
- Memory-Efficient Gradient Handling: Drawing directly from SM3, Fusedbun optimizes its gradient storage and computation, ensuring it operates efficiently even when tasked with optimizing models having millions of parameters.
- Adaptive Learning Rate Mechanism: Fusedbun incorporates a learning rate adjustment mechanism inspired by Adalite, allowing it to dynamically modify learning rates based on the magnitude and variability of each parameter’s gradients over time.
- Gradient Centralization (as influenced by Adalite): While emphasizing the centrality of gradients for enhanced stability and convergence, Fusedbun integrates this principle into its operations, promoting a more disciplined and focused optimization path.
### In Conclusion: The Essence of Fusedbun
Fusedbun stands as a testament to innovative synergy, crafted for the next generation of machine learning challenges. By solely leveraging the best practices from SM3 and Adalite, it represents a dedicated effort to provide a memory-efficient, adaptively tuned optimization solution for training large language models.
In its essence, Fusedbun is not merely an optimizer; it’s a strategic convergence of two pioneering optimization philosophies, meticulously designed to meet the nuanced demands of modern AI research and application. Its development underscores a commitment to pushing the boundaries of what’s achievable, facilitating the exploration of new horizons in machine learning and beyond.
This constrained focus ensures that Fusedbun is accurately represented as a product of SM3’s memory strategies and Adalite’s adaptive learning principles, exclusively blending these inspirations without borrowing from the broader spectrum of optimization techniques.
only write code for fusedbun based strictly on sm3 and adalite considering the above. Write comments of what codeblock do and where it’s taken from (sm3/adalite)
|
7abc619803fa969fa488aa8aef60c628
|
{
"intermediate": 0.3776407539844513,
"beginner": 0.39133796095848083,
"expert": 0.23102131485939026
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.